Home > Backend Development > PHP Tutorial > php静态文件回到304

php静态文件回到304

WBOY
Release: 2016-06-13 12:10:54
Original
906 people have browsed it

php静态文件返回304

有时一些静态文件(如图片)会由php输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在php中输出304了。

我们可以利用php中的 HTTP_IF_MODIFIED_SINCE 结合etag来干这事。Etag没有明确规定的格式,我们可以用文件修改时间的md5值,代码如下:

<span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span> _addEtag(<span style="color: #800080;">$file</span><span style="color: #000000;">) {    </span><span style="color: #800080;">$last_modified_time</span> = <span style="color: #008080;">filemtime</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">);     </span><span style="color: #800080;">$etag</span> = <span style="color: #008080;">md5_file</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">);    </span><span style="color: #008000;">//</span><span style="color: #008000;"> always send headers </span>    <span style="color: #008080;">header</span>("Last-Modified: ".<span style="color: #008080;">gmdate</span>("D, d M Y H:i:s", <span style="color: #800080;">$last_modified_time</span>)." GMT"<span style="color: #000000;">);     </span><span style="color: #008080;">header</span>("Etag: <span style="color: #800080;">$etag</span>"<span style="color: #000000;">);     </span><span style="color: #008000;">//</span><span style="color: #008000;"> exit if not modified</span>    <span style="color: #0000ff;">if</span> (@<span style="color: #008080;">strtotime</span>(<span style="color: #800080;">$_SERVER</span>['HTTP_IF_MODIFIED_SINCE']) == <span style="color: #800080;">$last_modified_time</span> ||<span style="color: #000000;">     @</span><span style="color: #008080;">trim</span>(<span style="color: #800080;">$_SERVER</span>['HTTP_IF_NONE_MATCH']) == <span style="color: #800080;">$etag</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>
Copy after login

在代码中可以在静态文件(如图片)输出之前调用即可。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template