简体   繁体   中英

ETAG -How to set expiration time?

I was try to set ETAG in my PHP page using the following code,

$time       = strtotime(date('Y-m-d H:i:').'00');
$lastmod    = gmdate('D, d M Y H:i:s \G\M\T', $time);
$etag       = '123';
$ifmod      = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?   $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $lastmod : null; 
$iftag      = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] ==      $etag : null; 

if (($ifmod || $iftag) && ($ifmod !== false && $iftag !== false)) { 
  header('HTTP/1.0 304 Not Modified');
  die;
} else {
  header("Last-Modified: $lastmod"); 
  header("ETag: $etag");
  echo "My Page content";
}

I write this code for caching enable for one minute,But it is not perfect ,because
strtotime(date('Ymd H:i:').'00'); is not give a absolute one minute interval.

Is there any other solution?

I'm struggling to understand your question. I think a large part of the reason for this is that Etags have nothing to with with expiration time. You could use the Etag as a proxy fr an expiration time, but that rather defeats the point.

If you've served up the content with correct caching information in the first place, then the client will not be making a conditional request until the cachetime has expired.

The only scenario where it makes sense to use Etags to manage caching is where you are publishing large content items (ie audio, video and PDFs) where you must re-use the same URL for updated content.

strtotime(date('Ymd H:i:').'00'); is not give a absolute one minute interval

Yes it does, but it's relative to the server's clock, not the client's clock.

It is impossible to enforce expiration at exactly :00 unless clocks are synced. However if you set a max-age=60 and age=`date('s') then this will work for clients with accurate clocks and only be up to 60 seconds out for non-synced clients.

Yes, I agree with symcbean. Etag has nothing to with time expiration. At first, server generates the etag against the response and send them to client. Client gets the response and etag. If client want to get the response again with returned etag, server would calculate the response again and generate a new etag to make comparison with the etag from client's request. If match, send 304. otherwise send the response with new etag directly.

What I mean by the description above is that server doesn't cache the etag of any response, indicating that there's no concept of expiration in terms of Etag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM