1

I set up PHP-FPM to have different versions of PHP for different folders. This was necessary due to legacy code and was achieved using the apache's .htaccess.

My question is: does anyone have a simple elegant way to do this in CLI? I was thinking maybe have a file in the folder indicating the desired version of PHP to run, but unsure of how to go about it.

My expected result is that when I run php ... in folder A, it runs with PHP 7.4 and when I do the same php ... in folder B, it runs with PHP 8.1

Thank you.

1 Answer 1

2

Assuming your PHP versions are installed in different paths, e.g.:

  • php 7.4 is in /usr/local/php74/bin
  • php 8.1 is in /usr/local/php81/bin
  • etc

Create a script php that looks for a .phppath file in each directory that describes which php binary to use. Something like:

#!/bin/sh

# This sets the default if not otherwise specified
phppath=/usr/local/php81/bin/php

if [ -f .phppath ]; then
  phppath=$(cat .phppath)
fi


exec $phppath "$@"

Put this in your $PATH somewhere and you should be all set. In directories where you want, say, PHP 7.4, create an appropriate .phppath file:

echo /usr/local/php74/bin/php > .phppath

Note that as written, this only finds .phppath in the current directory. It won't find it if you're working in a subdirectory. That's a solvable problem, but it's left as an exercise to the reader.

3
  • wonderful! actually it is exactly what I need, the extra exercise wasn't necessary. I think the path should be written into > .phpversion instead of > .phppath. Thank you!
    – bilogic
    Aug 29, 2022 at 16:12
  • i think there is still a bug in your script, checking for .phppath, but reading from .phpversion. I would have different names for variable and filename for clarity especially for new folks trying to learn. Thank you.
    – bilogic
    Aug 30, 2022 at 0:18
  • Yes, good catch. Updating.
    – larsks
    Aug 30, 2022 at 0:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .