<?php
// define createCache
function createCache ( $content , $cacheFile ) {
$fp = fopen( $cachefile , ‘w’ );
fwrite( $fp , $content );
fclose( $fp);
}
// define getCache
function getCache ( $cacheFile , $expireTime ) {
if ( file_exists ( $cacheFile ) && filemtime ( $cacheFile ) >( time() - $expireTime ) ) {
return file_get_contents( $cacheFile );
}
return false;
}
// start output buffering
ob_start();
// check if a valid header cache exists
if ( !$header = getCache( ‘headerCache.txt’ , 86400 ) {
// display header section
?>
<html>
<head>
<title>Cached Page</title>
</head>
<body>
The header section is updated on a daily basis.
<?php
$header = ob_get_contents();
ob_clean();
createCache( $header , ‘headerCache.txt’ );
}
// check if a valid body cache exists
if ( !$body = getCache( ‘bodyCache.txt’ , 10 ) {
// display body section
?>
<h1>This section is updated every 10 seconds.</h1>
<?php
$body = ob_get_contents();
ob_clean();
createCache( $body , ‘bodyCache.txt’ );
}
// check if a valid footer cache exists
if ( !$footer = getCache( ‘footerCache.txt’ , 86400 ) {
// display footer section
?>
The footer section is updated on a daily basis.
</body>
</html>
<?php
$footer = ob_get_contents();
ob_clean();
createCache( $footer , ‘footerCache.txt’ );
}
// stops output buffering
ob_end_clean();
// display the complete page
echo $header . $body . $footer;
?>
That’s the general idea behind the concept of caching server side output. Major performance improvements can be achieved if used in conjunction with proper caching policies for specific sections of the website.
Since I am a strong advocate of object oriented programming, I would recommend using some good and trusted caching classes, such as Pear::Cache_Lite, in order keep your code maintainable and have a reliable caching mechanism for websites.
From this point, there is long way to go. Caching is a very huge subject, and it can be approached from several points. But one thing is certain: caching server output with PHP output buffering functions is a good addition to your toolbox when building dynamic websites. Good luck!