How to install the latest version of PHP under Ubuntu on Windows (WSL)

January 1, 2020 at 7:05 PM

The latest version of PHP is not often immediately available in Ubuntu repositories, even less under Ubuntu on Windows (WSL: Windows Subsytem for Linux) where the installed version is often the LTS (Long Term Support) version.

To install the latest version of PHP, you have to add the ondrej/php repository.

Add the repository automatically

Nothing complicated here, let's just execute the following command :    

$ sudo add-apt-repository ppa:ondrej/php

If the repository has been successfully added, you are in luck! You can go directly to the "Installing PHP" section.

If you get the error below, then you need to add the repository manually.

Cannot add PPA: 'ppa:~ondrej/ubuntu/php'.
ERROR: '~ondrej' user or team does not exist.

Add the repository manually

It is necessary to edit the file /etc/apt/sources.list.

$ sudo vim /etc/apt/sources.list

Add the following two lines to the end of the file:

deb http://ppa.launchpad.net/ondrej/php/ubuntu bionic main
deb-src http://ppa.launchpad.net/ondrej/php/ubuntu bionic main

Note: these two lines are correct if you are using Ubuntu 18.04 (Bionic) or Ubuntu 18.10 LTS. Replace "bionic" with the name of your Ubuntu version. Just look at the already existing lines of the file /etc/apt/sources.list.

Save the changes (:wq if you are also using vim) and update the repositories:

$ sudo apt-get update

Another error!!

Hit:5 http://security.ubuntu.com/ubuntu bionic-security InRelease
Get:1 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease [20.8 kB]
Err:1 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease
The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C

To solve this problem, execute the following command:

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4F4EA0AAE5267A6C

Note that the last option of the command refers to the key in the error message (4F4EA0AAE5267A6C). If your error message contains a different key, you must change the command accordingly.

If you would like more information on this problem, see this article: Fix apt-get update “the following signatures couldn’t be verified because the public key is not available”.

Once this command is executed, refresh the repositories again:    

$ sudo apt-get update

Installing PHP

To install the latest version of PHP (7.4 at the time I'm writing this article), run the following command:

$ sudo apt-get install php7.4

Thanks to the "ondrej/php" repository, you can install any version you want:

$ sudo apt-get install php7.3
$ sudo apt-get install php7.2
$ sudo apt-get install php7.1

There you go! You can check the version of PHP with the command:

$ php -v
PHP 7.4.0 (cli) (built: Nov 28 2019 07:27:06) ( NTS )