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
$cacheFolder="/cache/";//must be writeable 

//check if file in cache
$output = file_get_contents($cacheFolder.$fileName);
ob_start(); //stop sending output to the browser
//do work
//do work
//do work
$output = ob_get_contents();
fwrite($fp, $output);
echo $output;

No comments:

Post a Comment