In this tutorial we are going to learn how to switch php version in linux. Let’s get an example that you have multiple projects that uses earlier version of the PHP and you need to switch the PHP version in your machine.
If you have multiple version of php in your machine then, CLI default sets to 7.0 and same goes for Apache or NGINX. Developers always needs to work accross multiple projects so switching PHP version in a click is necessary.
In windows you can use Ampps which is similar to xampp and very easy to switch multiple version of php. But in case of linux we need to take care of it through the command line.
We can use php -v
in the terminal to know our current version.
To change the php version you need to write the following code in your terminal.
1 2 3 |
sudo a2dismod php7.2 ; sudo a2enmod php7.0 ; sudo systemctl restart apache2 sudo ln -sfn /usr/bin/php7.0 /etc/alternatives/php |
It now changes your php 7.2 version to 7.0. If you want to revert back just change the 7.2 to 7.0 and you will be reverted back to 7.0 version of php. You can make assure that you php version is changed by typing php -v
in the terminal.
If you are using Nginx then type the code after using the code above
1 |
sudo systemctl restart nginx |
Typing this console commands may be time consuming but if you have knowledge of bash then you can create bash alias as a function and change the version.
Let’s see how can we achieve it.
Go to terminal and type
sudo nano ~/. bashrc
copy and paste the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
change_php_version () { local IS_PHP7=`php --version|grep "PHP 7.2"` if [[ -z $IS_PHP7 ]]; then echo "Changing PHP Version to 7.2" sudo a2dismod php7.0; sudo a2enmod php7.2; sudo systemctl restart apache2; sudo ln -sfn /usr/bin/php7.2 /etc/alternatives/php else echo "Changing PHP Version to 7.0" sudo a2dismod php7.2; sudo a2enmod php7.0; sudo systemctl restart apache2; sudo ln -sfn /usr/bin/php7.0 /etc/alternatives/php fi } |
After completing this process pen up your terminal and type change_php_version
and it will switch the version according to the version you are using and vice-versa. You can also edit the file the way you want and add more version to it.
I found this method in the web, but i forgot it. Salute to him. It has never been this easier to switch PHP version. If you have any problem mention them in comments or contact us through the contact page.
Leave a Reply