Home >Backend Development >PHP Tutorial >Introduction to how to set image browser cache in PHP_PHP tutorial

Introduction to how to set image browser cache in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:57:141075browse

Whether you use PHP to open the browser cache or use apache or iis server environment to configure it, we will operate based on the browser's Cache-Control. Let me introduce to you how to set up the image browser cache in PHP

Cache-Control

Cache-Control is the most important rule. This field is used to specify instructions that all caching mechanisms must obey throughout the request/response chain. These directives specify behavior that prevents caching from adversely interfering with requests or responses. These directives usually override the default caching algorithm. Caching directives are one-way, i.e. the presence of a directive in the request does not mean the same directive will be present in the response.

cache-control definition is: Cache-Control = “Cache-Control” “:” cache-directive. Table 1 shows applicable values.

表 1. 常用 cache-directive 值
Cache-directive 说明
public 所有内容都将被缓存
private 内容只缓存到私有缓存中
no-cache 所有内容都不会被缓存
no-store 所有内容都不会被缓存到缓存或 Internet 临时文件中
must-revalidation/proxy-revalidation 如果缓存的内容失效,请求必须发送到服务器/代理以进行重新验证
max-age=xxx (xxx is numeric) 缓存的内容将在 xxx 秒后失效, 这个选项只在HTTP 1.1可用, 并如果和Last-Modified一起使用时, 优先级较高

When the client makes the first request for a URL through the browser, according to the provisions of the HTTP protocol, the browser will send a header (Http Request Header) to the server, and the server will respond and record the relevant attribute tags (Http Response Header). ), the server-side return status will be 200, and the format is similar to the following:

The code is as follows Copy code
 代码如下 复制代码

HTTP/1.1 200 OK
Date: Tue, 03 Mar 2009 04:58:40 GMT
Content-Type: image/jpeg
Content-Length: 83185
Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT
Cache-Control: max-age=2592000
Expires: Thu, 02 Apr 2009 05:14:08 GMT
Etag: “5d8c72a5edda8d6a:3239″

HTTP/1.1 200 OK

Date: Tue, 03 Mar 2009 04:58:40 GMT
Content-Type: image/jpeg

Content-Length: 83185
 代码如下 复制代码

HTTP/1.x 304 Not Modified
Date: Tue, 03 Mar 2009 05:03:56 GMT
Content-Type: image/jpeg
Content-Length: 83185
Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT
Cache-Control: max-age=2592000
Expires: Thu, 02 Apr 2009 05:14:08 GMT
Etag: “5d8c72a5edda8d6a:3239″

Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT Cache-Control: max-age=2592000 Expires: Thu, 02 Apr 2009 05:14:08 GMT Etag: “5d8c72a5edda8d6a:3239″
When the client requests this URL for the second time, according to the provisions of the HTTP protocol, the browser will send a header (Http Request Header) to the server. The server responds and records that the relevant record attribute tag file has not been changed. The server returns 304, directly from Read from cache:
The code is as follows Copy code
HTTP/1.x 304 Not Modified Date: Tue, 03 Mar 2009 05:03:56 GMT Content-Type: image/jpeg Content-Length: 83185 Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT Cache-Control: max-age=2592000 Expires: Thu, 02 Apr 2009 05:14:08 GMT Etag: “5d8c72a5edda8d6a:3239″


1. Working principles related to Last-Modified, Expires and Etag
1. Last-Modified
When the browser requests a URL for the first time, the return status from the server will be 200. The content is the resource you requested, and there is a Last-Modified attribute mark (Http Response Header). This file was last modified at the service end. time, the format is similar to this:

1 Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT
When the client requests this URL for the second time, according to the provisions of the HTTP protocol, the browser will send the If-Modified-Since header (Http Request Header) to the server to ask whether the file has been modified after this time:

