Tips for sharing php static files returning 304, _PHP tutorial

WBOY
Release: 2016-07-13 10:10:17
Original
757 people have browsed it

php static files return 304 tips to share,

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:

Copy code The code is as follows:

private function _addEtag($file) {
$last_modified_time = filemtime($file);
$etag = md5_file($file);
// always send headers
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
// exit if not modified
If (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
@trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
}

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/938846.htmlTechArticlephp static files return 304 tips to share, sometimes some static files (such as pictures) will be output by php, and the request will be found Both are 200. It is a waste of resources to request static files from the server every time...
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