Sometimes you need more than one PHP version on the same server. Maybe an old project still runs on 5.6, another one needs 7.2, and you want to test something on 7.4 before committing. Debian’s default repositories only ship one version, so you need a third-party source.

The Sury repository is the standard way to get multiple PHP versions on Debian. Ondrej Surý has maintained it for years and it’s trusted by most people running PHP on Debian.

Setting up the Sury repository

First, log into your server. If you’re on a remote machine, SSH in:

ssh root@debian9

Update your existing packages and install the prerequisites:

sudo apt update
sudo apt upgrade
sudo apt install ca-certificates apt-transport-https

Now import the repository signing key and add the source:

wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add -
echo "deb https://packages.sury.org/php/ stretch main" | sudo tee /etc/apt/sources.list.d/php.list

Update the package list so apt knows about the new PHP versions:

sudo apt update

Installing a specific PHP version

Pick the version you need and install it. Here are the commands for each available version.

PHP 7.4

sudo apt install php7.4

PHP 7.3

sudo apt install php7.3

PHP 7.2

sudo apt install php7.2

PHP 7.1

sudo apt install php7.1

PHP 5.6

sudo apt install php5.6

Common PHP modules

Most projects need a handful of standard modules. Install them alongside your PHP version:

# For PHP 7.4
sudo apt install php7.4-cli php7.4-common php7.4-curl php7.4-mbstring php7.4-mysql php7.4-xml

# For PHP 7.3
sudo apt install php7.3-cli php7.3-common php7.3-curl php7.3-mbstring php7.3-mysql php7.3-xml

# For PHP 7.2
sudo apt install php7.2-cli php7.2-common php7.2-curl php7.2-mbstring php7.2-mysql php7.2-xml

# For PHP 7.1
sudo apt install php7.1-cli php7.1-common php7.1-curl php7.1-mbstring php7.1-mysql php7.1-xml

# For PHP 5.6
sudo apt install php5.6-cli php5.6-common php5.6-curl php5.6-mbstring php5.6-mysql php5.6-xml

Switching between versions

If you’re running Apache with mod_php, the default version is whatever was installed last. To switch, change the enabled module and restart Apache:

sudo a2dismod php7.4
sudo a2enmod php7.3
sudo systemctl restart apache2

With PHP-FPM (which is what most people use these days), each site gets its own configuration. You set the PHP version per virtual host in your Apache or Nginx config:

# Apache with PHP-FPM
SetHandler "proxy:unix:/run/php/php7.3-fpm.sock|fcgi://localhost"

# Nginx
fastcgi_pass unix:/run/php/php7.3-fpm.sock;

This way you can run different PHP versions for different sites on the same server without any conflicts.