Tested on: Ubuntu 22.04

Default php version is 8.1 and we want install php 7.4

Ondrej PPA contains PHP 8.2, 8.1, 8.0, 7.4, 7.3, 7.2, 7.1, 7.0 & PHP 5.6 packages.

First update the system

sudo apt update && sudo apt upgrade 

1. Check Active PHP Version

php -v 

2. Install php on system

Set the required PPA wich contains any PHP version.

 
  1. Install dependancy:
    sudo apt install software-properties-common ca-certificates lsb-release apt-transport-https 
  2. Enable Ondrej PPA 
    LC_ALL=C.UTF-8 sudo add-apt-repository ppa:ondrej/php 
  3. Update the Apt package manager cache.
    sudo apt update 
  4.  PHP versions on your system.
    • Install PHP 7.4:
      sudo apt install php7.4 

    You can install multiple PHP versions on a single Ubuntu system.

 

  1. PHP applications depend on various extensions to extend their features. That can also be installed using the following syntax:
    sudo apt install php7.4-[extension]
    

    for example:

    sudo apt install php7.4-interbase php7.4-mbstring php7.4-curl 

    Users who have installed different PHP versions, need to replace 8.2 with the required PHP versions.

 

3. Choose Default PHP Version 

with `update-alternatives` command you can set the default version you want to be active in your system

sudo update-alternatives --config php
There are 4 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php8.1   81        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.4   74        manual mode
  3            /usr/bin/php8.0   80        manual mode
  4            /usr/bin/php8.1   81        manual mode
  5            /usr/bin/php8.2   82        manual mode

Press  to keep the current choice[*], or type selection number: 2

4. Removing PHP

If you want to remove the php version 8.1 from your system you can do:

sudo apt remove php8.1 

Also, uninstall all the modules for that version with the following command:

sudo apt remove php8.1-*