How to include PHP code in an HTML file
Yes it is possible to run PHP code inside a regular HTML file!
Apache has a predefined configuration which decides what all file extensions are allowed to use PHP code such as .php, .php3 files. While serving a webpage to the client, it (apache web server) will first verify this condition and then only it will interpret and execute PHP code snippets written inside a particular file. But if we change this default configuration of Apache web server then we can include PHP code snippets in HTML files and server will execute them.
In order to change this default configuration we need to make a small change in the .htaccess file as explained in steps given below.
# Create a new file named test.html having following source code.
<html>
<head>
<title>How to include PHP code in an HTML file</title>
</head>
<body>
A sample PHP code is written below:
<br />
<strong>
<?php
echo "This output has been generated by PHP code";
?>
</strong>
</body>
</html>
At this point if we try to run this file through Apache web server, (as expected) the PHP code in the HTML file will be ignored. Check out the screenshots below.
# Now create a file named .htaccess and add the following line in it -
AddType application/x-httpd-php php php4 php3 html htm
# Save this in the same folder in which test.html is present. And now run the test.html via Apache web server and you will get the output as shown below.
Also if you view the source code of the test.html which has been generated by a web browser you will notice that PHP code has been evaluated. Check out the screenshot shown below.
Thats it!
Explanation
The one line code in .htaccess file tells the Apache to execute PHP code present in all files having extension as .php, .php4, .php3, .html and .htm.
Benefits
- Normally files with .html extension are considered more search engine friendly as compared to .php. Also URLs with .html files are more user friendly than .php.
- Suppose you have a website which is purely written in HTML and now if you want to use PHP in it, normally you will have to manually change all files having .html extension to .php and then only you will be able to include PHP code in them. Also you will have to change internal webpage links accordingly. This technique can come handy in such situations.