Click here to Skip to main content
Click here to Skip to main content

Caching Output in PHP

By , 23 Dec 2009
 

Introduction

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

Using the Code

 
Put the first function cache_start in the beginning of php script and the second cache_end in the end of script.
 
$_time : cache time
$dir : directory to cache files
 
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();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

koula7
Software Developer
Greece Greece
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralUmmemberRockyonfire16 Aug '10 - 11:24 
GeneralRe: UmmemberS.M. Zamshed Farhan11 Jan '13 - 5:52 
Very basic, but heavy helpful. Does it ensure in shared memory?
GeneralMy vote of 1memberdung_90ghost5 Apr '10 - 0:47 
GeneralGood TipmemberJon Anthony17 Dec '09 - 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 23 Dec 2009
Article Copyright 2009 by koula7
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid