Use multiple PHP versions on Ubuntu with Apache 2/CLI and switch PHP modules

Submitted by Peter Majmesku on Thu, 11/10/2016 - 16:55

I needed an easy ability to switch multiple PHP versions on my local development environment. This ability should include the command line interface and webserver components of PHP. Here I am sharing my findings with you.

Also debugging is very important in my development day-by-day work. Since PHP 7 you can easily enable/disable modules like Xdebug via command line. The commands below can be used already on Ubuntu 14.04. The instructions here are also valid for the Windows 10 subsystem for Linux 10 (WSL).

You can use multiple PHP versions with one Apache server. Easily install them via the Apt package manager by the famous PPA from Ondrej. Then you can install multiple PHP versions like so:

sudo apt install php7.1 php5.6 php7.0

For being able to switch the PHP versions within the Apache webserver, you need the Lib Apache packages. You can install them like so:

sudo apt install libapache2-mod-php7.0
sudo apt install libapache2-mod-php7.1
sudo apt install libapache2-mod-php5.6

Afterwards you are able to switch the PHP version, which is being executed by Apache. E.g.:

sudo a2dismod php7.0
sudo a2enmod php5.6
sudo service apache2 restart

To switch he PHP CLI version, you can use the "update-alternatives" command. This command let's choose you the various versions of your program. In the background it will create symlinks for you. For getting into the version chooser dialogue, execute the following command:

sudo update-alternatives --config php

Switching PHP extensions like Xdebug

To switch PHP extensions for a specific PHP version, you can use the "phpenmod" and "phpdismod" commands. For enabling the Xdebug PHP extension for PHP 7.0, use the following command:

sudo phpenmod -v 7.0 xdebug

To enable a module for ALL PHP versions, you can use the following command:

 sudo phpdismod -v ALL xdebug

For allowing the command above, there must not be the zend_extension config line in your php.ini file, which was valid for PHP 5.x versions, without the phpenmod command:


So you php.ini config for Xdebug can look like follows:

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000
xdebug.idekey = PHPSTORM