在 PHP 中回答 HTTP_IF_MODIFIED_SINCE 和 HTTP_IF_NONE_MATCH

2021-12-20 00:00:00 http-headers header caching php

我有用 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']));

相关文章