Easily Switch PHP versions on Linux with Script

If you are looking for best way to switch multiple PHP versions on your machine, you're at the right place to get the best solution for your requirement.

Let's say on your working computer you have installed multiple PHP versions (for eg: PHP 7.0 and PHP 7.2). As a default version, the PHP 7.0 is set to Nginx or Apache and CLI mode.

Of course, as a modern web developer who works on the different framework, packages need to have multiple PHP versions installed on their working machine. During their work on different projects, the project may not support all latest versions, so the developer may need to switch to a required version of PHP to run that project.

Below I will show you how to use the command line as well as a bash alias function to easily switch your versions.

You may want to go from PHP 7.2 to 7.0, use the commands below.

If you don't know how to check the php version on Linux Ubuntu type below command on terminal.

    php -v
//php 7.2 to php 7.0 switcher

sudo a2dismod php7.2 ; sudo a2enmod php7.0 ; sudo systemctl restart apache2

sudo ln -sfn /usr/bin/php7.0 /etc/alternatives/php

//if you are using nginx
sudo systemctl restart nginx

Similarly, while PHP version 7.0 is active, you can fall back to 7.2 with the following commands.

//php 7.0 to php 7.2 switcher

sudo a2dismod php7.0 ; sudo a2enmod php7.2 ; sudo systemctl restart apache2

sudo ln -sfn /usr/bin/php7.2 /etc/alternatives/php

//if you are using nginx
sudo systemctl restart nginx

Repeating the above process frequently is really irritating, time-wasting, right?

Finally, I decided to create a bash alias as a function to reduce my time to repeat the php switching and easy to remember.

Setup

Open up your terminal and type.

sudo nano ~/.bashrc

Scroll around the last line, where we want to paste the below function.

phpswap () {
    local IS_PHP7=`php --version|grep "PHP 7.2"`

    if [[ -z $IS_PHP7 ]]; then
        echo "Switching to PHP 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 "Switching to PHP 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
}

Usage

After completing the above process simply hit phpswap on your terminal.

I use multiple PHP versions, 7.2, 7.0 with Ubuntu 16.04.3 LTS. I simply run phpswapover the terminal, it detects the current default PHP version and switches to exactly reverse version which I need to go with.

Easy right?

We're done!

Conclusion

Thanks for reading this post up to the end, if you think this post is worth reading, feel free to share with others, also if you have feedback please post in the comment section below.

Happy Coding!

Last Updated: 16th Feb, 2018