允许缓存图像.php直到源已更改


Allowing caching of image.php until source has been changed

以下代码是我在图像中使用的代码.php(图像.jpeg也在htaccess下)。我希望用户能够在源未更改的情况下访问缓存副本(因此它是相同的图像)。但是,如果源已更改,请获取新副本。此图像是背景图像,因此缓存很重要。 这段代码是否正确? 我在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;

就个人而言,我使用这样的东西并且工作得很好;

$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

但如果你想看的话,这里有别的东西(参考:在PHP中回答HTTP_IF_MODIFIED_SINCE和HTTP_IF_NONE_MATCH)。