PHP for Apache on OS X El Capitan

If you are running an Apache web server under OS X El Capitan and want to use PHP with Apache, you will need to take some additional steps after you've got Apache running on OS X/macOS. Once you've got Apache working on the system, you can create a .php file, e.g. phptest.php and have the page displayed by your browser if you visit the page, but PHP code within the page won't be executed. E.g., suppose the phptest.php page contains the following code:

Easy PHPeasy - PHP and MySQL for code-phobes
Easy PHPeasy
PHP and MySQL for code-phobes
1x1 px

<html lang="en">
<meta charset="UTF-8">
<title>PHP Test</title>


<h2>A test page</h2>

<?php phpinfo(); ?>


If I visit the page using a browser, the HyperText Markup Language (HTML) code on the page will be displayed, e.g. the "A test page" heading will be displayed, but the information that the phpinfo() command would display regarding the PHP settings for a system on which PHP is working won't be displayed. You could also try a simple PHP echo command, e.g. <?php echo "This is the output from a PHP echo command."; ?>, but the output from that command would not be displayed, either.

To get PHP working, you need to edit the Apache configuration file /etc/apache2/httpd.conf with a text editor. There are several text editors that can be found on a Mac OS X/macOS system, e.g., vi, GNU nano, or the TextEdit application found in the Applications folder. The latter provides a graphical user interface (GUI). The first two are ones that can be run at a command line interface (CLI), e.g., within a Terminal window (the Terminal app is found within Applications/Utilities). Though the vi editor has many powerful text manipulation features, the nano editor will be easier to use, if you are unfamiliar with vi. To use either vi or nano, you will need to start the editor with administrator privileges, which you can do using the sudo command. You will be prompted for your password and your account will need to be allowed administrator, i.e., root, privileges. E.g.:

Learn PHP as a master
Learn PHP as a master
1x1 px

$ sudo nano /etc/apache2/httpd.conf

In the httpd.conf file look for the line below:

#LoadModule php5_module libexec/apache2/

If you are using the nano editor, you can use control-w to search for php to locate the line. Remove the hash sign (#) from the beginning of the line, since that makes the line a comment, rather than a configuration directive. After saving the modified file, you will need to restart Apache to have the configuration setting take effect.

$ sudo apachectl restart

Once you've restarted Apache, if you visit the test page where phpinfo() has been used, as in the example above, you should see a page similar to this one.