How to set up PHP in MacOS

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

If you’re working with web development or want to test PHP code locally on your Mac, setting up PHP is essential. This tutorial guides you through the process step-by-step, from installing PHP to configuring your environment.

Installing Homebrew

Firstly, you’ll need to install Homebrew, a popular package manager for MacOS. Open your terminal and run:

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

This script will install Homebrew, making it much easier to manage software installations on your Mac.

Installing PHP

With Homebrew installed, you can easily install PHP by running:

brew update
brew install php

This will download and install the latest version of PHP.

Basic PHP Server

After installation, you can start a basic PHP server to test things out. Navigate to the directory where your PHP files are located, then run:

php -S localhost:8000

This starts a PHP server on port 8000, and you can view the output by visiting http://localhost:8000 in your browser.

Advanced Configuration

To customize your PHP setup, you can tweak the php.ini file. Find it using:

php --ini

Edit the file with a text editor of your choice (for instance, Nano or Vim).

Using Virtual Hosts

It’s often useful to set up virtual hosts for local web development. Modify your Apache configuration file (httpd.conf), which is typically located in /etc/apache2/, and add the required directives to define your virtual host.

Integrating with MySQL or MariaDB

Many PHP projects require a database. Install MySQL or MariaDB using Homebrew:

brew install mysql
brew services start mysql

Or for MariaDB:

brew install mariadb
brew services start mariadb

To connect PHP with the database, use PDO or mysqli in your PHP scripts.

Using Package Managers like Composer

Composer is a dependency manager for PHP akin to npm for Node.js or pip for Python. Install Composer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Move the composer.phar file to a global path or use it locally in your project directory.

Conclusion

With PHP set up on your MacOS system, you’re ready to develop and test your web applications locally. Remember, the internet is your best resource for troubleshooting any setup issues. Happy coding!