有时一些静态文件(如图片)会由PHP输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在PHP中输出304了。
我们可以利用PHP中的 HTTP_IF_MODIFIED_SINCE
结合etag来干这事。Etag没有明确规定的格式,我们可以用文件修改时间的md5值,代码如下:
_addEtag( = ( = (
("Last-Modified: ".("D,d M Y H:i:s",)." GMT"("Etag: "
(@(['HTTP_IF_MODIFIED_SINCE']) == ||(['HTTP_IF_NONE_MATCH']) == ("HTTP/1.1 304 Not Modified"
上面那段代码有时不太好使,有下面这段:
_addEtag( = ( = ('r',('ETag: "'.(.).'"'('Last-Modified: '.('Cache-Control: public'
</span><span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$_SERVER</span>['HTTP_IF_MODIFIED_SINCE']) || <span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$_SERVER</span>['HTTP_IF_NONE_MATCH'<span style="color: #000000;">])) {
</span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$_SERVER</span>['HTTP_IF_MODIFIED_SINCE'] == <span style="color: #800080;">$gmt_mtime</span> || <span style="color: #008080;">str_replace</span>('"','',<span style="color: #008080;">stripslashes</span>(<span style="color: #800080;">$_SERVER</span>['HTTP_IF_NONE_MATCH'])) == <span style="color: #008080;">md5</span>(<span style="color: #800080;">$last_modified_time</span>.<span style="color: #800080;">$file</span><span style="color: #000000;">)) {
</span><span style="color: #008080;">header</span>('HTTP/1.1 304 Not Modified'<span style="color: #000000;">);
</span><span style="color: #0000ff;">exit</span><span style="color: #000000;">();
}
}
}</span></pre>