LJ Archive

Listing 1. The script output is read from the cache file and sent to the client's browser.

<?php
// path where cache files are stored
$CACHE_PATH="/tmp";

// cache time out in seconds
$CACHE_TIMEOUT=10;

// create cache file name based on
// the script name and the cache path
function cachefilename() {
global $PHP_SELF,$CACHE_PATH;

   return($CACHE_PATH."/".md5($PHP_SELF).".cache");
}

// check whether the script needs caching
function needscache($timeout) {
   clearstatcache();
   if (time()-filemtime(cachefilename())>$timeout)
      return(true);
   else
      return(false);
}

// read cache file and send it to the browser
function outputcache() {
   readfile(cachefilename());
}

// cache the script
function docache($buffer) {

   // write the script output into
   // the cache file
   $fp=fopen(cachefilename(),"w");
   if ($fp)
      fputs($fp,$buffer);

   // send the script output to
   // the browser
   return($buffer);
}

if (needscache($CACHE_TIMEOUT))
   // the script needs caching
   ob_start("docache");
else {
   // the script is cached so let's read
   // from the cache and exit
   outputcache();
   exit();
}
?>
LJ Archive