我有一个脚本,它在服务器上使用 PHP 生成图像,格式为 image.png。然后我在不同的地方使用这个图像<img src="http://domain.com/images/image.png" />
。
我遇到的问题是,即使图像每 30 分钟重新生成一次,它似乎已被缓存并且在我转到http://domain.com/images/image.png之前不会显示新值然后ctrl+shift+refresh
。
有什么办法可以保持图像名称相同,但让它始终显示图像的最新版本?
我有一个脚本,它在服务器上使用 PHP 生成图像,格式为 image.png。然后我在不同的地方使用这个图像<img src="http://domain.com/images/image.png" />
。
我遇到的问题是,即使图像每 30 分钟重新生成一次,它似乎已被缓存并且在我转到http://domain.com/images/image.png之前不会显示新值然后ctrl+shift+refresh
。
有什么办法可以保持图像名称相同,但让它始终显示图像的最新版本?
这发生在浏览器缓存超过 30 分钟时。由于您的图像每 30 分钟生成一次,因此您应该相应地设置Expires
和Cache-control
标题。
请参阅这些标题。
Expires: Mon, 10 Dec 2012 16:25:18 GMT
Cache-Control: max-age=1800
这里Expries
设置为从现在起 30 分钟后的时间 ( Date: Mon, 10 Dec 2012 15:55:18 GMT
)。而且Cache-Control
还需要设置。单位在这里是第二的。
我将这些标头用于缓存持续时间为 60 分钟的图像生成站点。这些是我缓存它所遵循的规则。
有几种选择,具体取决于您的情况。如果“images/image.png”是服务器上的实际文件并且您正在直接访问它,那么您必须更改文件夹上的缓存设置或使用 .htaccess 通知浏览器重新发送它。
<FilesMatch "\.(ico¦pdf¦flv¦jpg¦jpeg¦png¦gif¦js¦css¦swf)$">
ExpiresDefault A604800
Header set cache-control: "no-cache, public, must-revalidate"
</FilesMatch>
如果您使用 PHP 查找图像并返回它,您可以使用 PHP 发送标头。
header("Expires: ".gmdate("D, d M Y H:i:s", time()+1800)." GMT");
header("Cache-Control: max-age=1800");
要使用 PHP 完美地做到这一点,您可以检查它是否实际修改
$last_modified_time = @filemtime($file);
header("Expires: ".gmdate("D, d M Y H:i:s", $last_modified_time+1800)." GMT");
//change with $last_modified_time instead of time().
//Else if you request it 29mins after it was first created, you still have to wait 30mins
//but the image is recreated after 1 min.
header("Cache-Control: max-age=1800");
header("Vary: Accept-Encoding");
// exit if not modified
if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time) {
header("HTTP/1.1 304 Not Modified");
return;
}
}
您可以尝试使用 PHP 加载图像:
<?php
//generateImage.php
$path = "xxxx/xxx.jpg";
$img =imagecreatefromjpeg($path);
header("Content-Type: image/jpeg");
imagejpeg($img);
imagedestroy($img);
?>
然后像这样调用图像:
<img src="http://domain.com/generateImage.php" />