November 15, 2024
I found myself in a situation where I needed to switch my PHP veresion from 8.3 to 8.0 on Ubuntu. After doing some research, I found the terminal commands to switch PHP versions. Initially, I faced a few challenges, but after some trial and error, I successfully mad the switch. I'd like to share the steps with you.
First, let's check which versions of PHP are installed on the system.
Open your terminal by pressing ctrl
+ alt
+ t
user@my-pc:~$ cd /etc/php
user@my-pc:/etc/php$ ls
8.0 8.3
In the above commands, we can see that php versions 8.0
and 8.3
installed on my system.
Now, let's check which version of PHP is currently in use.
user@my-pc:~$ php -v
PHP 8.3.13 (cli) (built: Oct 30 2024 11:28:41) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.13, Copyright (c) Zend Technologies
with Zend OPcache v8.3.13, Copyright (c), by Zend Technologies
From the output, we can see that I'm currently using PHP 8.3
To switch from PHP 8.3 to PHP 8.0, we will first change the PHP version for the CLI by running the following command:
user@my-pc:~$ sudo update-alternatives --set php /usr/bin/php8.0
Next, disable PHP 8.3, enable PHP 8.0 and then restart Apache:
user@my-pc:~$ sudo a2dismod php8.3
user@my-pc:~$ sudo a2enmod php8.0
user@my-pc:~$ sudo systemctl restart apache2
Now, let's verify the switch was successful:
user@my-pc:~$ php -v
PHP 8.0.30 (cli) (built: Sep 27 2024 04:11:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.30, Copyright (c) Zend Technologies
with Zend OPcache v8.0.30, Copyright (c), by Zend Technologies
As you can see, the PHP version has successfully switched to 8.0
If you need to switch PHP versions frequently, you may want to create an alias to make this process faster. Here's how you can do that.
.bashrc
FileTo make the switch even easier, we can add a custom function to our .bashrc
file. This function will allow you to switch PHP versions in one command.
Open your terminal any type:
user@my-pc:~$ nano ~/.bashrc
Scroll to the end of the file and add the following function:
switchphp(){
sudo a2dismod php"$1"
sudo a2enmod php"$2"
sudo systemctl restart apache2
sudo update-alternatives --set php /usr/bin/php"$2"
}
In this function, $1
and $2
are the PHP versions you want to switch between.
.bashrc
After saving the file, reload .bashrc
file by running
user@my-pc:~$ source ~/.bashrc
Now, we can use the switchphp
function to easily switch between PHP versions. For example, to switch from PHP 8.0 to 8.3, you can simply run:
user@my-pc:~$ switchphp 8.0 8.3
This will switch PHP from version 8.0
to 8.3
in a single command.