Posted: 17th December 2013

Author: Steven

Tagged: Tutorials

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:

  1. 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.

  2. 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.

  3. Output the data as normal.

  4. 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. The code to do this 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.

Blog posts written by former QWeb employees are not necessarily an accurate indication of the current opinions of QWeb Ltd and the information provided in tutorials might be biased or subjective, or might become out of date.

Discuss this post

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 and you won't be added to any mailing list and your details won't be shared with any third party.