Check my php caching script

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Check my php caching script

Post by Mr Tech »

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?

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();
Post Reply