php - 304 : Not modified and front end caching

标签 php http caching http-headers

我正在使用 PHP 脚本来提供文件。 如果文件自客户端上次下载以来未更改,我希望能够在我的 http 响应中发回 304 not modified header 。这似乎是 Apache(以及大多数其他 Web 服务器)中的一项功能,但我不知道如何通过 PHP 实现它。

我听说过使用 $_SERVER['HTTP_IF_MODIFIED_SINCE'],但是这个变量似乎没有出现在我的 $_SERVER super 数组中。

我的问题不是如何返回 304 header ,而是如何知道应该返回一个 header 。


编辑:问题是我的 $_SERVER['HTTP_IF_MODIFIED_SINCE'] 没有设置。这是我的 .htaccess 文件的内容:

ExpiresActive On 
ExpiresByType image/jpeg "modification plus 1 month"
ExpiresByType image/png "modification plus 1 month"
ExpiresByType image/gif "modification plus 1 month"
Header append Cache-Control: "must-revalidate" 


<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond $1 !^(controller\.php)
   RewriteRule (.*\.jpg|.*\.png|.*\.gif) controller.php/$1
</IfModule>

HTTP_IF_MODIFIED_SINCE 仍然没有出现在 $_SERVER super 数组中。

最佳答案

HTTP_IF_MODIFIED_SINCE 是正确的方法。如果你没有得到它,检查 Apache 是否有 mod_expiresmod_headers启用并正常工作。借自a comment on PHP.net :

$last_modified_time = filemtime($file); 
$etag = md5_file($file);
// always send headers
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
header("Etag: $etag"); 
// exit if not modified
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || 
    @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
    header("HTTP/1.1 304 Not Modified"); 
    exit; 
}

// output data

关于php - 304 : Not modified and front end caching,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583740/

相关文章:

http - 使用 http 1.0 或更早版本的客户端可以使用 UDP 套接字而不是 TCP 套接字吗?

http - 登录失败时返回正确的状态码

html - 从缓存渲染 CSS 时,IE7 回退到 IE6 标准模式

php - PHP 中的广告管理系统?

php - 在应用程序和网络之间共享数据库

php - 如何在 PHP 中合并多维数组以便能够将它们输出在一起

javascript - 将 html2pdf pdf 或 html2canvas 图像发送到电子邮件

python - Shopify 不会停止向 Flask 应用程序发送 webhook

python - linux磁盘缓冲区缓存是否使python cPickle比搁置更有效?

php - CodeIgniter 缓存驱动程序忽略备份适配器