Same name and namespace in other branches
  1. 6.x includes/bootstrap.inc \drupal_page_cache_header()

Set HTTP headers in preparation for a cached page response.

The general approach here is that anonymous users can keep a local cache of the page, but must revalidate it on every request. Then, they are given a '304 Not Modified' response as long as they stay logged out and the page has not been modified.

File

includes/bootstrap.inc, line 583
Functions that need to be loaded on every Drupal request.

Code

function drupal_page_cache_header($cache) {

  // Set default values:
  $last_modified = gmdate('D, d M Y H:i:s', $cache->created) . ' GMT';
  $etag = '"' . md5($last_modified) . '"';

  // See if the client has provided the required HTTP headers:
  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
  if ($if_modified_since && $if_none_match && $if_none_match == $etag && $if_modified_since == $last_modified) {

    // if-modified-since must match
    header('HTTP/1.1 304 Not Modified');

    // All 304 responses must send an etag if the 200 response for the same object contained an etag
    header("Etag: {$etag}");
    return;
  }

  // Send appropriate response:
  header("Last-Modified: {$last_modified}");
  header("ETag: {$etag}");

  // The following headers force validation of cache:
  header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
  header("Cache-Control: must-revalidate");

  // Determine if the browser accepts gzipped data.
  if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE && function_exists('gzencode')) {

    // Strip the gzip header and run uncompress.
    $cache->data = gzinflate(substr(substr($cache->data, 10), 0, -8));
  }
  elseif (function_exists('gzencode')) {
    header('Content-Encoding: gzip');
  }

  // Send the original request's headers. We send them one after
  // another so PHP's header() function can deal with duplicate
  // headers.
  $headers = explode("\n", $cache->headers);
  foreach ($headers as $header) {
    header($header);
  }
  print $cache->data;
}