Home » » Cache in PHP

Cache in PHP

Written By 1 on Friday, June 7, 2013 | 2:59 AM

Follow the following steps to implement cache in Core PHP?

  • Create a folder with write permission where you store the output of page
  • At the start of file, check whether you have already stored the output of file or not
  • If you have already stored the output in cache, then get the contents from cache instead of executing the code
  • If Not, first prevent the php to send the output to the browser (ob_start php) and store the output in cache folder
  • Create the page in your application from where you can delete all the files, stored in cache folder (when website updates)



See Example
$fileName="xxxx.html";
$cacheFolder="/cache/";//must be writeable

//check if file in cache
if(file_exists($cacheFolder.$fileName,'r'){
$output = file_get_contents($cacheFolder.$fileName);
}else{
ob_start(); //stop sending output to the browser
//do work
//do work
//do work
$output = ob_get_contents();
ob_end_flush();
$fp=fopen($cacheFolder.$fileName,'w');
fwrite($fp, $output);
fclose($fp);
}
echo $output;



0 Comment:

Post a Comment