douzhanrun0497 2014-09-08 21:19
浏览 44
已采纳

PHP缓存太长

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

?>
  • 写回答

1条回答 默认 最新

  • douguanya4248 2014-09-08 22:56
    关注

    I assume you are calling isRecentlyCached() to determine whether the file is cached? In which case, once the cache file has been written then the first condition will always be true, until the actual file is changed again...

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

    In other words (pseudo code):

    if (timestamp of actual file < timestamp of cached file) /* TRUE */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历