PHP 304 error setting method: 1. Open the corresponding php file; 2. Modify the md5 value of the time; 3. Pass "@trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { header("HTTP/1.1 304 Not Modified");exit;" method can output 304.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
What to do if PHP 304 error is reported?
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 have to be requested on the server every time. It's 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:
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; } }
can be called in the code before the static file (such as a picture) is output. That’s it.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to deal with PHP 304 error. For more information, please follow other related articles on the PHP Chinese website!