問題描述
我有用 PHP 5.1.0+ 制作的可緩存動態(tài)內(nèi)容.我已經(jīng)向客戶端發(fā)送了正確的標(biāo)頭(包括 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.
我現(xiàn)在希望我的腳本能夠在存在時回答 $_SERVER['HTTP_IF_MODIFIED_SINCE']
和 $_SERVER['HTTP_IF_NONE_MATCH']
.當(dāng)條件匹配時,我想向客戶端回答 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.
正確的條件是什么?我什么時候發(fā)出 304 而不是整個內(nèi)容?
What are the correct conditions? When exactly I issue a 304 instead of the whole content?
有問題的已接受答案如何知道何時發(fā)送 304未修改的響應(yīng) 似乎正確地發(fā)出了這個問題,但我很難將該代碼移植到 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']));
這篇關(guān)于在 PHP 中回答 HTTP_IF_MODIFIED_SINCE 和 HTTP_IF_NONE_MATCH的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!