tengkuiqbal

Install and Manage Multiple PHP Versions

Sat, July 20, 2024 - 2 min read
php

When developing with PHP on macOS, it’s often necessary to switch between different versions. Here’s a comprehensive guide on how to install, list, and switch PHP versions using Homebrew.

Installing the Latest PHP Version

To install the latest version of PHP, you can use Homebrew. Open your terminal and run the following command:

brew install php

Check installed version:

php -v

result:

PHP 8.3.9 (cli) (built: Jul  2 2024 14:10:14) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.9, Copyright (c) Zend Technologies
    with Zend OPcache v8.3.9, Copyright (c), by Zend Technologies

To check the installation path, use:

which php

This should return something like:

/opt/homebrew/bin/php

Installing a Specific PHP Version

If you need a specific version of PHP, you can specify it during installation. For example, to install PHP 8.0, use:

brew install [email protected]

Listing Installed PHP Versions

To list all the PHP versions installed via Homebrew, you can use:

brew ls --versions | grep '^php[ @]'

Switching Between PHP Versions

Switching between different PHP versions can be done using a Bash script. Below is a script to switch PHP versions.

Create a file named php_versions.sh and add the following content:

#!/bin/bash
 
if [ $# -ne 1 ]; then
    echo 1>&2 "USAGE: $0 <phpVersion>"
    exit 2
fi
 
INSTALLED_VERSIONS=`find /opt/homebrew/opt | grep 'php@' | sed 's/\/opt\/homebrew\/opt\/php@//'`
 
if [[ ! -f /opt/homebrew/opt/php@${1}/bin/php ]]; then
    echo 1>&2 "/opt/homebrew/opt/php@${1}/bin/php was not found"
    printf 'valid options:\n%s\n' "${INSTALLED_VERSIONS[*]}"
    exit 2
fi
 
for VERSION in ${INSTALLED_VERSIONS[*]}; do
    brew unlink php@$VERSION > /dev/null 2>&1
    brew services stop php@$VERSION > /dev/null 2>&1
done
 
brew link --force --overwrite php@$1 > /dev/null 2>&1
brew services start php@$1 > /dev/null 2>&1
 

Make the script executable:

chmod 755 php_versions.sh

To switch to PHP 8.0, run:

./php_versions.sh 8.0

Creating Aliases for Convenience

You can create aliases to simplify the usage of the script and listing installed PHP versions. Add the following lines to your shell configuration file (e.g., .bashrc or .zshrc):

alias php_versions="./php_versions.sh"
alias php_list="brew ls --versions | grep '^php[ @]'"

Apply the Zsh configuration with:

source ~/.zshrc

Now, you can switch PHP versions and list them more easily:

php_versions 8.0
php_list