How to Setup PHP & MySQL on Mac OS X

If you’re a PHP developer and use Mac OS X you’ve probably heard of MAMP or XAMPP. It’s an easy way to setup a local development environment with Apache, PHP and MySQL (AMP stack) and recommended for beginners. Having said that, Mac OS X comes with Apache and PHP out of the box and there is no reason not to setup your own environment once you feel comfortable. It’s more flexible, independent and very easy! In fact it’s only four steps with MySQL as a database:

1. Activate PHP

PHP isn’t running automatically on your Mac. To enable it, you need to uncomment the following line in /etc/apache2/httpd.conf:

LoadModule php5_module libexec/apache2/libphp5.so

2. Install Homebrew

Homebrew could be described as the missing package manager for OS X and makes installing MySQL a breeze.

$ ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go)

3. Install MySQL via Homebrew

$ brew install mysql
$ unset TMPDIR
$ mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp

4. Secure MySQL Installation

$ /usr/local/Cellar/mysql/ 5.5.27/bin/mysql \_secure\_installation

That’s it! In case you’d like to manage your databases with a GUI, you could install phpMyAdmin or use the free Mac app Sequel Pro.

You can use the following shell script to comfortably start, stop and restart Apache and MySQL:

#! /bin/sh

# ----------------------------- #
# Apache + MySQL Control Script
# ----------------------------- #

command=$1

if [ $# -eq 0 ]
then
    echo "Please provide a command: start, restart, stop"
    read command
fi

if [ $command = "start" -o $command = "restart" -o $command = "stop" ]
then
    mysql.server $command
    sudo apachectl $command
else
    echo "Unkown command provided."
fi

I send new articles to my newsletter list first; subscribe here! If you like what you just read, why not tweet about it?