The classic Dev dilemma, you get comfortable in a language or tool and then there is an update. Do your projects stay with the version that you know? Or do you try and upgrade to a new version as soon as possible?
I decided to try and find a way to work in 7.4 but experiment with 8.0. Eventually all of my newer projects will adopt the latest versions but I want to be flexible.
I found working with two different versions of PHP on the same device to be very hard. I tried to find different methods but weren't entirely happy with the results. Therefore, I created a PHP toggle! A Bash script that will allow users to comfortably switch between versions with a quick command.
Now to preface, I'm totally new to Linux and Bash and realize that there are probably better ways of doing this. But I thought I would share what I did and maybe work shop things. See if this helps other people.
#!/usr/bin/env bash
# shellcheck disable=SC2005
modExists="$(php -v:0:7)"
modExists=${modExists:0:7}
case $modExists in
"PHP 8.0")
a2dismod php8.0
a2enmod php7.4
update-alternatives --set php /usr/bin/php7.4;;
"PHP 7.4")
a2dismod php7.4
a2enmod php8.0
update-alternatives --set php /usr/bin/php8.0;;
esac
php -v
systemctl restart apache2
systemctl status apache2
I've been using this for a while and so far it's been working like a charm. Happy Hacking everyone! I have a gist as well here:
toggle.sh
Top comments (3)
Hey, congrats on your first post ! That's a pretty nice solution too.
What I usually do with my LAMP stack is use php-fpm, run all versions I need at the same time, and then in my apache VirtualHost set the correct handler for php files depending on the version I want :
or
That way all my projects run at the same time without needing to switch from one version to the other, except for the CLI where I still need to run
update-alternatives
Awesome solution!
For windows users: with wsl2 you can easily switch between distros with the -d flag and mount them to the current directory.
e.g.
wsl -d Ubuntu
Assuming you have various distros with various testing scenarios, you can use that to easily run tests or applications in different distributions, versions etc
To test a project at same time with multiple PHP versions I have a default virtualhost with project name and version alias:
And a second virtualhost with each other version to test:
You should remember to add this hosts to your
/etc/hosts
file:Cheers!