PHP Set Image Browser Caching method Introduction _php Tutorial

Source: Internet
Author: User
Tags echo date
Whether you use PHP to open the browser cache or use the APACHE,IIS server environment to configure we will be for the browser Cache-control to operate, let me introduce you to PHP settings picture browser cache

Cache-control

Cache-control is the most important rule. This field is used to specify the instructions that all caching mechanisms must obey in the entire request/response chain. These directives specify the behavior that is used to prevent the cache from interfering with the request or response negatively. These directives typically override the default cache algorithm. The cache instruction is one-way, that is, the presence of an instruction in the request does not imply that the same instruction will exist in the response.

Cache-control definition is: Cache-control = "Cache-control" ":" Cache-directive. Table 1 shows the applicable values.

Table 1. Common cache-directive values
cache-directive Description
Public All content will be cached
Private Content is cached only in the private cache
No-cache All content is not cached
No-store All content is not cached in the cache or in temporary Internet files
Must-revalidation/proxy-revalidation If the cached content is invalidated, the request must be sent to the server/proxy for re-authentication
Max-age=xxx (XXX is numeric) Cached content will expire after xxx seconds, this option is only available in HTTP 1.1 and higher priority if used with last-modified

When a client requests a URL for the first time through a browser, the browser transmits a header (HTTP Request header) to the server, as specified in the HTTP protocol, and the server-side response records the associated attribute tag (HTTP reponse header). The return status of the server side will be 200, similar to the following format:

The code is as follows Copy Code

http/1.1 OK
Date:tue, 04:58:40 GMT
Content-type:image/jpeg
content-length:83185
Last-modified:tue, 08:01:04 GMT
cache-control:max-age=2592000
Expires:thu, 05:14:08 GMT
Etag: "5d8c72a5edda8d6a:3239″


When the client requests this URL for the second time, according to the HTTP protocol, the browser transmits the header (HTTP Request header) to the server, the server side responds and records the related record property tag file has not changed, the server side returns 304, reads directly from the cache:

The code is as follows Copy Code

http/1.x 304 Not Modified
Date:tue, 05:03:56 GMT
Content-type:image/jpeg
content-length:83185
Last-modified:tue, 08:01:04 GMT
cache-control:max-age=2592000
Expires:thu, 05:14:08 GMT
Etag: "5d8c72a5edda8d6a:3239″


I. Last-modified, expires and etag related working principles
1, last-modified
When the browser requests a URL for the first time, the server-side return status is 200, the content is the resource you requested, and there is a last-modified attribute tag (Http reponse Header) This file was last modified at the end of the service period, in the format similar to this:

1 Last-modified:tue, 08:01:04 GMT
When the client requests this URL for the second time, according to the HTTP protocol, the browser transmits the If-modified-since header (HTTP Request header) to the server, asking if the file has been modified since:

1 If-modified-since:tue, 08:01:04 GMT
If the server-side resource does not change, the HTTP 304 (not Changed.) Status code is returned automatically, and the content is empty, which saves the amount of data transferred. When the server-side code changes or restarts the server, the resource is re-emitted, similar to when the first request is returned. This ensures that the resources are not duplicated to the client, and that the client is able to get the latest resources when the server changes.

Note: If the if-modified-since time is later than the current time of the server (the current request time Request_time), it will be considered an illegal request.

2. ETag working principle

The HTTP protocol specification defines the etag as the entity tag of the requested variable (see 14.19).

The simple point is that the server responds with the request URL token and transmits it to the client in the HTTP response header, similar to the format returned by the server side:

1 Etag: "5d8c72a5edda8d6a:3239″
The client's query update format is this:

1 If-none-match: "5d8c72a5edda8d6a:3239″
If the etag does not change, the status 304 is returned.
That is: After the client makes the request, the Http reponse header contains the Etag: "5d8c72a5edda8d6a:3239″
The identity, which is equal to telling the client side, you get this resource has the expression id:5d8c72a5edda8d6a:3239.

The next time you request a request for the same URI, the browser issues a If-none-match header (Http Request header) at which the information in the header contains the etag that was last accessed: "5d8c72a5edda8d6a : 3239″ identification.

1 If-none-match: "5d8c72a5edda8d6a:3239″
This way, the client side equals the cache two copies, the server side will be compared to 2 of the etag. If If-none-match is false, returns 200, returning 304 (not Modified) Response.

3, Expires
Given the date/time after the response is considered obsolete. such as Expires:thu, 05:14:08 GMT
Must be used in conjunction with the last-modified. Used to control the validity time of the request file, when the request data is within the validity period, the client browser requests data from the cache instead of the server side. When data in the cache is invalidated or expired, the data is updated from the server.

4, Last-modified and expires
The Last-modified logo can save a bit of bandwidth, but still can't get out of an HTTP request and use it with expires. And the Expires logo makes the browser simply even HTTP requests do not have to send, such as when the user F5 or click the Refresh button even for a expires URI, the same will send an HTTP request out, so, last-modified still need to use, and And be used with expires.

5. ETag and expires
If both the ETag and the expires are set on the server side, the ETag principle is the same as the HTTP Request header:if-modified-since and if-none-match corresponding to the Last-modified/etag. We can see that the value of these two headers is exactly the same as the Last-modified,etag value emitted by Web server, and after the exact match of If-modified-since and If-none-match, when the modification time and the ETag are checked, The server can return 304.

