Building an HTML Cache of your Database Driven Site

You might have started your site off as static HTML files, and that worked for awhile, but eventually due to the size and management needs of your site you switched to a dynamic database driven setup. If your success continues there will come a point when you need to go back to what you did originally and serve static HTML files. This doesn't mean that you will need to do without the nice database driven backend you've developed, but rather you need to tweak it to generate static HTML files.

The reason for this, if it wasn't obvious, is that database driven pages use significantly more server resources than static HTML pages. When your site gets large and or popular the number of database queries can quickly slow down your site. By caching your database driven pages as static HTML pages you will speed up your site. Also, since you will only be running your database related code maybe once per day or less, you will not need to code it as efficiently as you might need to normally. This is definitely a good thing if you're not a PHP expert.

Building the Caching System

When I recently set out to do this I thought it would be a very involved process, but luckily thanks to a simple function it actually only took a couple hours to convert a page from database driven to built off an HTML page cache. I knew that I'd basically need to take everything I normally print to the screen and print it to a variable instead and then write the contents of that variable to an html file. I thought I would have to go through and edit all those print's and echo's by hand, but the below handy function takes care of all of that.

function get_include_contents($filename) {
   if (is_file($filename)) {
       include $filename;
       $contents = ob_get_contents();
       return $contents;
   echo "no file";
   return false;

Basically you feed it a filename and it takes all the normal output from that file returns it as a variable. You'd call it as outlined below and then write the contents it returns to a file.

$string = get_include_contents('/full/path/to/your/include/file.php');

$handle = fopen("/full/path/to/your/cache/htmlfile.html", "w");

if (fwrite($handle, $string) === FALSE) {
       echo "Cannot write to file ($filename)";
   echo "Success, wrote content to file ($filename)";