Installing PHP on your Mac

Installing PHP on your Mac

372

Installing Homebrew

When it comes to installing software on your Mac, we need only one package manager, and it's Homebrew.

It can install any package or software you want and even install specific versions.

Quick guide: Run the following command in your terminal:

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

Installing PHP with Homebrew on Mac

To install PHP, we can run the following command:

brew install php

This will install the latest stable version of PHP (At the moment of writing, this is PHP 8.1).

Before running any brew commands, it's a good habit to run the following commands first. These will check if Homebrew is all up to date and running the latest versions.

brew update
brew doctor

Installing PHP 8.0 with Homebrew

In my case, I wanted to install PHP 8.0 since it's the version our server is running.

To install a specific version, we can use the @ notation.

brew install [email protected]

This will run the installer, and it should end with a success notice in your terminal.

However, even though this installed PHP, it didn't change our running instance yet.

So if we run the php -v command, we might still see a different version like PHP 7.3.14 (CLI) or whatever you have installed.

To fix this, we need to link the correct PHP version.

Switching PHP Versions with Homebrew on Mac

Now that we installed versions, we can easily switch between them using the link command.

First, check which version of PHP is currently running:

php -v

Then we can unlink that version by using:

brew unlink [email protected]

The next step is to link the version we want:

brew link [email protected]

It will tell you to run a script to add the path:

echo 'export PATH="/opt/homebrew/opt/[email protected]/bin:$PATH"' >> ~/.zshrc

This will make sure the right PHP version is loaded, now if you run php -v again it should show:

And there we go. We switched to the PHP version.

Php -v is still showing the wrong version

I had the issue when upgrading from 7.4 to 8.0 for my demo that I kept seeing 7.4 when running php -v. Remove the old line in your .zshrc file to fix this manually.

nano ~/.zshrc

Remove the line that points to your old instance of PHP.

export PATH="/opt/homebrew/opt/[email protected]/bin:$PATH"


Important:

Remember every time you add new path to your mac sources files you need to run source <name_of_file_you_edited> and try the command in new terminal window.

- Last updated 2 years ago

Be the first to leave a comment.

You must login to leave a comment