How to run PHP code in .html or .htm files

No Comments » Written on January 9th, 2013 by
Categories: Website Development

PHP code is in fact compatible with HTML code, allowing for more dynamic developments. You can include PHP code within a HTML code or vice versa as long as you correctly keep the syntax for each language code. However, for PHP code to be executed on the server side, it needs to run in files with the .php extension. The .php file extension tells the server how to execute the code within the file. Including PHP code in a .html or .htm file will not work as the server will execute the code differently because of the extension. So how to override the server settings and tell it to execute PHP inside .html / .htm files as well?

This is something very possible, and for many webmasters a life saver. For me, having some website areas that can be updated easily from within a single file and go live on multiple HTML pages at once was the reason to look into this. I didn’t want to change the page extension as people have bookmarked specific pages ending in .html, and not in .php.

Whatever your reason is for including and executing PHP code in a .html / .htm file, here is how you can do that. You will have to override a server command and tell it to also execute PHP code within .html or .htm files. This can be done very easily with the .htaccess file (for Apache / Linux servers). If you have a .htaccess file in the root of your hosting account, simply open it and add the following line of code (or create the file if you don’t have it – make sure you name it .htaccess and put it in the root folder of your website):

Command to execute PHP in .html / .htm filesAddType application/x-httpd-php .html .htm

If this doesn’t work, simply replace the above line of code with the following (for PHP version 5):

Command to execute PHP in .html / .htm filesAddType application/x-httpd-php5 .html .htm

That’s it. If you are using an Apache / Linux server, most likely you also have the PHP environment as well, but just in case, look over your hosting account specifications.

Addition: In the case you have used both code types listed above and it still not works on your website (you get to download the webpage when you visit the website instead of parsing the correct code in the browser), check with your hosting provider as the code to be included in the .htaccess files might be a little different. Among the hosting providers I use are 1and1, and they require me to use a different code in the .htaccess file like bellow:

1and1 Hosting Command to execute PHP in .html / .htm filesAddHandler x-mapp-php5 .html .htm