How to handle If-modified-since header in PHP

Created
Modified

If-Modified-Since

The If-Modified-Since request HTTP header makes the request conditional: the server sends back the requested resource, with a 200 status, only if it has been last modified after the given date. If the resource has not been modified since, the response is a 304 without any body; the Last-Modified response header of a previous request contains the date of last modification.

header('Last-Modified: Mon, 04 Apr 2022 11:14:54 GMT');
header('Etag: "13ae4368810e6594"');
  
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Tue, 05 Apr 2022 02:34:28 GMT
Etag: W/"13ae4368810e659493f54575ddecc096d8350cf751dd0b7a921640eb9e13463d"
Last-Modified: Mon, 04 Apr 2022 11:14:54 GMT
Server: nginx
Transfer-Encoding: chunked
Vary: Accept-Encoding

Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time.

Handling If-Modified-Since

If the If-Modified-Since request header is present, then it can be parsed to get a timestamp that can be compared against the modification time. If the modification time is older than the request time, a 304 response can be returned instead of generating the page.

$updatedTime = filemtime($file);
$updatedTime = strtotime("2022-04-11 11:14:54");
$gmtTime = gmdate('D, d M Y H:i:s T', $updatedTime);
header('Last-Modified: ' . $gmtTime );

$conent = "content";
// $etag = md5_file($file);
// hash
$etag = hash('sha256', $conent);
// using CRC32
$etag = crc32($conent);

header(sprintf('Etag: "%s"', $etag));

// HTTP_IF_MODIFIED_SINCE || If-None-Match
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $gmtTime === $_SERVER['HTTP_IF_MODIFIED_SINCE'] || 
  isset($_SERVER['If-None-Match']) && $etag === $_SERVER['If-None-Match']) {
  
  http_response_code(304);
  header('X-MODIFIED-SINCE: MATCH'); 
  die();
}

The most common use case is to update a cached entity that has no associated ETag.

curl: If-Modified-Since

Type the following curl command:

curl header
curl -v -H 'If-Modified-Since: Mon, 11 Apr 2022 11:14:54 GMT' https://installmd.com/c/77/go/fetching-a-url
HTTP/1.1 304 Not Modified
Server: nginx
Date: Tue, 05 Apr 2022 03:12:29 GMT
Connection: keep-alive
Last-Modified: Mon, 11 Apr 2022 11:14:54 GMT
Etag: "4274335913"
X-MODIFIED-SINCE: MATCH

Related Tags