Sometimes some static files (such as pictures) will be output by php, and you will find that the request is 200, and the static files go to the server every time The request is too wasteful of resources. How to let the browser cache the image? 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:
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;
}
}
It can be called in the code before static files (such as pictures) are output.