Setting up a local web server with PHP on MAC OS X

Mac OS X runs atop UNIX. Apache and PHP come packaged with OS X. To create a local web server, all you need to do is enable them.

Starting Appache

Open the Terminal app (command line) and type:

$ sudo apachectl start

Starting PHP

In order to enable PHP you need to enable it on httpd.conf.
Open for editing /etc/apache2/httpd.conf

$ vi /etc/apache2/httpd.conf

and uncomment the line

#LoadModule php5_module libexec/apache2/libphp5.so

Note: it may require root permission. You can use sudo or change permission to 777

$ sudo chmod 777 httpd.conf

Restart Apache for changes to take place

$ sudo apachectl stop
$ sudo apachectl start

From now on .php files can be created and executed from the terminal using

$ php -f filename.php

Run PHP files on server

Web files located at directory: /Library/WebServer/Documents
Create a filename.php file by

$ echo "<?php phpinfo(); ?>" > filename.php

Open a browser in the address http://localhost/filename.php

Changing default web files directory

The default web files directory is /Library/WebServer/Documents.
Every time you browse to your localhost you get to that directory.
The following will instruct you to change the directory to /Users/your-username/Sites.

Edit the Apache config file:

$ sudo vim /etc/apache2/httpd.conf

Change the Document root from the default /Library/WebServer/Documents to the new folder under home directory:
Look for these lines:

    DocumentRoot "/Library/WebServer/Documents"
    <Directory "/Library/WebServer/Documents">

And change them to:

    DocumentRoot "/Users/your-username/Sites"
    <Directory "/Users/your-username/Sites">

Of course instead of your-username insert there your real username.

I prefer to have it there, as I do not need root permissions to add content to that folder.

Enable .htaccess file in Mac OS X

In the same file (/etc/apache2/httpd.conf), under the section <Directory “/Users/your-username/Sites”> look for:

    AllowOverride None

And change it to:

    AllowOverride All

Also edit this file:

$ sudo vim /etc/apache2/users/your-username.conf

And look for the same line as above

    AllowOverride None

And change it to:

    AllowOverride All

Then restart apache:

$ sudo apachectl start

How to enable access to sub-directories from the browser

Starting with OS X 10.10 (Yosemite), Apple moved from Apache 2.2 to Apache 2.4, and that means there are a few additional changes we need to make. One of them is a directive that helps secure your machine by denying access to the entire file system by default.
In order to enable access to a sub directory from the browser (e.g. http://localhost/subdirectory/filename.php ) you need to edit the Apache config file:

$ sudo vim /etc/apache2/httpd.conf

Comment out (place ‘#’ in front of each line) the section of code runs from line 220 through 223.

 <Directory />
     AllowOverride none
     Require all denied
 </Directory>
Leave a Reply

*