Published Tuesday 17th December 2013

Caching: A quick effective way to speed up your site

While caching is becoming slightly less popular due to the forever increasing speed of networks, it can still be useful for both mobile data and slow connections. Caching, like everything, should only be used in certain instances such as when content is not regularly updated. Putting a caching system on an e-commerce system, for instance, would not be a useful development, unless it is a very short caching system (e.g. an expiry time of 15 minutes so that the page reloads faster).

Caching works in a very simple manner, the idea is as follows:

  • Check to see if a file has been previously made from cached data - if it has, and is within a specified time frame, then load the file and exit the script.
  • If it isn't found, or isn't in the specified time frame, then: get data from database and do whatever scripting necessary before output.
  • Output the data as normal.
  • Create/update a html cache file with the output data.

The primary advantage of caching is that any scripting has already been done before and therefore it is just outputting data. That means there is no database fetching and no logic processes, which in turn means less memory and faster loading times. One way to do this in PHP is as follows:

//Current page
$currentUrl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$urlPath = parse_url($currentUrl,PHP_URL_PATH);
$urlPath = trim($urlPath,'/');
$currentUrl = explode('/',$urlPath);
$currentPage = str_replace('.php', '', $currentUrl[count($currentUrl)-1]);

//Cache Settings
$cacheFolder = '/cache/';
$cacheFile = $cacheFolder . $currentPage . '.html';
$cacheTime = 60; //Amount of cache time in minutes

//Check file exists
if(
   file_exists($cacheFile)
   && time() - $cacheTime*60 < filemtime($cacheFile)
){ //Cache file found within $cacheTime minutes
   include($cacheFile);
   exit;
} else { //Cache file not found or not within the $cacheTime minutes
   //Logic / Scripting
   $db = mysqli_connect($dbHostname, $dbUsername, $dbPassword, $dbDatabase);
   $result = mysqli_fetch_assoc(mysqli_query($db, '
      SELECT * FROM tblPages 
      WHERE fldPage = \'' . mysqli_real_escape_string($db, $currentPage) . '\'
   '));

   //Get contents
   ob_start(); //Use output buffering which stores all output data in a buffer rather than actually outputting it
   include('/header.php');
   include('/cmsPage.php'); //This would have outputs on the $result var
   include('/footer.php');
   $buffer = ob_get_clean(); //Get the captured output

   //Output
   echo $buffer;

   //Save file (updates file time)
   $fp = fopen($cacheFile, 'w');
   fwrite($fp, $buffer);
   fclose($fp);
   exit;
}

Hopefully from the example above you will be able to make your own caching system. Feel free to leave comments on improvements, ideas or general information about caching.

Photo of Steven

Steven

Steven is a former QWeb Ltd director and continues to work with us as a contract developer. He's experienced with a number of front-end technologies but is primarily focussed on back-end development, particularly building complicated plugins and bespoke mechanisms for Wordpress.

Blog posts are written by individuals and do not necessarily depict the opinions or beliefs of QWeb Ltd or its current employees. Any information provided here might be biased or subjective, and might become out of date.

Discuss this post

Nobody has commented yet.

Leave a comment

Your email address is used to notify you of new comments to this thread, and also to pull your Gravatar image. Your name, email address, and message are stored as encrypted text. You won't be added to any mailing list, and your details won't be shared with any third party.

This site is protected by reCAPTCHA and the Google Privacy Policy & Terms of Service apply.