PHP缓存太长

时间:2014-09-08 21:19:00

标签: php apache caching

我上周使用我的全站模板文件中引用的PHP类在我的网站上推出了一个非常简单的缓存系统。缓存系统显着改善了服务器响应时间(模板从我们数据中心的其他几台服务器中提取数据,因此Apache并未将其缓存在内存中)。问题是,它是过度缓存文件。我相信我已将其设置为缓存五分钟,或直到修改HTML,但在创建缓存版本后几天仍然提供缓存版本的页面。

任何人都可以发现我的代码有任何问题,或者您是否知道任何版本的PHP / Apache / Red Hat可能会报告文件修改时间的错误信息? (我们使用的是PHP 5.3.3,Apache 2.2.15和RHEL 6.我一直在运行mod_pagespeed,但是在我禁用它之后问题仍然存在。)

<?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);
    }
}

?>

1 个答案:

答案 0 :(得分:0)

我假设你正在调用isRecentlyCached()来确定文件是否被缓存?在这种情况下,一旦写入缓存文件,那么第一个条件将始终为真,直到实际文件再次更改...

if(is_file($_SERVER['DOCUMENT_ROOT'] . $this->path) && (filemtime($_SERVER['DOCUMENT_ROOT'] . $this->path) < filemtime($cache_location))) {
    return TRUE;
}

换句话说(伪代码):

if (timestamp of actual file < timestamp of cached file) /* TRUE */