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 */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本