Caching Output

calendar December 7, 2009

High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again.

Put the first function cache_start in the beginning of php script and the second cache_end in the end of script.

Code:

function cache_start($_time, $dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $cachetime = $_time;
  ob_start();

  if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
  {
    include($cachefile);
    ob_end_flush();
    exit;
  }
}

//——————————————–

function cache_end($dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $fp = fopen($cachefile, 'w');
  fwrite($fp, ob_get_contents());
  fclose($fp);
  ob_end_flush();
}

//————————————–
$_time : cache time

$dir : directory to cache files

admin

Leave a Reply

You must be logged in to post a comment.