1 If-Modified-Since: Tue, 24 Feb 2009 08:01:04 GMT
If the resource on the server side has not changed, HTTP 304 (Not Changed.) status code will be automatically returned with empty content, thus saving the amount of data to be transmitted. When the server-side code changes or the server is restarted, the resource is reissued and the return is similar to the first request. This ensures that resources are not sent to the client repeatedly, and also ensures that when the server changes, the client can get the latest resources.

Note: If the time of If-Modified-Since is later than the current time of the server (current request time request_time), it will be considered an illegal request

2. Working principle of Etag

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

To put it simply, the server tags the request URL when responding and transmits it to the client in the HTTP response header, similar to the format returned by the server:

1 Etag: “5d8c72a5edda8d6a:3239″
The query update format of the client is as follows:

1 If-None-Match: “5d8c72a5edda8d6a:3239″
If the ETag has not changed, status 304 is returned.
That is: after the client makes a request, the Http Response Header contains Etag: “5d8c72a5edda8d6a:3239″
The identifier is equivalent to telling the client that the resource you obtained has an ID: 5d8c72a5edda8d6a:3239.

The next time you need to send a Request for the same URI, the browser will also send an If-None-Match header (Http Request Header). At this time, the information in the header contains the Etag obtained from the last visit: "5d8c72a5edda8d6a:3239" identification. .

1 If-None-Match: “5d8c72a5edda8d6a:3239″
In this way, the client side caches two copies, and the server side will compare the etags of the two. If If-None-Match is False, 200 is not returned, but 304 (Not Modified) Response is returned.

3. Expires
The response is considered stale after the given date/time. Such as Expires: Thu, 02 Apr 2009 05:14:08 GMT
Need to be used in conjunction with Last-Modified. Used to control the validity time of the requested file. When the requested data is within the validity period, the client browser requests data from the cache instead of the server. When the data in the cache becomes invalid or expires, it is decided to update the data from the server.

4. Last-Modified and Expires
The Last-Modified flag can save a little bandwidth, but it still cannot escape from sending an HTTP request, and it must be used together with Expires. The Expires flag allows the browser to not even send an HTTP request. For example, when the user F5 or clicks the Refresh button, even for a URI with Expires, an HTTP request will still be sent out. Therefore, Last-Modified still needs to be used. , and must be used together with Expires.

5. Etag and Expires
If both Etag and Expires are set on the server side, the principle of Etag is the same, that is, the Http Request Header corresponding to Last-Modified/Etag: If-Modified-Since and If-None-Match. We can see that the values ​​of these two Headers are exactly the same as the Last-Modified and Etag values ​​sent by the Web Server; the server can return only after fully matching If-Modified-Since and If-None-Match, that is, after checking the modification time and Etag. 304.

6, Last-Modified and Etag
Last-Modified is used together with the http header of the ETags request. The server first generates the Last-Modified/Etag tag. The server can later use it to determine whether the page has been modified and decide whether to continue caching the file

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 displays the page and caches the page together with Last-Modified/ETag.
4. The client requests page A again and passes the Last-Modified/ETag returned by the server during 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, and directly returns response 304 and an empty response body.

Note:
1. The Last-Modified and Etag headers are both Http Response Headers issued by the Web Server. The Web Server should support both headers at the same time.
2. After the Web Server sends the Last-Modified/Etag header to the client, the client will cache these headers;
3. When the client initiates a request for the same page again, it will send the Http Request Header: If-Modified-Since and If-None-Match corresponding to Last-Modified/Etag respectively. We can see that the values ​​of these two Headers are exactly the same as the Last-Modified and Etag values ​​sent by the Web Server;
4. Use the above value to check on the server side to determine whether the file continues to be cached;

2. Processing of Epires and Etag in non-real-time interactive dynamic pages
For data that is not updated frequently, such as tag classification and archiving, etc., you can consider caching it. The simple point is to output expires and etag identifiers in non-real-time interactive dynamic programs and let them be cached. But you need to pay attention to closing the session to prevent the http header from containing the session id in the http response;

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’);

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
 代码如下 复制代码

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);
}

Processed according to Http return status. When returning 304, read directly from the cache

