How do I use PHP in .html files?
PHP is a wonderful scripting language for adding dynamic features to your web pages. But most web servers are only configured to look for an process PHP commands in files that end with a .php extension. What if you wanted to include PHP commands in .html files, essentially treating them the same as .php files?
If you’re running the Apache web server, which most hosting services do, this is actually very simple to do. Internally, the web server maintains a list of file extensions and actions to take when a particular file type is requested by a browser. For .php files, the default action is to run the contents of the file through the PHP processor, which then runs the PHP commands it finds embedded in the file. The browser actually gets sent the processed file, not the raw .php file. All you need to do, then, is tell the web server to treat .html files exactly the same as .php files.
The easiest way to do this is with a .htaccess file, although this feature is not enabled on all web hosts. But try it first. Add these two lines to the file:
RemoveHandler .php .html .htm AddType application/x-httpd-php .php .html .htm
Be sure to keep a backup copy of the .htaccess file before you make these changes. Upload the modified .htaccess file to your web server and try to load a page. If you get an error, replace the .htaccess file with the backup and try the alternate method using cPanel instead. (If your host doesn’t use cPanel for management the following instructions won’t work.)
From the cPanel, click on the “Apache Handlers” icon. You should see a list of file extensions and actions. You just need to add a mapping for the .html extension. Just copy the mapping used for .php files.
That’s all you need to do. Now you can embed PHP commands in your .html files and no one will be the wiser. It really shouldn’t matter to the browser if you’re using PHP or not, so why signal that fact with a .php extension?
Comments
3 Responses to “How do I use PHP in .html files?”
Leave a Reply
You imply that there is something “bad” about using the .php extension for our PLRSB pages. Is there some evidence that Google frowns on the practice, or that there is some other disadvantage?
No, it has nothing to do with search engines. It’s not a biggie, but I just prefer not to use .php if I don’t have to. Why advertise to the world what kind of scripting system you’re using? If you decide to change it, you’ll have to change all your URLs to match the new extension, or else map the .php extension to the other scripting language. It’s a small thing, but I just prefer to see .html or even no extension at all. The extension is really irrelevant, it’s an anachronism of the early Web that’s still around.
Eric
[…] finally caught up! My contribution for Day 3 is A Winning AdSense Business Plan and for Day 4 is How do I use PHP in .html files?. The former explains one simple (but time-consuming) way to create an AdSense network. The second […]