Install & config Apache, MySQL and PHP on your Mac (MAMP)


There’s a Mac computer that I want to use as local development server for web apps. I don’t want to use bundled installers like XAMPP or MAMP because I feel that I will learn more about Apache if I install each component of the LAMP stack separately. By the way, one of my goals is to be an expert in the LAMP stack. And prior to writing this blog entry, I had only been concerned about the actual coding of web apps, and have never had the chance or need to play with the installation and configuration of Linux, Apache, MySQL and PHP as individual components since there’s always been XAMPP and MAMP for easy setup in my local environment. And at work, someone else is always in charge of setting up our Linux server and the rest of the things we need for our production environment.

I also plan to setup a LAMP environment on my Mac by using VirtualBox to create a virtual machine with Linux, but I’m saving that for another post if it happens. 😆

Here in this blog entry, I shall take note of the steps that I take as I setup Apache, MySQL and PHP on Mac.

My environment

Computer: MacBook Pro
Operating System: OS X El Capitan version 10.11.5
I’ll be using the Terminal and Vim editor

Apache, MySQL, and PHP versions that I will setup:

Apache: version 2.4.18 (bundled with El Capitan, default)
MySQL: version 5.7.15 (installed via Homebrew)
PHP: version 5.5.34 (bundled with El Capitan, default)

I have no MAMP, XAMPP or any bundled *AMP stack installed on my Mac, so I will have fresh install of MySQL.

Start Apache on your Mac

Apache is already in OS X El Capitan so I just need to set it up. If you want to check your Apache version, run the command httpd -v in Terminal. Mine is Apache version 2.4.18.

Mac:apache2 toncatzu$ httpd -v
Server version: Apache/2.4.18 (Unix)
Server built:   Feb 20 2016 20:03:19

Type this command in Terminal to start Apache on your Mac:

sudo apachectl start

Now that we started Apache, you should now be able to access the URL http://localhost/.

Start PHP on your Mac

Maybe you expected this section to be for MySQL setup, but I’m going to work with PHP first since it should be already in OS X El Capitan, like Apache.

Also, as of writing, the latest PHP version is 7 but I want to take one little step at a time as I write this so I’ll stick with the PHP 5 bundled with my Mac. I will try to post another blog entry on how to upgrade from PHP 5 to PHP 7. 🙂

We are going to edit the Apache configuration file to enable PHP on Mac, but for now let’s make a back up of the file. Let’s do that by running these commands:

cd /etc/apache2 #navigate to the apache2 folder
sudo cp httpd.conf http.conf.20160910.bak #copy httpd.conf file into httpd.conf.20160910.bak

Notice the 20160910 in the command sudo cp httpd.conf http.conf.20160910.bak. It’s the date when I made a backup. You may change the date or even delete it.

Open Vim to edit httpd.conf by running this command:

sudo vim httpd.conf

Find the following line in httpd.conf and uncomment it:

LoadModule php5_module libexec/apache2/libphp5.so

