Project dependent PHP CLI version

When you use one system for different PHP projects then sooner or later you will need to set up different PHP version per project. One solution is to manually change PHP before switching to project. But this is boring… To have the right version of PHP without our interaction we can use php-fpm and set right php version directly in vhost. But how to automatically change PHP version on CLI ?

Lucky there is a project called https://direnv.net/
Its library that reads .envrc file on each folder change and executes commands inside. It hooks into “cd” command. What we would like to do is to create .envrc file in root of each local project and modify PATH to read the php binary from right folder.

Here is the howto for mac osx:

  • Install with brew install direnv
  • In ~/.bash_profile add line eval "$(direnv hook bash)"
  • Add pathes to different php versions in your ~/.bash_profile like:
export PATH_PHP73="/usr/local/opt/php@7.3/bin"
export PATH_PHP72="/usr/local/opt/php@7.2/bin"
export PATH_PHP71="/usr/local/opt/php@7.1/bin"
export PATH_PHP70="/usr/local/opt/php@7.0/bin"
export PATH_PHP56="/usr/local/opt/php@5.6/bin"
  • In folder where you want to switch PHP version create file .envrc Preferably put it into git. In the file put one line export PATH="$PATH_PHP72:$PATH" – of course choose the right version of PHP for the project.
  • For security reason you need to tell direnv that it needs to read .envrc file from this folder. To do that run command direnv allow You will need to activate reading of .envrc again if content of the .envrc file will change.

Thats all.

Now when you run php -v inside this folder you should have the php version you choose.

Leave a Comment.