How to switch PHP versions in Ubuntu with one line of code

navya , Credit to  volkotech-solutions Jun 15
Switch PHP versions in Ubuntu via command line banner image

This blog gives a solution for maintaining multiple PHP versions in the same machine(Ubuntu) and can easily switch from one another as per the project requirement.

It is literally hard to change our php versions for each and every project and if you are dealing with multiple projects at a time, then this issue will bang us like anything. So here is a very simple solution for this, and we can switch php versions as required to the current project.

Check php version

At the very first step check your php version with the following command

$ php -v

Check PHP version using Ubuntu terminal

After that enter the following command to get the available php versions that are configured in your machine.

Selecting the manual updation mode

Enter the following command to select the manual mode

$ sudo update-alternatives --config php

Change to manual mode using Ubuntu terminal

Right after hitting enter, you may need to add your password after that you will see the list of php versions that your machine is holding. Here is the screenshot for your reference

Select the version that you want to configure, for example, now I have the php version 7.4 and if I want to shift to the php version 8.1 then I should enter the number 3 here and then press enter.

Choose required php version using Ubuntu terminal

Restart nginx

After that, we need to restart the nginx server, and here is the command

$ sudo service nginx restart

Restart Nginx using Ubuntu terminal

To complete this process we need to do one more operation that is we have to restart our php fpm also and here is the command.

Restart php fpm

This is the generic command $ sudo service phpversion_number-fpm. Since I need to restart my php fpm of version 8.1 then I need to write the command in this way.

$ sudo service php8.1-fpm
$ sudo service php8.1-fpm restart

Restart fpm using Ubuntu terminal


Then again check the php version to confirm whether it is updated or not and hope you know the command, there it is! So, there we go. The php version is updated successfully. 
Result of changing PHP version shown in Ubuntu terminal

We can also check in manual mode.
Checking the manual mode results in Ubuntu terminal


Switching php versions is far better than the changing existing version forcibly. With the above simple steps, we have achieved an instant change of the php version when required. Hope this article deserves to be on your favorite list. Thank you soo much for reading.




Read Next