Install and Run PHP on MacOS

To enable PHP on the Apache server on macOS, you’ll need to edit the Apache configuration file (httpd.conf) to load the PHP module and then restart Apache for the changes to take effect. Here’s a step-by-step guide to enable PHP:

Step 1: Install PHP (if not already installed)

As of macOS Catalina and later, PHP is not pre-installed. You can install PHP using Homebrew, a package manager for macOS. If you haven’t installed Homebrew yet, you can install it by pasting the following command into your terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

After installing Homebrew, you can install PHP by running:

brew install php

This command installs the latest version of PHP and automatically starts the PHP service.

Step 2: Edit the Apache Configuration File

  1. Open the Terminal application.
  2. Open the Apache configuration file in a text editor. You might use nano (a user-friendly text editor) for editing. You’ll need superuser privileges to edit this file:
sudo nano /etc/apache2/httpd.conf
  1. Uncomment (remove the # at the beginning of) the line that loads the PHP module. This line might look slightly different depending on the version of PHP you have installed. For PHP 7 and PHP 8, it might look something like this:

For PHP 7.x:

LoadModule php7_module libexec/apache2/libphp7.so

For PHP 8.x:

LoadModule php_module /usr/local/opt/php/lib/httpd/modules/libphp.so

The exact path may vary based on how PHP was installed and its version. If you installed PHP via Homebrew, the correct LoadModule directive might be slightly different, and you can usually find the correct line to include by checking the post-installation instructions provided by Homebrew.

  1. Save the changes and exit the editor. If you’re using nano, you can do this by pressing Ctrl + X, then Y to confirm changes, and Enter to exit.

Step 3: Restart Apache

To apply the changes, restart Apache using the following command:

sudo apachectl restart

Step 4: Test PHP

To ensure PHP is working correctly, you can create a simple PHP file to serve:

  1. Navigate to the DocumentRoot of your Apache server (by default, this is /Library/WebServer/Documents/ on macOS, unless you’ve changed it in your httpd.conf).
  2. Create a file named test.php with the following PHP code:
<?php phpinfo(); ?>
  1. Open a web browser and navigate to http://localhost/test.php.

If PHP is correctly enabled, you should see the PHP information page displayed in your browser.

Note

The paths and module names might vary depending on your macOS version, the version of PHP you’re using, and how you’ve installed PHP. Always refer to the most current documentation for the versions you’re using.

Comments

comments