Published Tuesday 17th December 2013
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:
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.
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.
Nobody has commented yet.
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.