Home  >  Article  >  Backend Development  >  In-depth analysis of PHP and browser cache_PHP Tutorial

In-depth analysis of PHP and browser cache_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:09:021031browse

We often carry out various optimization solutions for cache settings on the server, but we rarely pay attention to client cache, to be precise, it is the browser’s caching mechanism.
In fact, every browser has a caching policy that temporarily caches each browsed file in a special folder. We can tell the user that the page has not changed when the user repeatedly submits a page request, and the cache can be called. So how do we know whether the user has cached data for this page? In fact, the browser will first send the http header when sending a request, usually like this:
Date: Sun, 30 Jul 2006 09:18:11 GMT
Content-Type: image/gif
Last-Modified : Wed, 19 Jul 2006 07:40:06 GMT
ETag: "8c55da8d6abc61:2327"
Content-Length: 14757
where
Last-Modified: Wed, 19 Jul 2006 07:40:06 GMT
ETag: "8c55da8d6abc61:2327"
is the cache information about the page. Then if the response code returned by the server is not HTTP 200 (OK), but 304, the browser will read the data from the cache.
//Tell the client browser not to use cache, HTTP 1.1 protocol
header("Cache-Control: no-cache, must-revalidate");

//Tell the client browser Does not use caching and is compatible with HTTP 1.0 protocol
header("Pragma: no-cache");
According to this principle, it can be used on pages that are not updated frequently or need to be refreshed frequently, which can greatly reduce the burden on the server, because If it finds that the client has a cache, it sends a 304 response to the client and then stops the execution of the program.

The request sent by the browser contains two parameters: If-Modified-Since and If-None-Match. The first one indicates whether the last modification time of the data is Thu,19 Jun 2008 16:24:01 GMT Then the server will check the last modification time of the data. If it is that time, it will return status code 304 (indicating no modification). At this time, when the browser receives the status code 304, it will not download the data but from the local cache. call. However, the browser will send the If-Modified-Since parameter only if the data for the requested resource exists in the local cache and its value is the Last-Modified value returned by the last server (not all servers support If-Modified -Since and If-None-Match); If-None-Match has a similar function. It is generated by the value of Etag returned by the server and can be any value, because its function is only to make the server check the modification time of the data and then It just returns, anything else is fine as long as it is not none (default value) or not empty.

