PHP Caching to Speed up Dynamically Generated Sites

Lug
31

Regenerate only When Necessary

An alternative method involves checking to see if the data sources have been modified, this increases the load of each request slightly, because it requires a database connection in the case of DB-based sites, or a query of the file modification time of potentially a few files, it also makes the script slightly more complicated. However, this method prevents unecessary LARGE queries, such as those required to retrieve data for inclusion in a page, and prevents regenerating pages regularly even when nothing has changed. This is the approach used on this site.

All that is involved here is changing the if() clause, for example:

<?php
$cachefile = "cache/".$reqfilename.".html";

// Serve from the cache if it is the same age or younger than the last
// modification time of the included file (includes/$reqfilename)

if (file_exists($cachefile) && (filemtime("includes/".$reqfilename)
< filemtime($cachefile))) {

include($cachefile);

echo "

n";

exit;
}

// start the output buffer
ob_start();
?>

.. Your usual PHP script and HTML here ...

<?php
// open the cache file for writing

$fp = fopen($cachefile, 'w');

// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());

// close the file
fclose($fp);

// Send the output to the browser
ob_end_flush();
?>

This could be easily adapted to query a database containing a column for 'datemodified' or something similar.
Where not to use Caching

Caching should not be used for some things, the most obvious being search results, forums etc... where the content has to be up-to-the-minute and changes depending on user's input. It's also advisable to avoid using this method for things like a "Latest News" page, in general dont use it on any page that you wouldn't want the end users browser or proxy to cache.