When you’re working on different projects, sometimes you’ll find that each one needs a different version of PHP. For example, one project may require PHP 7.4, while another one works best on PHP 8.2. Instead of uninstalling and reinstalling PHP every time, Ubuntu gives us a neat way to switch between versions using the update-alternatives tool.
In this guide, we’ll walk through installing multiple PHP versions on Ubuntu and switching between them whenever you need.
Step 1: Add the PHP Repository
The default Ubuntu repositories don’t always contain the latest PHP versions. To get access to more versions (like PHP 8.2 or 8.3), we’ll add the famous Ondřej Surý PHP repository:
sudo add-apt-repository ppa:ondrej/php
After adding this repo, Ubuntu will know where to fetch newer PHP packages from.
Step 2: Install the update-alternatives package
update-alternatives is the tool that lets us switch between different versions of the same program (in this case, PHP). Install it with:
sudo apt-get install update-alternatives
Step 3: Install Your Desired PHP Version
Now let’s install the PHP version we want. For this tutorial, we’ll go with PHP 8.2:
sudo apt update sudo apt install php8.2
(You can replace php8.2 with php7.4, php8.1, or whichever version you need.)
Step 4: Switch Between PHP Versions
Here comes the fun part — switching versions. Run this command to open the selection prompt:
sudo update-alternatives --config php
You’ll see a list of installed PHP versions with index numbers. Just type the number of the version you want to use and hit Enter.
For example:
Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/php8.1 81 auto mode 1 /usr/bin/php7.4 74 manual mode 2 /usr/bin/php8.2 82 manual mode
If you type 2, PHP 8.2 becomes the default.
Step 5: Install PHP Extensions
Each PHP version you install needs its own set of extensions. For example, if your project requires XML, DOM, cURL, MySQL, or SQLite, you’ll need to install them specifically for PHP 8.2:
sudo apt install php8.2-xml sudo apt install php8.2-dom sudo apt install php8.2-curl sudo apt install php8.2-mysql sudo apt install php8.2-sqlite3
The idea is simple: if you install phpX.Y, you also install phpX.Y-extension for that version.
Wrapping Up
That’s it! Now you can:
-
Install multiple PHP versions on Ubuntu.
-
Switch between them easily using update-alternatives.
-
Add the extensions you need for each version separately.
This way, you don’t have to break one project to make another one work — everything stays neat and organized.
Comments: