How to execute multiple versions of PHP on macOS using the CLI

Categories: Development

Many sites still required php 7.4 even though it’s older and now considered deprecated. That being said, it’s still important to test with newer versions of PHP.

Combined with PHP having a quicker release cycle PHP 8, 8.1, and 8.2 are on their way.

I have to work with a couple of versions regularly in the CLI, and the best way I found to do this was to create an alias.

Let’s assume that you installed your versions of PHP using brew, or already know where your version of PHP is.

Add the following to your bash profile.

alias php7='/usr/local/opt/[email protected]/bin/php'
alias php8='/usr/local/opt/[email protected]/bin/php'

If you want you can install PHP 8.1 and 8.2 as well with brew install [email protected] and add another alias.

This will allow you to run php8 composer, you can do a quick test by creating an index.php file and adding phpinfo() to it.

php7 index.php | grep "PHP Version"
php8 index.php | grep "PHP Version"

If you have an M1 mac, your system paths will be different. You can replace:

/usr/local/opt/

with

/System/Volumes/Data/opt/homebrew/opt

If you were to run php -v and see v7.4 then you can now run php8 composer install in most cases, this has worked perfectly, but if you need something a bit more permanent it’s still best to change your system environment.

Alternatively, if you want to change your version of PHP in the command line more permanently you can add this function to your .bash_profile

function phpv() {
    brew unlink php
    brew link --overwrite --force "php@$1"
    php -v
}

And then run with phpv 8.2

I can’t take credit for the above shell script, but I also can’t find the original post that I discovered it on.


Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!