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:
<?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
?>
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