PHP: Using Output Buffering to Cache PHP FilesFirst of all, credit to Dennis Pallett for his code presented on PHPit (see link under References below) which helped to demystify output buffering. The code presented here is adapted from his script, with a number of changes to make it more suitable especially for Linux/UNIX systems. Creating Cache Files using Output BufferingThe principal behind output buffering is that you generate a page as normal using PHP, but the output is stored in memory rather than being sent directly to the browser. This gives a chance for lazy programmers to send some new header commands, but also makes it possible for us to write that output to a file. The logic behind the following script, which you can simply include at the top of a page, is as follows:
<?PHP
// Adapted for The Art of Web: www.the-art-of-web.com
// Based on PHP code by Dennis Pallett: www.phpit.net
// Please acknowledge use of this code by including this header.
// location and prefix for cache files
define('CACHE_PATH', "/tmp/cache_");
// how long to keep the cache files (hours)
define('CACHE_TIME', 12);
// return location and name for cache file
function cache_file()
{
return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}
// display cached file if present and not expired
function cache_display()
{
$file = cache_file();
// check that cache file exists and is not too old
if(!file_exists($file)) return;
if(filemtime($file) < time() - CACHE_TIME * 3600) return;
// if so, display cache file and stop processing
readfile($file);
exit;
}
// write to cache file
function cache_page($content)
{
if(false !== ($f = @fopen(cache_file(), 'w'))) {
fwrite($f, $content);
fclose($f);
}
return $content;
}
// execution stops here if valid cache file found
cache_display();
// enable output buffering and create cache file
ob_start('cache_page');
?>
Note: save this script as buffer.php and include it at the top of your HTML/PHP files. This script assumes the existence of a /tmp/ directory which is writable by the webserver. If this isn't the case, or you want to store cache files in a different location, you need to create a directory that is writable by the webserver (chgrp to the webserver user and chmod 775) and change the CACHE_PATH constant accordingly. It also assumes that $_SERVER['REQUEST_URI'] is defined, which isn't always the case on Windows XP or Microsoft IIS. See the user comments with the PHP documentation on Predefined Variables for a work-around. How do I use this script?You need to include this script before you output any content to the page. The subsequent HTML and PHP code will then only be accessed as necessary to update the cache file (once to start with and then every CACHE_TIME hours). Some things that you might want to consider if you use this on a live site:
Other then that it really is trivial. The beauty of using /tmp/ as the destination directory is that services such as tmpreaper can automatically clean up any garbage left behind when your website structure changes or pages are removed. To remove a cache file using PHP you'll need the following function: function cache_remove($path)
{
$file = CACHE_PATH . md5($path);
if(file_exists($file)) unlink($file) or die("Could not remove file: $file!");
}
where $path is the REQUEST_URI of the page to be 'un-cached' and CACHE_PATH is as defined earlier. Advantages of Output Buffering over other methodsThe beauty of this solution is that it's completely independent of the method you use to generate content. Whether pages are coded by hand, generated by a CMS or pulled from an external source makes no difference. Even the addressing scheme is irrelevant. Another benefit is that the cache files can be removed whenever you want without effecting the website. Finally, the whole script weighs in at just 20 lines of code! Contrast this to other methods where you have a horribly complicated CMS generating PHP files that are then parsed and served to the browser. If this is the only way of generating new content, or editing existing content, then it becomes difficult to make even some simple changes. An alternative approach is to 'spider' a dynamic site, one with search engine friendly URL's, to create a static version that can then be served from the same or another webserver. Again, as a webmaster you're a step removed when it comes to updating the content. Before anyone jumps in with their favourite caching system, I'm sure it's very good but there are a lot of them - all with different advantages, but none I think as simple. References |
|
|
© Copyright 2010 Chirp Internet
- Page Last Modified: 22 November 2009
|
|