970_90

Friday, 7 June 2013

Cache in PHP - Speed Up your website

Follow the following steps to implement caching 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;


No comments:

Post a Comment