Remove the hash symbol (#) at the beginning of that line to uncomment it.

Vim editor tip: when you open the httpd.conf file, search for the line containing “php5_module” by pressing the esc key to make sure you’re not in INSERT mode, then type /php5_module and then hit the return/enter key. Vim should point you to the line that you should uncomment. Press the “i” key to enter INSERT mode in Vim, and uncomment that line. To save the file, press esc key again and type :wq!

Now, restart Apache to reflect the change:

sudo apachectl restart

Check if PHP works

Run these commands:

cd /Library/WebServer/Documents
sudo vim temp_phpinfo.php

Press the “i” key to enter INSERT mode again, then place this PHP code into temp_phpinfo.php:

<?php

phpinfo();

Then using your web browser, go to http://localhost/temp_phpinfo.php

If the page shows a table of details about PHP, then PHP now works on your Mac. Good job! 🙂

I recommend that you delete this temp_phpinfo.php file though, and avoid using phpinfo() especially in production servers because it can lead to security issues. It will be easier for attackers to hack into your system when they see all the details that phpinfo() exposes.

Install MySQL

Install Homebrew if you haven’t yet. I choose to install MySQL with Homebrew because I find the process simple.

Run this command to install MySQL via Homebrew:

brew install mysql

The installation process on my Mac looked like this:

Mac:local toncatzu$ brew install mysql
==> Installing dependencies for mysql: openssl
==> Installing mysql dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2h_1.el_capitan
######################################################################## 100.0%
==> Pouring openssl-1.0.2h_1.el_capitan.bottle.tar.gz
==> Using the sandbox
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
?  /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12M
==> Installing mysql
==> Downloading https://homebrew.bintray.com/bottles/mysql-5.7.15.el_capitan.bot
######################################################################## 100.0%
==> Pouring mysql-5.7.15.el_capitan.bottle.tar.gz
==> /usr/local/Cellar/mysql/5.7.15/bin/mysqld --initialize-insecure --user=[...]
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

To connect run:
    mysql -uroot

To have launchd start mysql now and restart at login:
  brew services start mysql
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Summary
?  /usr/local/Cellar/mysql/5.7.15: 13,510 files, 445.9M

By default, Homebrew installs MySQL without root password, and with this setup, you can now log into MySQL by typing:

mysql -uroot

But wait! Securing MySQL with a password is highly recommended, and if you agree, run this command:

mysql_secure_installation

With a password for root set, you should access MySQL with this command instead, adding a -p to the command for a password prompt:

mysql -uroot -p

MySQL command line on a Mac Mini with MAMP bundle installed

The Mac Mini I’m using at work already has MAMP installed, but I followed the steps for setting up Apache, MySQL and PHP in this page just to test. Since MAMP is already installed, I already have MySQL.

So, before using MySQL via command line, simply start your MySQL server from MAMP and then use command line MySQL by logging in like this:

mysql -uroot -p

Create sample database table for testing with PHP later

Run the following commands:

create database test;
use test;
create table sample (id int not null, name varchar(20) not null, primary key (id));
insert into sample (id,name) values (1,"catzie");
insert into sample (id,name) values (2,"petar");

This is what my MySQL command line interface looked like:

mysql> create database test;
Query OK, 1 row affected (0.01 sec)

mysql> use test;
Database changed
mysql> create table sample (id int not null, name varchar(20) not null, primary key (id));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into sample (id,name) values (1,"catzie");
Query OK, 1 row affected (0.00 sec)

mysql> insert into sample (id,name) values (2,"petar");
Query OK, 1 row affected (0.00 sec)

Make sure PHP can communicate with MySQL

The following command creates a symbolic link to help point to the right socket for MySQL to use on Mac.

cd /var 
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /tmp/mysql.sock mysql.sock

Reason: “You may have a socket (appearing as a zero length file) as /tmp/mysql.sock or /var/mysql/mysql.sock but 1 or more apps is looking in the other location for it.” – source

Another option: A fellow developer told me that instead of creating a symbolic link to the socket, he connects directly to localhost:3306, connecting through networking sockets instead of Unix sockets.

Enable mod_rewrite

My guide suggests we enable this now to avoid forgetting later that it’s not yet enabled. This will prevent hiccups when we’re already busy with coding web apps.

Edit the config file with Vim.

sudo vim /etc/apache2/httpd.conf

Uncomment the following lines:

LoadModule deflate_module libexec/apache2/mod_deflate.so
LoadModule expires_module libexec/apache2/mod_expires.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so

Restart Apache:

sudo apachectl restart

Sample PHP-MySQL code to test your “MAMP” stack

Remember the table I created earlier? This is when we’re going to use that.

Run this command, we’re going to paste code into it:

sudo vim /Library/WebServer/Documents/testsql.php

Paste the following PHP code which SELECTs data from a sample MySQL table. Remember to edit the variable values to match your own settings, especially the password.

<?php

$servername = "localhost";
$username = "root";
$password = "your-password";
$dbname = "test";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // test query
    foreach($conn->query('SELECT * FROM sample') as $row) {
        echo $row['id'] . ' ' . $row['name'] . '<br>'; //etc...
    }

    echo "(done)";

    }
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$conn = null;
?>

Visit this link on your browser: http://localhost/testsql.php

It should display this:

1 catzie
2 petar
done

