From HTML to PHP

ken's picture

I have a website that was originally written entirely in HTML (and CSS). This was originally done intentionally and there were good reasons for sticking to HTML. But, over time, site maintenance has become increasingly complex and time consuming, so I began the task of migrating the site to PHP. The main reason for moving to PHP was to use ‘include’ statements so that the menus, logos, headers, footers etc. were all in one place so the whole site can be updated more easily. So how easy is it to move to php? Actually much easier than you might expect!

The first thing to consider is that the site is already indexed by all the search engines – with a page rank etc. If you create a new file ‘index.php’ to replace ‘index.htm’, then the search engines will see this as a new and different page (with duplicate content on it). Clearly a priority is not to lose the page ranking of each page – i.e. so index.php could inherit the page rank of index.htm. There are several ways this can be done – and they mostly involve a .htaccess file.

One option would be to create a 301 redirect, which informs the search engine the site has moved to its new location – a strategy which still results in a temporary dip in traffic. A better way would be to set the server up so that when it receives an HTML request, it automatically parses the file as PHP. That way the files can keep their existing names, but now PHP code can be included in amongst the html. This is the ideal solution, and it is pretty simple to implement.

The .htaccess file is a very powerful tool which can contain instructions for the server which are applied to the directory in which it is saved, and all subdirectories. As this instruction should be applied to the whole site, the .htaccess file needs to be in the root directory. So, first check if you already have a .htaccess file, if you do, just add the following line to it. If not, open notepad and save a file called .htaccess (Notice the . which makes htaccess the file extension). Inside the file you need;

addtype application/x-httpd-php .php .htm

And thats it! A similar effect can be got using addHandler instead of addType. This simple line adds the php application to .htm extensions. Sadly this didn't work for me though. Due to my bad hosting service, I am not allowed to use either addtype or addhandler - each time I did I received a '500 Internal Server Error' message. Fortunately (courtesy Sven) a work around was found. Again using .htaccess, but this time the powerful modrewrite;

RewriteEngine On
RewriteBase /
RewriteRule ^(.*)\.htm$ $1.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.php$ $1.htm

Now when a htm request comes in, the htm is stripped off, and a php added - i.e. the php file of the same name is then served. The downside of this is that I have to rename all my files to php - but at least it got around the problem!