If your Apache 2 web server is failing to execute PHP files, learn how to quickly remedy this issue.
How many times have you set up a web server with Apache 2 only to find out that when you attempt to view a page with a .php extension, the page either attempts to save onto the local drive or it displays the PHP code in the browser? This is bad on multiple levels. First off, your website isn’t functioning properly; even worse is the idea that someone could get a first-hand glimpse of your code, which is not only a frustration, but a possible security issue.
Considering this is an easy fix, there’s no reason to avoid working with PHP and Apache 2. But how do you fix it? Let me show you. Note: I demonstrate this process on Ubuntu Server 16.04, running the latest releases of Apache 2 and PHP.
SEE: Power checklist: Managing and troubleshooting servers (Tech Pro Research)
The first thing we must do is modify the main Apache 2 configuration file. To do this, open a terminal window and issue the command:
sudo nano /etc/apache2/apache2.conf
With apache2.conf open, all you have to do is add the following to the bottom of the file:
SetHandler application/x-httpd-php
​
Save and close apache2.conf.
In order to get PHP to function properly, you have to disable the mpm_event module and enable the mpm_prefork and php7 modules. To do this, go back to your terminal window and issue the command:
sudo a2dismod mpm_event && sudo a2enmod mpm_prefork && sudo a2enmod php7.0
You’re ready to restart Apache 2. Because we’ve disabled/enabled modules, we have to do a full restart of Apache 2 (instead of a reloading of the configuration files). To restart Apache, go back to the terminal window and issue the command:
sudo service apache2 restart
You should now be able to point a browser to a PHP file and watch it execute properly, as opposed to saving to your local drive or displaying code in your browser.
That’s it–Apache 2 should be functioning exactly as you need.
I warned you this would be a simple fix. Apache 2 is a very admin-friendly web server to configure and manage. Although one would think executing PHP would be an out-of-the box feature, it’s a very easy issue to resolve.
Happy Apache’ing!