Move Document Root folder

Right now, the document root is at "/Library/WebServer/Documents", and you may have noticed that each time we edit a file to create a new file within this folder, we need to sudo. That is inefficient, so let’s move our document somewhere that we won’t have to sudo for each change that we want to make.

We will move document root from "/Library/WebServer/Documents" to /webcontent.

Create “webcontent” folder under the root directory /. You can choose any other name you like.

sudo mkdir /webcontent

Let’s create a sample page inside the newly created folder.

sudo vim /webcontent/index.html

And place anything there such as “Hello!”

Now, let;s edit the Apache configuration file to point to the /webcontent folder:

sudo vim /etc/apache2/httpd.conf

Change the line DocumentRoot "/Library/WebServer/Documents" into /webcontent

Change the line <Directory "/Library/WebServer/Documents"> into <Directory "/webcontent">

Restart Apache:

sudo apachectl restart

Visit http://localhost again, and you should see whatever text you placed inside /webcontent/index.html

Just in case you still need to ‘sudo’ to access /webcontent folder

Try to copy the /webcontent/index.html file to check if you no longer need sudo in the /webcontent folder:

cp /webcontent/index.html /webcontent/index2.html

If it gives you the error cp: /webcontent/index2.html: Permission denied then here are your options:

  • Option #1: Change ownership of /webcontent folder

    In the Mac Mini I use, the directory permissions for /webcontent is drwxr-xr-x which means only the owner (root) has permissions write to it, unless I sudo as another user, which is not convenient if I need to edit many files.

    What we can do is change ownership of /webcontent from “root” user to our own user, like so:

    sudo chown -R yourUsername /webcontent

    Now try to create or edit files under the /webcontent folder. Your system should no longer deny you permission, since it is owned by you. So far I have not encountered a problem yet with this setup.

  • Option #2: Move document root under your user folder

    You can try to move your document root under your user folder, i.e. ~/ or /Users/<yourUsername>, and see if you can edit files there without the need for sudo. Your user is the owner of this folder so you shouldn’t need additional permissions to edit files under it.

On my MacBook Pro, I no longer had to sudo when I edit files in new document root /webcontent, but on another Mac computer that I use (Mac Mini), I still needed sudo to edit files in document root. I will edit this blog entry when I find a way to avoid this.

Tested on:

Computer: Mac Mini
Operating System: OS X El Capitan version 10.11
Apache: 2.4.16 (bundled with El Capitan)
PHP: 5.5.27 (bundled with El Capitan)
MySQL: 5.5.34 (bundled with installed MAMP)

Extras…

How to stop Apache on your Mac

Type this command in Terminal to stop Apache on your Mac:

sudo apachectl -k stop

or

sudo apachectl stop

Based on my observation, when I start and stop Apache multiple times, the stop command with -k only works on the first time. Succeeding commands for stopping Apache becomes just sudo apachectl stop.

How to check version of Apache, MySQL and PHP

Apache version:

apachectl -v

or

httpd -v

MySQL version:

If using MAMP bundle, MySQL service should be running when you use this command:

mysql --version

The welcome screen should show MySQL version when you login to MySQL via command line:

 mysql -uroot -p

PHP version:

php -v

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)

When I got this error regarding a socket (my MySQL is installed via Homebrew), it was fixed when I started MySQL by running the following command:

mysql.server restart

I think the same command is used for both starting and restarting of the MySQL server. Note that this is the command I use for my MySQL that’s installed via Homebrew. If you have MAMP GUI and not the MySQL from Homebrew, simply use that interface to start your MySQL service.

Reference(s):
Install MySQL on Mac OSX with Homebrew
Running Simple Select Statements
symbolic link setup for correct socket file locations in Mac OS X for MySQL
Version of Apache in Mac
Main Guide: Installing Apache, PHP, and MySQL on Mac OS X El Capitan

Related Posts:

Posts that may be related to "Install & config Apache, MySQL and PHP on your Mac (MAMP)":

Catzie

A Filipino programmer and baker. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Running small-time online dessert shops Cookies PH and Catzie's Cakery.

Leave a Reply

Your email address will not be published. Required fields are marked *