Such as etag.php

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();

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); }
Image caching example
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
 代码如下 复制代码

$fullpath = '/www/images/' . basename($_GET['img']); //假定文件都在/www/images/下
if (!is_file($fullpath)) {
    header("HTTP/1.0 404 Not Found");
    exit();
}
 
$info = getImageSize($fullpath); //获取图片信息
if (!$info) {                    //如果不是图片
    header("HTTP/1.0 404 Not Found");
    exit();
}
 
// 以下凡是header函数都是在输出头部信息。较多。
header('Content-type: '. $info['mime']);          //类似于image/png
header('Content-Length: '. filesize($fullpath));  //文件长度
 
header('Pragma: ');             //没用,但要设置,防止服务器生成no-cache的可怕字眼
 
//手动设置过期时间,单位都是秒
$validtime = 48* 60 * 60;    // 48小时
 
//缓存相对请求的时间,
header('Cache-Control: ' . 'max-age='. $validtime);
 
//也很重要的Expires头,功能类似于max-age
//time()+$validtime: 设置期限,到期后才会向服务器提交请求
//gmdate,生成Sun, 01 Mar 2009 04:05:49 +0000  的字符串,而且是GMT标准时区
//preg_replace,  生成Sun, 01 Mar 2009 04:05:49 GMT, 注意:可能与服务器设置有关,
//但我都用默认设置
header('Expires:'. preg_replace('/.{5}$/', 'GMT', gmdate('r', time()+ $validtime)));
 
//文件最后修改时间
$lasttime = filemtime($fullpath);
 
//最后修改时间,设置了,点击刷新时,浏览器再次请求图片才会发出'IF_MODIFIED_SINCE'头,
//从而被php程序读取
header('Last-Modified: ' . preg_replace('/.{5}$/', 'GMT', gmdate('r', $lasttime) ));
 
//重要,如果请求中的时间和 文件生成时间戳相等,则文件未修改,客户端可用缓存
if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lasttime) {
    header("HTTP/1.1 304 Not Modified"); //服务器发出文件不曾修改的指令
    exit();
}
 
//如果文件被修改了,只好重新发出数据
echo file_get_contents($fullpath);

Copy code
$fullpath = '/www/images/' . basename($_GET['img']); //Assume the files are all under /www/images/
if (!is_file($fullpath)) {
header("HTTP/1.0 404 Not Found");
exit();
}

$info = getImageSize($fullpath); //Get image information
if (!$info) { //If it is not a picture
header("HTTP/1.0 404 Not Found");
exit();
}

// All the following header functions output header information. More.
header('Content-type: '. $info['mime']); //Similar to image/png
header('Content-Length: '. filesize($fullpath)); //File length

header('Pragma: ');                                                                                                    // Useless, but it must be set to prevent the server from generating the terrible word no-cache

//Manually set the expiration time in seconds
$validtime = 48* 60 * 60; // 48 hours

//Cache the time relative to the request,
header('Cache-Control: ' . 'max-age='. $validtime);

//The Expires header is also very important, its function is similar to max-age
//time()+$validtime: Set the period, and the request will be submitted to the server after expiration
//gmdate, generates a string of Sun, 01 Mar 2009 04:05:49 +0000, and it is the GMT standard time zone
//preg_replace, Generate Sun, 01 Mar 2009 04:05:49 GMT, Note: It 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);

//The last modification time is set. When you click refresh, the browser will send out the 'IF_MODIFIED_SINCE' header when requesting the image again.
//Thus 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 has not been modified and the client can cache it
if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lasttime) {
header("HTTP/1.1 304 Not Modified"); //The server issues an instruction that the file has not been modified
exit();
}

//If the file is modified, the data has to be reissued
echo file_get_contents($fullpath);

http://www.bkjia.com/PHPjc/631550.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/631550.html
TechArticle
Whether you use php to open the browser cache or use apache or iis server environment to configure it, we will configure it for browsing To operate the Cache-Control of the server, let me introduce to you the PHP setting diagram...
Statement:
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