How to parse HTML files with apache / php7

TL;DR version: here’s how to parse HTML files with PHP hypertext preprocessor on apache 2.4x webserver, and PHP7 on linux

In PHP 7, the newest and ever more popular version of the PHP scripting language, the only files that are parsed by default are the ones that have .php, .phtml, or .php3/php4/php5 extensions. I don’t know who might still be using .php3, .php4 (never seen anyone use this one), or .php5 file extensions, but I’m sure many of you still usually use HTML files, and want to insert some PHP code into it.

Obviously, even though a lot of discussion is against the practice of parsing HTML files with PHP, you might still need this option. Regardless of whether you are a beginner or a pro in the art of website creation, scripting, web programming and alike, you still need to be able to parse files with the HTML or HTM extension, as PHP files, because integrating some PHP code into HTML and viceversa, it’s the easieast way to quickly test out something in a browser. So set aside the “best practices” pride for now, and just accept it as a fact that a lot of people still need this option 🙂

To be able to parse the PHP code in the HTML files, make sure you’ve installed not just the client version, but the actual PHP module for apache.  Go to a terminal window and type:

sudo apt install libapache2-mod-php7

and press enter.Representative image for how to Parse HTML files with PHP on apache 2.4 / linux Confirm your password and wait for the installation.

Then once it’s done (or if you already had this module installed), open the following config file in your favourite editor (terminal or graphical, just make sure you open it with superuser privileges, e.g. sudo or gksudo).

/etc/apache2/mods-available/php7.0.conf

Add the following lines under the existing <FilesMatch… sections

(keep capitalization as it is shown, correct capitalization is important !)

<FilesMatch “.html|.htm”>
SetHandler application/x-httpd-php
</FilesMatch>

Save the file. Then go to the terminal prompt again, and type

apachectl restart

and press enter.

If the config modification was correct, from now on you’ll be able to include PHP code into your HTM or HTML files, and have them parsed by the PHP interpreter.

 

Leave a Reply

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