Answering HTTP_IF_MODIFIED_SINCE and HTTP_IF_NONE_MATCH in PHP(在 PHP 中回答 HTTP_IF_MODIFIED_SINCE 和 HTTP_IF_NONE_MATCH)
问题描述
我有用 PHP 5.1.0+ 制作的可缓存动态内容.我已经向客户端发送了正确的标头(包括 Last-Modified 和 ETag).
I have cacheable dynamic content made in PHP 5.1.0+. I already send the correct headers (including Last-Modified and ETag) to clients.
我现在希望我的脚本能够在存在时回答 $_SERVER['HTTP_IF_MODIFIED_SINCE']
和 $_SERVER['HTTP_IF_NONE_MATCH']
.当条件匹配时,我想向客户端回答 HTTP 304 "Not Modified"
.
I now want my script to be able to answer $_SERVER['HTTP_IF_MODIFIED_SINCE']
and $_SERVER['HTTP_IF_NONE_MATCH']
when present. When the conditions matches, I want to answer a HTTP 304 "Not Modified"
to clients.
正确的条件是什么?我什么时候发出 304 而不是整个内容?
What are the correct conditions? When exactly I issue a 304 instead of the whole content?
有问题的已接受答案如何知道何时发送 304未修改的响应 似乎正确地发出了这个问题,但我很难将该代码移植到 PHP 5.
The accepted answer in question How to know when to send a 304 Not Modified response seems to issue this correctly but I have hard times to port that code to PHP 5.
谢谢!
推荐答案
我一直在用:
function caching_headers ($file, $timestamp) {
$gmt_mtime = gmdate('r', $timestamp);
header('ETag: "'.md5($timestamp.$file).'"');
header('Last-Modified: '.$gmt_mtime);
header('Cache-Control: public');
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime || str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == md5($timestamp.$file)) {
header('HTTP/1.1 304 Not Modified');
exit();
}
}
}
不记得是我写的还是从其他地方得到的...
Don't remember whether I wrote it or got it from somewhere else...
我通常以这种方式在文件顶部使用它:
I'm normally using it at the top of a file in this way:
caching_headers ($_SERVER['SCRIPT_FILENAME'], filemtime($_SERVER['SCRIPT_FILENAME']));
这篇关于在 PHP 中回答 HTTP_IF_MODIFIED_SINCE 和 HTTP_IF_NONE_MATCH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中回答 HTTP_IF_MODIFIED_SINCE 和 HTTP_IF_NONE_MAT
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01