标题缓存控制不起作用标题" Last-Modified"

时间:2014-09-06 15:45:35

标签: php header cache-control

我使用php创建一个图像,并希望控制缓存时间。 我有这段代码:

header("Cache-Control: must-revalidate"); 

$fn = gmdate('D, d M Y H:i:s \G\M\T', time() + 60);
$now = gmdate('D, d M Y H:i:s \G\M\T', time());

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
    strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) <= $now  )
{
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.$fn, true, 304);
}else {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.$fn, true, 200);
        //Header
        header("Content-type: image/PNG");
        //Ausgeben
        imagePNG($bild);

};

只有在60秒后才会发出新图像。 但我的代码总是给它。 怎么了?坦克提前任何提示。

1 个答案:

答案 0 :(得分:1)

我认为你的算术是关闭的;根据您的代码查看以下示例:

$lifetime = 60;

header("Cache-Control: must-revalidate");

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  $lastMod = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
} else {
  $lastMod = 0;
}

if ($lastMod <= $_SERVER['REQUEST_TIME'] - $lifetime) {
  // Time to refresh
  $lastMod = $_SERVER['REQUEST_TIME'];
  header("Content-type: text/plain");
  header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', $lastMod), true, 200);
  echo "Hello!";

} else {
  header("Last-Modified: " . gmdate('D, d M Y H:i:s \G\M\T', $lastMod), true, 304);
}

这会将最后修改的标头设置为现在(使用$_SERVER['REQUEST_TIME'],这可能比直接使用time()更有效地满足您的需求),并在后续请求中检查If-Modified-Since至少60秒。如果是这样,它将刷新(并重新设置最后修改为现在);否则,返回304并且不更改最后修改。

相关问题