Check my php caching script
Posted: Tue May 05, 2009 11:23 pm
I found some code on the net to cache php files. I've modified it to suit.
Does the following code look ok to you?
Is it going to be valid in all browsers?
Any other headers I need to add?
Does the following code look ok to you?
Is it going to be valid in all browsers?
Any other headers I need to add?
Code: Select all
// Settings
$cachedir = ABSPATH . 'cache/'; // Directory to cache files in
$cachetime = 600; // Seconds to cache files for
$cacheext = 'html.gz'; // Extension to give cached files
// Ignore List
$ignore_list = array();
// Script
$page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
$cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create
$ignore_page = false;
for ($i = 0; $i < count($ignore_list); $i++) {
$ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;
}
$cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0;
@clearstatcache();
// Show file from cache if still valid
if (time() - $cachetime < $cachefile_created) {
header("Last-Modified: " . gmdate("D, d M Y H:i:s \G\M\T", $cachefile_created));
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Cache-Control: private, must-revalidate, s-max-age=0");
@readfile($cachefile);
exit();
}
// If we're still here, we need to generate a cache file
ob_start();
/*************
*
*
*
* PAGE CONTENT IS LOADED HERE
*
*
*
*************/
// Now the script has run, generate a new cache file
$fp = @fopen($cachefile, 'w');
// gzip content
$cached_content = ob_get_contents();
$cached_content_gzip = gzencode($cached_content, 6);
// save the contents of output buffer to the file
@fwrite($fp, $cached_content_gzip);
@fclose($fp);
ob_end_flush();