Install or Upgrade to PHP 7.X on Ubuntu

Install or Upgrade to PHP 7.X on Ubuntu

The latest version of PHP is 7.x, the successor branch of PHP 5 which, since Ubuntu 16.04, has become the default version of this Linux distribution. The problem with PHP is that people (and I’m one of those people) tend to not take it up to date with the latest versions. However, this new version is not installed with the standard commands that we used to install the version 5, but, although it is in the repositories themselves, we must install their own packages as We show below.

STEP 1: Add a PPA for PHP 7.2 Packages

sudo add-apt-repository ppa:ondrej/php

STEP 2: Update the local package cache

sudo apt-get update
sudo apt-get upgrade

For Apache:

STEP 3: For Apache, install the new packages (To configuring PHP-FPM With Nginx, go to step 6)

sudo apt-get install php7.2

If you are using MySQL, make sure to re-add the updated PHP MySQL bindings:

sudo apt-get install php7.2-mysql

If you want to install all common packages, you can run following command

sudo apt-get install php7.2-cli php7.2-common libapache2-mod-php7.2 php7.2 php7.2-mysql php7.2-fpm

You might need to install mbstring package also:

sudo apt-get install php7.2-mbstring

STEP 4: To update web-server configuration

Apache with php-fpm:

a2disconf php5-fpm
a2enconf php7.2

Apache with mod_php:

sudo a2dismod php5
sudo a2enmod php7.2

STEP 4: Restart Apache

sudo service apache2 restart


For Nginx:

STEP 6: If you are using Nginx as the web server and PHP-FPM to execute PHP code, install the new PHP-FPM package and its dependencies

sudo apt-get install php7.2-fpm

If you are using MySQL, make sure to re-add the updated PHP MySQL bindings:

sudo apt-get install php7.2-mysql

STEP 7: Now you need to update fastcgi_pass configuration to point new version file. Open the default site configuration file

sudo nano /etc/nginx/sites-enabled/default

In the file, go to Server > location ~ \.php$ > fastcgi_pass. Probably it would look like below:

fastcgi_pass unix:/var/run/php/php5-fpm.sock;

change the above with new version:

fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;

Similarly, you can do the same with your any other virtual sites defined in /etc/nginx/sites-enabled.

STEP 8: Restart Nginx

sudo service nginx restart

STEP 9: Before upgrading, if you want to do it from scratch means want to uninstall the existing nginx and install a fresh version.

To uninstall:

sudo apt-get purge nginx nginx-common nginx-full

To install:

sudo apt-get update
sudo apt-get install nginx

Clean up:

Run phpinfo(), php –info or php -v to verify PHP 7.2 setup.

If all is well, you can clean up old versions:

sudo apt purge php5*

Now you have working PHP 7.2 environment.

Congratulations! You’ve successfully installed and configured Apache2 / Nginx with PHP / PHP-FPM support on Ubuntu servers.