If like me, you have the chance to work on several projects with different php frameworks or not, you must have encountered compatibility issues between the different versions of php.
Examples:
- Old sites in php 5.6
- The latest version of laravel in php 7.4
- CakePhp 2 which hardly supports php> 7.1
- …
In short, you understand me, you will sometimes have to switch to the php version …
How to switch from one version of php to another?
To tell the truth, it is very simple, 4 lines are enough.
I start from the predicate that you have several versions of php installed (5.6, 7.1, 7.2 …)
If not, feel free to search google with queries such as: How to install php XX on YY (YY being your Linux distribution.)
Anyway, back on topic.
Open your terminal and type this.
sudo a2dismod php *
This will disable all your versions of php.
sudo a2enmod php7.3
Here we are going to activate php7.3 which you can replace with whatever version you want.
sudo update-alternatives --set php /usr/bin/php7.3
We update the configuration to tell it to take php7.3 by default.
sudo systemctl reload apache2
Finally, we restart apache2 for the changes to take effect.
To check, always in your terminal
php -v
And you should have an exit like this.
PHP 7.3.27-4 + ubuntu20.04.1 + deb.sury.org + 1 (cli) (built: Feb 14, 2021 2:26:33 PM) (NTS)
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.27, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.27-4 + ubuntu20.04.1 + deb.sury.org +1, Copyright (c) 1999-2018, by Zend Technologies
How to quickly switch between different versions of PHP?
If like me you are lazy and you do not want to remember these 4 lines, which is to your credit, a good developer must be lazy :p.
I invite you to create a small bash file that you can call switch.sh and whose content will be:
#!/bin/bash
read -p "What version do you want ?: " version
sudo a2dismod php*
sudo a2enmod php$version
sudo update-alternatives --set php /usr/bin/php$version
sudo systemctl reload apache2
Now you just have to type (where you bash script is, generally in www)
bash switch.sh
And answer the question with the version of php you want to switch to.
7.4
Once again you can check with php -v command.
You couldn’t do simpler and faster.