How to install PHP, Apache and switch PHP versions (5.6, 7.0, 7.1, 7.2) in Ubuntu

October 25, 2017

This is the quickest way that I’ve found to install PHP and setup Apache2 and switch the versions:

Using this guide you will only be able to use currently supported versions. The supported versions are listed here: http://php.net/supported-versions.php

Step 0

In case you have something messed up or you have old version on your machine you will have to run a remove command:
sudo apt-get purge php* apache2 libapache2*

Step 1

Add repository and run update:
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Step 2

Run install command:
sudo apt-get install php

Permissions

To be able to edit files inside apache document root directory run these permission commands:
Run command whoami to get your username
sudo adduser youruser www-data
sudo chown -R www-data /var/www
sudo chmod 770 -R /var/www

How to check php version on apache

Run sudo service apache2 start
Create a file at /var/www/html/index.php with contents:
<?php
phpinfo();

It should show your version at the top, something like “PHP Version 7.10.10-1+ubuntu16.04.1+deb.sury.org+1”.  Which means you have PHP 7.1 running on your apache.

How to check php version for command line

Run this command:
php -v

How to install other php versions

Run install command:
sudo apt-get install php7.0 php5.6

How to switch php version from 7.1 to 5.6:

sudo update-alternatives --set php /usr/bin/php5.6
sudo a2enmod php5.6
sudo a2dismod php7.1
sudo service apache2 restart


Thank you for reading. If you have any questions let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *