Ubuntu, Switching PHP version

Ubuntu, Switching PHP version

Written by Sohag Hossain on Oct 28th, 2021 Views Report Post

It's quite natural for a developer that you need to work on different projects which don't have the same language version. For me, most of the time I work on PHP and I need to work on a couple of projects which depend on various PHP versions like PHP5.6, PHP7.0, PHP7.4, and PHP8.0. If you're managing through docker that's totally awesome, but if you're managing through docker then, to change the PHP version both for WEB and CLI you need to run multiple commands. Of course, it's possible searching the commands to the web or save the commands to a local place and reuse them. Isn't it better to write one word and your machine help you to switch the PHP version for you, what do you think 🤔?

To switch specific php version

bash <bash_file_name> <desired_version_to_switch> (e.g: bash sample.sh 5.6)

As you can see this file expect only one parameter, the expected PHP version to switch. Here's the bash file content

REQUESTED_VERSION=${1?Error: no version given}
CURRENT_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')

echo Current Version: $CURRENT_VERSION
echo Requested Version: $REQUESTED_VERSION

sudo a2dismod php"$CURRENT_VERSION" \
&& sudo a2enmod php"$REQUESTED_VERSION" \
&& sudo update-alternatives --set php /usr/bin/php"$REQUESTED_VERSION" \
&& sudo service apache2 restart

CURRENT_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')

echo done, your PHP Version is: $CURRENT_VERSION

In my case, I've added couple of aliases and finally to switch a specific PHP version.

** alias bash_file_location_which_change_php_version="/home/devnet/mine/bash/change_php_version.sh"

** alias php56="bash_file_location_which_change_php_version 5.6

** alias php74="bash_file_location_which_change_php_version 7.4

** alias php8="bash_file_location_which_change_php_version 8.0

Now if i want to change the php version, all i need to do press php56 or php74 or php8 and i'm done.

switching_php_version_image

Comments (0)