【发布时间】: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