Weblincs.co.uk is proud to...
As a part of our ongoing que...
WebLincs.co.uk is proud to a...
Some web sites and applications have complex ways of parsing and manipulating data before the information is presented to the visitor or user. This article addresses the need for page caching, a way of processing the information once and caching the page's content for any subsequent views. I'm writing this article in view of providing page caching for simple CMSs (Content Management Systems). The key points for processing page caching are as follows:
So, with all of that said and done let's look at the code to perform this functionality:
// The name and path for the cache file $cache_file_directory = "/home/username/public_html/cache/"; $cache_filename = $cache_file_directory . __FILE__ . ".cache"; // If the cache file exists, present it if(file_exists($cache_filename)) { $file_handle = fopen($cache_filename, "r"); echo fread($file_handle, filesize($cache_filename)); fclose($file_handle); } else { // Create a temporary swap file $swap_filename = $cache_file_directory . md5(getmypid()); $swap_handle = fopen($swap_filename, "w"); // Start the output buffer from here ob_start(); /*** Process and render your web page here ***/ // Write the contents of the output buffer to the swap file fwrite($swap_handle, ob_get_contents()); fclose($swap_handle); // Rename the swap file to the final cache file name rename($swap_filename, $cache_filename); // Stop the output buffer and clear its contents ob_end_flush(); }
As you can see by the above code, the functionality to perform page caching is quite simplistic, although there are a few points to consider:
One important point I would like to cover is to do with the way we use swap files to stop file write conflictions. This is necessary so that two simultaneous fopens do not cause the cache file to erroneously written if two visitors try to create a cache file at the same time.
Back to Web Development Articles.