I rolled out a pretty simple cache system on my site last week using a PHP class referenced in my sitewide template file. The cache system dramatically improved server response times (the template pulls data from a couple other servers in our datacenter, so it isn't all cached in memory by Apache). The problem is, it was over-caching files. I believe I have it set to cache for five minutes, or until the HTML is modified, but it was still serving cached versions of pages days after the cached versions were created.
Can anyone spot any issues with my code, or do you know about any versions of PHP/Apache/Red Hat that might, say, report bad info on file modification times? (We're on PHP 5.3.3, Apache 2.2.15, and RHEL 6. I had been running mod_pagespeed, but the problem persisted even after I disabled it.)
<?php
class IWU_Cache {
protected $cache_prefix = '/tmp/webcache_';
protected $remote_delay = 300; // in seconds; 300 is five minutes
protected $path;
public function __construct($path = '') {
$this->path = $path;
}
public function isRecentlyCached() {
$cache_location = $this->path2Cache($this->path);
if(is_file($cache_location)) {
if(is_file($_SERVER['DOCUMENT_ROOT'] . $this->path) && (filemtime($_SERVER['DOCUMENT_ROOT'] . $this->path) < filemtime($cache_location))) {
return TRUE;
}
elseif(filemtime($cache_location) > time() - $this->remote_delay) {
return TRUE;
}
}
return FALSE;
}
public function getCachedVersion() {
return file_get_contents($this->path2Cache($this->path));
}
public function addToCache($html) {
return file_put_contents($this->path2Cache($this->path), $html);
}
protected function path2Cache($path) {
return $this->cache_prefix . str_replace('/', '____', $path);
}
}
?>