Maison > Article > développement back-end > php静态文件返回304,_PHP教程
有时一些静态文件(如图片)会由php输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在php中输出304了。
我们可以利用php中的 HTTP_IF_MODIFIED_SINCE
结合etag来干这事。Etag没有明确规定的格式,我们可以用文件修改时间的md5值,代码如下:
<span>private</span> <span>function</span> _addEtag(<span>$file</span><span>) { </span><span>$last_modified_time</span> = <span>filemtime</span>(<span>$file</span><span>); </span><span>$etag</span> = <span>md5_file</span>(<span>$file</span><span>); </span><span>//</span><span> always send headers </span> <span>header</span>("Last-Modified: ".<span>gmdate</span>("D, d M Y H:i:s", <span>$last_modified_time</span>)." GMT"<span>); </span><span>header</span>("Etag: <span>$etag</span>"<span>); </span><span>//</span><span> exit if not modified</span> <span>if</span> (@<span>strtotime</span>(<span>$_SERVER</span>['HTTP_IF_MODIFIED_SINCE']) == <span>$last_modified_time</span> ||<span> @</span><span>trim</span>(<span>$_SERVER</span>['HTTP_IF_NONE_MATCH']) == <span>$etag</span><span>) { </span><span>header</span>("HTTP/1.1 304 Not Modified"<span>); </span><span>exit</span><span>; } }</span>
在代码中可以在静态文件(如图片)输出之前调用即可。