PHP: Run HTML as PHP

The last time I end up with hundreds of HTML files with PHP codes dispersed in them. Tried to rename them all to .php but failed. To use them and enable the php code within, I have to run the HTML files as PHP.

How Apache web server works in resolving .php requests

Apache gets HTTP requests from client browsers, trys to connect a special file extension of the script requested such as .php to a mime type, in turn affiliates the mime type to a installed module, filter or extension such as PHP and passes the request to it.

In case Apache failed to find the right processor to parse the requested document, it presents the raw content of the file to client which is why we have websites showing the whole bunch of server side code in the browser.

Therefore, now that:

  1. You requests http://www.somesite.com/somescript.php in browser address bar.
  2. Apache detects that the mime type of .php is application/x-httpd-php.
  3. PHP engine is configured to run documents with that mime type.
  4. So it parses it and passes the results to Apache.
  5. Apache sends the results to client.

Pretty much.

Modify .html files as also application/x-httpd-php — the Solution to Run HTML as PHP!

To make PHP engine run .html and the php code in it, you only have to declare a different mime type than .html already is. Find or create a file of .htaccess (there’s a leading dot) in the directory in which you want all .html files to be parsed as .php and append or write the following text:

AddType application/x-httpd-php .htm .html
AddHandler x-httpd-php5 .htm .html

That’s it! Also you may use php5-script instead of x-httpd-php5 in some cases. And you may also try this with regular expressions to better match specific criteria:

<FilesMatch "\.(htm|html|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Looking to run PHP in HTML code? You mean writing and running PHP code from HTML right?

2 thoughts on “PHP: Run HTML as PHP”

  1. Pingback: PHP: Run .CSS files as PHP

  2. Pingback: How to execute / run PHP code inside JavaScript files?

Comments are closed.

Scroll to Top