【问题标题】:Bizarre bug when trying to use HTTP Caching Headers from PHP尝试使用 PHP 中的 HTTP 缓存标头时出现奇怪的错误
【发布时间】:2009-06-08 18:17:29
【问题描述】:

我正在设置我认为正确的用于从 PHP 缓存的 HTTP 标头,并且每第二个请求都会收到 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: 我没有高兴地清除了我的缓存,有人报告说它对他们有用。这是否意味着服务器配置问题?如果重要,它在托管服务器上。

编辑 2:在 IE 中似乎不会发生,但在 Firefox 中会发生

【问题讨论】:

  • 对我来说没问题。尝试清除浏览器缓存。您可能已经缓存了 500 或其他内容。
  • 没有快乐。这是否意味着您需要配置服务器?

标签: php caching


【解决方案1】:

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

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

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

如果您真的在每个其他请求上都收到 Server 500 错误,请查看您的网络服务器(Apache?)日志以查看弹出的错误类型。

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2020-12-27
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多