So we can set the Etag returned to the browser to a certain value in the first part of the code, and then when this resource is requested for the second time, it will be accompanied by an If-None-Match parameter. After verification When the value is indeed the Etag value sent, you can specify that the server returns 304 and then forcefully exit the program. The same is true for If-Modified-Since. Here, only the php version of the etag method is given (the Last-Modified version is too Common (such as setting cache timeout, etc.):
Copy the PHP code to the clipboard

Copy the code The code is as follows:

if ($_SERVER["HTTP_IF_NONE_MATCH"] == "claymorephp.com")
{
header('Etag:'.'zhaiyun.com',true,304);
exit();
}
else {
header('Etag:'."claymorephp.com");
}
You can also change it slightly:
$expires=date("Ymd "); //Cache expires after one day
if ($_SERVER["HTTP_IF_NONE_MATCH"] == $expires)
{
header('Etag:'.$expires,true,304);
exit();
}
else {
header('Etag:'.$expires);
}
if ($_SERVER["HTTP_IF_NONE_MATCH"] == "claymorephp.com ") { header('Etag:'.'zhaiyun.com',true,304); exit(); } else { header('Etag:'."claymorephp.com"); } You can also change it slightly: $expires=date("Ymd"); //The cache expires after one day if ($_SERVER["HTTP_IF_NONE_MATCH"] == $expires) { header('Etag:'.$expires,true,304); exit(); } else { header('Etag:'.$expires); }

In addition, when GZIP and ETAG are used at the same time, problems sometimes occur, that is, ETAG has no value. This problem is common. I haven't found the relevant reason yet. After searching online for a while, people generally call it a BUG.
Based on the above reasons, the client cache of PHPBLOG is handled as follows (at the same time, HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE are judged):
Copy the PHP code to the clipboard
Copy Code The code is as follows:

      if($_SERVER['HTTP_IF_NONE_MATCH'])
        {
            if($_SERVER['HTTP_IF_NONE_MATCH'] == 'phpblog')
            {
                header('Etag:phpblog',true,304);//控制浏览器缓存
                $_SESSION['time_end']=microtime(true);
                exit();
            }
        }
        else if($_SERVER['HTTP_IF_MODIFIED_SINCE'])//eg:Sun, 02 Nov 2008 07:08:25 GMT; length=35849
        {
            $array=explode(' ',$_SERVER['HTTP_IF_MODIFIED_SINCE']);
            $gmday=$array[1];
            $month_array=array(
            "Jan"=>"01",
            "Feb"=>"02",
            "Mar"=>"03",
            "Apr"=>"04",
            "May"=>"05",
            "Jun"=>"06",
            "Jul"=>"07",
            "Aug"=>"08",
            "Sep"=>"09",
            "Oct"=>"10",
            "Nov"=>"11",
            "Dec"=>"12");
            $gmmonth=$month_array[$array[2]];
            $gmyear=$array[3];
            $array=explode(':',$array[4]);
            $gmtimestamp=gmmktime($array[0],$array[1],$array[2],$gmmonth,$gmday,$gmyear);
            if(gmmktime()-$gmtimestamp<$config_client_cache_time*60*60)
            {
                header('Etag:phpblog',true,304);//控制浏览器缓存
                $_SESSION['time_end']=microtime(true);
                exit();
            }
        }
if($_SERVER['HTTP_IF_NONE_MATCH']) { if($_SERVER['HTTP_IF_NONE_MATCH'] == 'phpblog') { header('Etag:phpblog',true,304);//控制浏览器缓存 $_SESSION['time_end']=microtime(true); exit(); } } else if($_SERVER['HTTP_IF_MODIFIED_SINCE'])//eg:Sun, 02 Nov 2008 07:08:25 GMT; length=35849 { $array=explode(' ',$_SERVER['HTTP_IF_MODIFIED_SINCE']); $gmday=$array[1]; $month_array=array( "Jan"=>"01", "Feb"=>"02", "Mar"=>"03", "Apr"=>"04", "May"=>"05", "Jun"=>"06", "Jul"=>"07", "Aug"=>"08", "Sep"=>"09", "Oct"=>"10", "Nov"=>"11", "Dec"=>"12"); $gmmonth=$month_array[$array[2]]; $gmyear=$array[3]; $array=explode(':',$array[4]); $gmtimestamp=gmmktime($array[0],$array[1],$array[2],$gmmonth,$gmday,$gmyear); if(gmmktime()-$gmtimestamp<$config_client_cache_time*60*60) { header('Etag:phpblog',true,304);//控制浏览器缓存 $_SESSION['time_end']=microtime(true); exit(); } }

缓存的HEADER是这样来发送的:
PHP 代码复制到剪贴板
复制代码 代码如下:

$client_cache_time=$config_client_cache_time*60*60;//Unit-second
header('Cache-Control: public, max-age='.$client_cache_time);
header('Expires : '.gmdate (' d, d m y h: i: s', time ()+$ client_cache_time). 'gmt'); // Set the page cache time
Header ('Last-Modified:' .gmdate (''. D, d M Y H:i:s',time()).' GMT');//Return the last modification time
header('Pragma: public');
header('Etag:phpblog'); //Return identification, used to identify the last visit (there is a cache in the browser)
$client_cache_time=$config_client_cache_time*60*60;//Unit - seconds header('Cache-Control: public, max-age ='.$client_cache_time); header('Expires: '.gmdate('D, d M Y H:i:s',time()+$client_cache_time).' GMT');//Set the page cache time header('Last -Modified: '.gmdate('D, d M Y H:i:s',time()).' GMT');//Return the last modified time header('Pragma: public'); header('Etag:phpblog' );//Return identification, used to identify the last visit (there is a cache in the browser)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327397.htmlTechArticleWe often carry out various optimization solutions for cache settings on the server, but we rarely pay attention to the client cache , to be precise, it is the browser’s caching mechanism. In fact, every browser...
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