Home  >  Article  >  Backend Development  >  php static file returns 304

php static file returns 304

WBOY
WBOYOriginal
2016-08-08 09:33:031077browse

Sometimes some static files (such as pictures) will be output by PHP, and you will find that the requests are all 200. It is a waste of resources to request the static files from the server every time. How to make the browser cache the pictures? 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>

It can be called in the code before static files (such as pictures) are output.

The above introduces the 304 returned by PHP static files, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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
Previous article:smarty notesNext article:smarty notes