The browser's caching policy will temporarily cache browsed files on the local disk. When the user repeatedly requests the page, the client is informed that the page has not changed and caching can be called. So how do you know if the client has a page cache? From the HTTP protocol level, when the browser sends a request, it will first send the following
HTTP header:
Connection Keep-Alive
Date Sun, 06 May 2012 18:00:36 GMT
Last-Modified Sun, 06 May 2012 17:31:02 GMT
Etag ec1f629013925ab0fa4389ba926e8c06
Keep-Alive timeout=15, max=299
Server Apache/2.2.16 (Unix) DAV/2
Vary Accept-Encoding
Please note these two lines, which describe the cache information of the page:
Last-Modified Sun, 06 May 2012 17:31:02 GMT
Etag ec1f629013925ab0fa4389ba926e8c06 In this case, if the server responds with a 304 status code, the browser will consciously read the data from the cache; if it responds with a 200 status code, it will still read from the server regardless of whether there is a client cache.
According to this theoretical support, for example, most of the query results of the webmaster army are obtained asynchronously through ajax, and secondary visits can be cached in this way. As long as the client has cache, send a 304 response status code to the client, and then exit the program execution.
The request sent by the browser contains two parameters: If-Modified-Since and If-None-Match:
If-Modified-Since means asking whether the last modification time of the data is a certain time value. Then the server will check the last modification time of the data, and if it is that time, it will return a 304 status code. After receiving the status code, the client will read the cache directly from the local cache. This situation has a precondition, that is, cache resources must exist locally before the browser will send the If-Modified-Since parameter, and the value is the Last-Modified value returned by the last server.
If-None-Match is similar. It is generated by the Etag value returned by the server. It is only used by the server to check the modification time of the data. It can be any value. Considering that the method of If-Modified-Since combined with Last-Modified is not supported by all servers, only the implementation using etag will be considered here.
In PHP, you can use $_SERVER['HTTP_IF_NONE_MATCH'] to determine whether the file is cached by the browser. The code snippet is as follows:
//Use the etag tag to control caching
The code is as follows
|
Copy code
|
||||
$etag = md5 (date('Ymd')); if ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { | header('Etag:' . $etag);
} Here I use the current date to generate the etag, which ensures The cache will take effect for up to one day, and this parameter can be modified as needed.
www.bkjia.com