Guide: Installing PHP for Apache (Ubuntu 16.04 / 17.10)

Last updated on

In this guide we will install and configure PHP for Apache on  Ubuntu 16.04 / 17.10.

1. Install PHP

Let’s begin by updating the package lists.

sudo apt-get update

Now install PHP and associated packages.

sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

2. Configure Apache

We will need to alter the dir.conf file to tell Apache to load index.php as the default index page first instead of index.html.

sudo nano /etc/apache2/mods-enabled/dir.conf

Make sure index.php appears first.

/etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
        DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Save file and exit. (Press CTRL + X, press Y and then press ENTER)

Restart Apache.

sudo systemctl restart apache2

3. Test PHP

We can now load a PHP test script to our web root. Your web root may be in /var/www/html/, or if you followed our previous guide on setting up multiple domains, your web root may be in /var/www/example.com/public_html

Let’s create a file info.php using the nano text editor.

sudo nano /var/www/html/info.php

Paste in the follwing. (If using PuTTY, click to right mouse button to paste)

/var/www/html/info.php
<?php
phpinfo();
?>

We can now load this in the browser by going to http://example.com/info.php or http://your_ip/info.php

If you don’t know your IP, you can find out with:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

Once you’ve confirmed PHP is working correctly, it’s important to delete info.php as it contains information that could be useful to hackers.

sudo rm /var/www/html/info.php

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

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