代码之家  ›  专栏  ›  技术社区  ›  Allain Lalonde

尝试从PHP使用HTTP缓存头时出现奇怪的错误

  •  0
  • Allain Lalonde  · 技术社区  · 16 年前

    我正在设置我认为正确的HTTP Header用于从PHP缓存,并且每秒收到500个错误。

    有人能给我指出正确的方向吗?

    执行缓存的代码是:

    <?php
    header('Content-Type: text/css');
    $content = file_get_contents('test.css');
    header('Content-Length: '. strlen($content ));
    
    $expires = 3600;
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
      // Split the If-Modified-Since (Netscape < v6 gets this wrong) 
      $modifiedSince = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']); 
    
      // Turn the client request If-Modified-Since into a timestamp 
      $modifiedSince = strtotime($modifiedSince[0]); 
      $current_time = time();
      if (($current_time - $modifiedSince) < $expires) {
        header("304 Not Modified");
    
        //echo $current_time - $modifiedSince;
        exit();
      }
    }
    
    $current_time = time();
    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $current_time)." GMT");
    header("Expires: " . gmdate("D, d M Y H:i:s", $current_time+$expires) . " GMT");
    header("Cache-Control: max-age=$expires"); 
    echo $content;
    

    编辑1: 我毫无喜悦地清空了我的缓存,有人报告说它对他们有效。这是否意味着服务器配置问题?如果重要的话,它在托管服务器上。

    1 回复  |  直到 16 年前
        1
  •  4
  •   Alana Storm    16 年前

    当我运行你的代码时,我没有收到Status 500错误,但我看到了与你描述的类似的每隔一个请求“提供文件,提供空白页”的行为。

    在设置状态304时,您似乎没有正确使用header()函数。您缺少“HTTP/1.1”。这意味着PHP正在发回一个Status 200标头,然后退出而没有输出。尝试

    header("HTTP/1.1 304 Not Modified");
    

    如果你真的在每隔一次请求时都会收到Server 500错误,请查看你的Web服务器(Apache?)日志,看看会出现什么类型的错误。

    推荐文章