search
HomeBackend DevelopmentPHP TutorialIntroduction to how to set image browser cache in PHP_PHP tutorial
Introduction to how to set image browser cache in PHP_PHP tutorialJul 13, 2016 pm 04:57 PM
apacheiisphpintroduceWho are youusepictureOpenmethodBrowsercacheset upstill

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)