6, Last-modified and ETag
Last-modified is used with the HTTP header of the etags request, the server first generates the Last-modified/etag tag, which the server can later use to determine whether the page has been modified to determine whether the file continues to be cached

The process is as follows:
1. The client requests a page (a).
2. The server returns page A, and adds a last-modified/etag to a.
3. The client presents the page and caches the page along with Last-modified/etag.
4. The Customer requests page A again and passes the Last-modified/etag that the server returned on the last request to the server.
5. The server checks the last-modified or ETag, and determines that the page has not been modified since the last client request, directly returning response 304 and an empty response body.

Note:
1, last-modified, and ETag headers are all HTTP reponse that are emitted by the WEB server Header,web server should support both headers.
2. After the WEB server sends the LAST-MODIFIED/ETAG header to the client, the client caches the headers;
3. When the client initiates a request for the same page again, the HTTP request header:if-modified-since and if-none-match corresponding to the Last-modified/etag will be sent separately. We can see that the value of these two headers is exactly the same as the Last-modified,etag value emitted by Web server;
4, through the above value to the server-side check to determine whether the file continues to cache;

Second, for the non-real-time interactive dynamic page epires and etag processing
The data update is not frequent, such as tag classification archive, etc., you can consider to its cache. The simple point is to output the expires and ETag identifiers in non-real-time interactive dynamic programs and let them cache. However, you need to pay attention to closing the session, to prevent HTTP response when the HTTP header contains session ID identification;

3.1, Expires
such as expires.php

The code is as follows Copy Code

Header (' cache-control:max-age=86400,must-revalidate ');
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT ');
Header ("Expires:". Gmdate (' d, D M Y h:i:s ', time () + ' 86400′). ' GMT ');


3.2. Etag
Processed according to the HTTP return status. When return 304 is read directly from the cache
such as etag.php

The code is as follows Copy Code

Cache ();
echo Date ("y-m-d h:i:s");
function Cache ()
{
$etag = "Http://longrujun.name";
if (Isset ($_server[' Http_if_none_match ')) &&
$_server[' http_if_none_match '] = = $etag)
{
Header (' Etag: '. $etag, true,304);
Exit
}
else header (' Etag: '. $etag);
}

Picture Cache Instance

The code is as follows Copy Code


$imagePath = "Path/to/some/image";

$eTag = $imagePath;
$eTag. = Filemtime ($imagePath);
$ETAG = MD5 ($ETAG);

if ((Isset ($_server[' Http_if_none_match ')) &&
(Stripslashes ($_server[' http_if_none_match ')) = = $eTag)) {
Header ("http/1.1 304 Not Modified", TRUE, 304);
Exit ();
}

Header ("ETag:". $eTag);
Header ("Content-type:image/png");
ReadFile ($imagePath);
Exit ();

The above method is super simple, see a complete example below

The code is as follows Copy Code

$fullpath = '/www/images/'. basename ($_get[' img '); Assuming the files are under/www/images/
if (!is_file ($fullpath)) {
Header ("http/1.0 404 Not Found");
Exit ();
}

$info = getimagesize ($fullpath); Get picture information
if (! $info) {//If not picture
Header ("http/1.0 404 Not Found");
Exit ();
}

The following general header function is the output header information. More.
Header (' Content-type: '. $info [' MIME ']); Similar to Image/png
Header (' Content-length: '. FileSize ($fullpath)); File length

Header (' Pragma: '); Useless, but to set, to prevent the server from generating no-cache awful words

Manually set the expiration time, units are seconds
$validtime = 48* 60 * 60; 48 Hours

The time the cache is relative to the request,
Header (' Cache-control: '. ' Max-age= '. $validtime);

Also very important expires head, features similar to Max-age
Time () + $validtime: Set a deadline to submit a request to the server after it expires
Gmdate, generating a string of sun, 2009 04:05:49 +0000, and GMT Standard Time zone
Preg_replace, generate Sun, 04:05:49 GMT, note: May be related to server settings,
But I use the default settings
Header (' Expires: '. Preg_replace ('/.{ 5}$/', ' GMT ', gmdate (' R ', time () + $validtime)));

File Last Modified Time
$lasttime = Filemtime ($fullpath);

Last modified time, set, click on Refresh, the browser again request the image will be issued ' If_modified_since ' head,
Thus being read by the PHP program
Header (' last-modified: '. Preg_replace ('/.{ 5}$/', ' GMT ', gmdate (' R ', $lasttime));

Important, if the time in the request and the file generation timestamp are equal, the file is not modified and the client is available for caching
if (Strtotime ($_server[' http_if_modified_since ')) = = $lasttime) {
Header ("http/1.1 304 not Modified"); The server issued an instruction that the file was not modified
Exit ();
}

If the file is modified, the data must be re-issued
Echo file_get_contents ($fullpath);

http://www.bkjia.com/PHPjc/631550.html www.bkjia.com true http://www.bkjia.com/PHPjc/631550.html techarticle Whether you use PHP to open the browser cache or use the APACHE,IIS server environment to configure we will be for the browser Cache-control to operate, let me introduce you to the PHP Setup diagram ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.