Skip to content

Instantly share code, notes, and snippets.

@phramz
Created July 17, 2023 12:32
Show Gist options
  • Select an option

  • Save phramz/d61fea3616806f6925147c06e670de8a to your computer and use it in GitHub Desktop.

Select an option

Save phramz/d61fea3616806f6925147c06e670de8a to your computer and use it in GitHub Desktop.
Multiple PHP Versions with Direnv & Homebrew on MacOS

Step 1) Install Direnv

If you're not already installed Direnv you can do it using Homebrew:

brew install direnv

Do not forget to properly setup the shell hook for your Bash, ZSH, etc. (whatever shell you use) ... see https://direnv.net/docs/hook.html

Step 2) Install PHP

You probably already installed the latest PHP via the Homebrew formular brew install php. So this is your default:

php --version

Will output something like

PHP 8.2.8 (cli) (built: Jul  6 2023 10:57:44) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.8, Copyright (c) Zend Technologies
    with Xdebug v3.2.0, Copyright (c) 2002-2022, by Derick Rethans
    with Zend OPcache v8.2.8, Copyright (c), by Zend Technologies

Step 3) Install addtional PHP versions

You can install multiple versions using shivammathur/php tap. So you need to add it to Homebrew:

brew tap shivammathur/php

Now install your desired legacy Version (e.g. 7.4)

brew install shivammathur/php/php@7.4

You need lookup the exact path where the PHP binaries are installed (we need it later):

ls -la /opt/homebrew/Cellar/php@7.4/
total 0
drwxr-xr-x    3 phramz  admin    96 Jul 17 14:01 .
drwxrwxr-x  130 phramz  admin  4160 Jul 17 14:01 ..
drwxr-xr-x   16 phramz  admin   512 Jul 17 14:01 7.4.33_4

In this case it is /opt/homebrew/Cellar/php@7.4/7.4.33_4

Step 4) Setup preject

Now cd to your project root path and create/edit the .envrc file:

export PHP_PATH="/opt/homebrew/Cellar/php@7.4/7.4.33_4" # the installation path from the step before
export PATH="$PHP_PATH/bin:$PHP_PATH/sbin:$PATH"

Step 5) Check

Since the .envrc is still blocked/inactive you should still see your "default" PHP Version is active:

php --version
PHP 8.2.8 (cli) (built: Jul  6 2023 10:57:44) (NTS)

Now unblock the .envrc file and check again:

direnv allow
php --version
PHP 7.4.33 (cli) (built: Jul 13 2023 17:41:11) ( NTS )

... done 🤓

@jhernandis
Copy link
Copy Markdown

Thanks for sharing. I'll test on a Linux (WSL)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment