【问题标题】:Allowing caching of image.php until source has been changed允许缓存 image.php 直到源被更改
【发布时间】:2013-01-17 16:05:57
【问题描述】:

以下代码是我在 image.php 中使用的(htaccess 下也是 image.jpeg)。如果源未更改(因此它是相同的图像),我希望用户能够访问缓存的副本。但是,如果源已更改,请获取新副本。该图像是背景图像,因此缓存很重要。这段代码正确吗?我在 Chrome 中尝试过,刷新页面总是重新加载图像。再次访问该页面(单击 Enter)始终保留缓存的图像,即使它已更新。

<?php
session_start(); 
header("Cache-Control: private, max-age=10800, pre-check=10800");
header("Pragma: private");
header("Expires: " . date(DATE_RFC822,strtotime(" 2 day")));
if(file_exists('settings.xml')){
        $xml = simplexml_load_file('settings.xml');
        define("BACKGROUND_IMAGE", $xml->background->image);
        define("BACKGROUND_TIME", $xml->background->time); // when image changes this is set to time()
    }
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) 
       && 
  (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == BACKGROUND_TIME)) {
  // send the last mod time of the file back
  header('Last-Modified: '.gmdate('D, d M Y H:i:s', BACKGROUND_TIME).' GMT', 
  true, 304);
  exit;
}
// open the file in a binary mode
$name = BACKGROUND_IMAGE;
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;

【问题讨论】:

  • 刷新 (F5) 总是重新加载图像。您可以通过使用 JS 来实现您的目标(页面加载后设置 bg-pic)。

标签: php caching http-headers


【解决方案1】:

我个人使用这样的东西并且效果很好;

$etag = '"'. md5($img) .'"';
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) 
       && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
    header('HTTP/1.1 304 Not Modified');
    header('Content-Length: 0');
    exit;
}

$expiry = 604800; // (60*60*24*7)
header('ETag: '. $etag);
header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
header('Expires:'.        gmdate('D, d M Y H:i:s', time() + $expiry) .' GMT');
...
// show/send/read image

但如果您想看的话,这里还有其他内容(参考:Answering HTTP_IF_MODIFIED_SINCE and HTTP_IF_NONE_MATCH in PHP)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多