Using a Mac for the first time, I faced a problem installing PHP. I would install it over and over, and every time the terminal would tell me that I don’t have PHP on my laptop. Furthermore, I didn’t just need to install one version of PHP, I needed multiple versions because I had different projects to run. Here are the steps I had to follow to be able to install multiple versions of PHP on Mac.
First uninstall PHP on your Mac
The first step is to update brew before using it to install PHP
brew update
brew upgrade
brew cleanup
Then you need to check the current PHP installed
brew list | grep php
Then uninstall all the PHP that the grep return, here is an example :
brew uninstall --force php71 php71-apcu php71-opcache php71-xdebug php71-yaml
brew uninstall --force php72 php72-apcu php72-opcache php72-xdebug php72-yaml
brew cleanup
Check again with a grep if you have anything related to PHP left :
brew list | grep php
If it returns nothing, then you are all good. Otherwise, try to uninstall what is left.
Then we want to remove the old PHP configuration :
rm -Rf /usr/local/etc/php/*
Once everything is clean, you can jump into the PHP installation.
Then Install PHP on your Mac
We start by installing tap from shivammathur/php, to handle multiple versions of php.
brew tap shivammathur/php
Then you can install the different versions of PHP you want. I need versions 7.1, 7.2 and 7.3:
brew install shivammathur/php/php@7.1
brew install shivammathur/php/php@7.2
brew install shivammathur/php/php@7.3
Now you can go in the php.ini of every version and change the options you need like the memory settings, the date.timezone etc… You can find the files of each version here:
/usr/local/etc/php/7.1/php.ini
/usr/local/etc/php/7.2/php.ini
/usr/local/etc/php/7.3/php.ini
You also need to add PHP to your path, so do that for each version of PHP you installed :
echo 'export PATH="/usr/local/opt/php@7.3/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/usr/local/opt/php@7.3/sbin:$PATH"' >> ~/.zshrc
export LDFLAGS="-L/usr/local/opt/php@7.3/lib"
export CPPFLAGS="-I/usr/local/opt/php@7.3/include"
We have installed but not linked these PHP versions. To switch to PHP 7.3 for example, we can type:
brew unlink php && brew link --overwrite --force php@7.3
Now you can test if you are in the correct version using :
php -v
You can switch versions of PHP easily
If you want to switch versions, use this command :
brew unlink php && brew link --overwrite --force php@7.2
Don’t forget to check if the version correctly changed:
php -v
That’s it! You’ve successfully installed PHP on Mac.