【问题标题】:Last modified header for a fixed resource link where the resource changes from time to time?资源不时更改的固定资源链接的上次修改标头?
【发布时间】:2019-03-05 18:21:38
【问题描述】:

目前我正在编写一个小的 WordPress 插件,用于下载资源并运行更新。这意味着我调用一个固定的端点 URL,例如:

https://www.example.com/downloads/app/latest

如果调用此 URL,则服务器正在交付所请求资源的最新版本(例如,可执行应用程序)。资源的名称可能会有所不同,但也可能与旧版本相同。因此,我想放置一个工作最后修改的标题。

基本上我从这个问题中得到了要设置的标题:Force file download with php using header()

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Pragma: public');
header('Content-Length: ' . $size);

现在我想知道如何正确设置标头,以便浏览器知道资源是否已更改。假设我有请求资源的最后修改日期,我的猜测是:

header('Cache-Control: must-revalidate');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', $last_modified_time));

如果我不知道最后修改日期是什么,我会输入:

header('Cache-Control: no-cache');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T'));

这是正确的(尤其是标题)还是我错过了什么?不确定,因为缓存控制、修改日期、过期等设置有很多。

【问题讨论】:

  • 你测试了吗?发现这种方法有任何问题?你如何定义“正确”?您的预期行为是什么?
  • @yivi 对不起,如果我的问题有点不清楚,谢谢你的提问。我认为我的问题的答案是 ETag 标头,正如我在自己的答案中所解释的那样。但是,如果我在某个地方出错了,请随时纠正我。

标签: php caching download http-headers last-modified


【解决方案1】:

经过一番研究,我发现 ETag 标头正在解决我的问题。设置 ETag 标头的工作方式如下所述:How to use etags in a PHP file?

还找到了一些关于如何将其与Expires 标头结合使用的信息:ETag vs Header Expires - ETag 标头至少发出一个请求来比较文件校验和,而 expires 标头至少发出一个请求。

拼图的最后一部分是:HTTP: Does the ETag header make the Cache-Control header obsolete? How to make sure Cache-Control is not harmful then?

因此我现在有了完美的答案(至少我认为):

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);
$etag   = hash_file('md5', $file); 

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Pragma: public');
header('Content-Length: ' . $size);
header('Cache-Control: no-cache');
header('Expires: 0');
header('ETag: ' . $etag);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多