Our highest priority is to satisfy the customer through early and continuous delivery of valuable and working software.

Friday, April 27, 2007

Caching with PHP

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, you don’t have to edit any of your core application logic. You can just dropped in some extra code at the top and bottom of the index.php file. Here’s how it works:

$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)) {
echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
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());
ob_end_flush(); // Send the output to the browser

It should work on practically any PHP application.

Also, you can find more information about output buffering at http://www.php.net/manual/en/ref.outcontrol.php

No comments:

Post a Comment