Home > Article > Backend Development > PHP static files return 304,_PHP tutorial
Sometimes some static files (such as pictures) will be output by php, and you will find that the requests are all 200, and the static files are requested on the server every time It's such a waste of resources. How can I let the browser cache the image at this time? We need to output 304 in php.
We can use HTTP_IF_MODIFIED_SINCE
in php combined with etag to do this. Etag does not have a clearly defined format. We can use the md5 value of the file modification time. The code is as follows:
<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>
You can call it in the code before outputting static files (such as pictures).