Mac OS X Apache and PHP Setup

2016-02-01

To setup the Apache and PHP on OS X El Captain, thanks to this artile of Ole Michelsen

In terminal,

1
httpd -v

It would display the installed version of Apache, to start Apache

1
sudo apachectl start

Open http://localhost in a browser, if everything works, a webpage
with text “It works” would display.

Next, create a Sites folder under the user folder,

1
mkdir ~/Sites

We need to create a new user config for Apache(The user config is actually already created when I go to the folder /etc/apache2/users/),

1
sudo vim /etc/apache2/users/Watson.config

Paste the following config or modify the existed ones in the Watson.config(I didn’t dig into what these configs are used for),

1
2
3
4
5
<Directory "/Users/*/Sites/">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Require all granted
</Directory>

Next, to enable the Apache using our own user directory to serve files, modify the httpd.conf file.

1
sudo vim /etc/apache2/httpd.conf

In vim, press / for searching and search for “userdir”, uncomment the following lines(remove the leading#),

1
2
3
4
LoadModule userdir_module libexec/apache2/mod_userdir.so
LoadModule alias_module libexec/apache2/mod_alias.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
LoadModule php5_module libexec/apache2/libphp5.so

And one more line to uncomment,

1
Include /private/etc/apache2/extra/httpd-userdir.conf

Note, from another post on Stackoverflow
There is one more config in httpd.conf,
Change

1
2
User _www
Group _www

To

1
2
User Watson
Group staff

Next, modify the httpd-userdir.conf file,

1
sudo vim /etc/apache2/extra/httpd-userdir.conf 

Uncomment the following line, then save the file.

1
Include /private/etc/apache2/users/*.conf

Next, restart Apache,

1
sudo apachectl restart

To test that PHP is working, create a PHP test file in your new user level web root (~/Sites),

1
printf "<?php phpinfo(); ?>" > ~/Sites/phpinfo.php

Open the http://localhost/~Watson/phpinfo.php in a browser to see if the configuration works.
If you want Apache to start up automatically after a restart, run the following command in the Terminal,

1
sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist

The reason I install Apache and PHP is that I want a script to upload some images from a Java server. In the installation, the php code has some “write privileges” issue, then I found the solution from the stackoverflow.