Installing PHP and Configuring It with Apache on Ubuntu

PHP is a widely-used open-source scripting language especially suited for web development. This guide walks you through installing PHP on Ubuntu and integrating it with the Apache web server.

← Back

Step 1: Update Package Index

Make sure your package list is up to date:

sudo apt update

Step 2: Install PHP and Common Modules

Install PHP along with modules commonly used with Apache:

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

Step 3: Verify PHP Installation

Check that PHP is installed successfully:

php -v

Step 4: Configure Apache to Prefer PHP Files

Edit the dir.conf file so Apache loads PHP files before HTML files:

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

Find the following line:

DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm

Change it so index.php comes first:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

Save and close the file by pressing CTRL+O, ENTER, then CTRL+X.

Step 5: Restart Apache

Apply the changes by restarting Apache:

sudo systemctl restart apache2

Step 6: Test PHP with Apache

Create a simple PHP test file to verify everything is working:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

Then visit:

http://your_server_ip/info.php

You should see the PHP info page. Once confirmed, delete the test file for security:

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