标头高速缓存控制不工作标头“;最后修改”;


Header Cache-Control do not work header "Last-Modified"

我用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秒后给出一个新的图像。但我的代码总是给出它。

我觉得你的算术有些问题;根据您的代码查看以下示例:

$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并且不改变最后修改的内容。