How to switch PHP versions for apache2 and command line?

Why we need to switch PHP versions

Lets say we have an older version of PHP installed. We want to upgrade the PHP to the latest version. After the installation we will end up having two PHP versions. From the command line if we type the following command then it will show us the active PHP version for command line (PHP cli):

$ php -v 

//Output
PHP 7.3.3-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Mar  7 2019 20:31:26) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.3, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.3-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

The command line php version will automatically be the latest version installed. But if it does not activate the latest PHP then we can use the following command to activate the latest version of PHP:

$ sudo update-alternatives --config php

// Sample output
Selection       Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.3   72        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode
  3            /usr/bin/php7.1   71        manual mode
  4            /usr/bin/php7.2   72        manual mode
Press  to keep the current choice[*], or type selection number:

Now if we have apache2 installed, then apache2 will still point to the old version of PHP. You can check the active PHP version used by apache2 using following code in the index.php file. Then simple browser: http://localhost

phpinfo();

Let say the apache2 is using PHP version 7.0 and we want to upgrade to the PHP version 7.3. We can easily do that using following commands:

From PHP 7.0 => PHP 7.3

$ sudo a2dismod php7.0
$ sudo a2enmod php7.3
$ sudo service apache2 restart

After switching the new version if we find incompatibility, then we can easily switch back to the old version using following command:

From PHP 7.3 => PHP 7.0

$ sudo a2dismod php7.3
$ sudo a2enmod php7.0
$ sudo service apache2 restart
Share