PHP static files return 304,_PHP tutorial

WBOY
Release: 2016-07-13 10:12:27
Original
845 people have browsed it

php static files return 304,

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>
Copy after login

You can call it in the code before outputting static files (such as pictures).

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/920881.htmlTechArticlephp static files return 304. Sometimes some static files (such as pictures) will be output by php, and you will find that the requests are 200. It is a waste of resources to request static files from the server every time. At this time, for example...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!