代码之家  ›  专栏  ›  技术社区  ›  hamburger

标头缓存控件不工作标头“上次修改”

  •  0
  • hamburger  · 技术社区  · 10 年前

    我用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 回复  |  直到 5 年前
        1
  •  1
  •   shevron    10 年前

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

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