Instant caching with PHP
5th May 2003
I’ve been getting more database timeout errors today, probably due to increased traffic from links to recent entries. A permanent solution would be to switch to generating static HTML (this site is currently dynamically generated for every request), but I don’t have time for a full re-write at the moment. Luckily, PHP offers an extremely simple solution to dynamic caching in the form of output buffering. The front page of the site (which generates by far the most traffic) is now served from a cached copy if it has been cached within the last 5 minutes. Best of all, I didn’t have to edit any of my core application logic—I just dropped in some extra code at the top and bottom of the index.php
file. Here’s how it works:
<?php
$cachefile = 'cache/index-cached.html';
$cachetime = 5 * 60;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
include($cachefile);
echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
exit;
}
ob_start(); // Start the output buffer
/* The code to dynamically generate the page goes here */
// Cache the output to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush(); // Send the output to the browser
?>
I’ve added a few extra bits of logic to check that the page being cached isn’t itself a database error page, but the above is the bulk of the code. Best of all, due to the nature of output buffering it should work on practically any PHP application.
More recent articles
- Trying out QvQ - Qwen's new visual reasoning model - 24th December 2024
- My approach to running a link blog - 22nd December 2024
- Live blog: the 12th day of OpenAI - "Early evals for OpenAI o3" - 20th December 2024