Its always a good practice to keep system packages up-to-date with the latest security patches and software updates. If any of the package are required to stick with specific version, You can exclude them from automatic upgrade. Now, execute the following commands to update Apt cache and then upgrade all system packages.
sudo apt update
sudo apt upgrade
The default Debian 12 repositories contains PHP 8.3 and PHP 7.4 packages, but not other versions like PHP 8.1, 7.3, 7.2 or 5.6. So we recommend to add a third-party repository, Ondřej Surý’s PHP repository, which provides up-to-date PHP packages. Run the following commands to add the repository:
sudo apt install -y apt-transport-https lsb-release ca-certificates wget
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpgecho "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
Then update the system to reflect the addition of the new repository.
sudo apt update
As you have configured the required PPA on your system. Let’s install the required PHP version. You can also installed multiple versions on a single system.
To install PHP 8.3, execute the following command:
sudo apt install -y php8.3
Now, install PHP 8.2 by running the following command:
sudo apt install -y php8.2
For some legacy applications, you may need an older version like PHP 7.4. Now you can install PHP 7.4 using the following command:
sudo apt install -y php7.4
You can check the installation using the same method as above:
php -v
This should display the version of PHP that’s currently active on your system. If PHP 7.4 is correctly installed, it will reflect here.
If you have multiple versions of PHP installed, you can switch between them using the update-alternatives command. For example, to switch to PHP 7.4, you would use:
sudo update-alternatives --set php /usr/bin/php7.4
To switch back to PHP 8.3, replace php7.4 with php8.2.
Congratulations! You now know how to install PHP 8.3, PHP 8.2 and PHP 7.4 on a Debian 12 system, and how to switch between the two versions. Remember, the version of PHP your server should run depends on your specific requirements and the compatibility of the web applications you plan to host. Always ensure to use supported and up-to-date versions of PHP for the best security and performance.