Conditional GET

From DreamHost

Jump to: navigation, search

A conditional GET method requests that a document be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached documents to be refreshed without requiring multiple requests or transferring data already held by the client. With the Apache HTTP Server utilized by DreamHost, this caching should occur automatically for static pages. For dynamic pages, deliberate action is necessary.

Contents

mod_rewrite Solution

The best approach is to use mod_rewrite to perform a conditional GET.

PHP Solution

It is possible to use PHP to force a conditional GET, by examining $_SERVER['HTTP_IF_MODIFIED_SINCE'] if it is available. Consider the following function:

function conditionalGET($timestamp) {
  $last-modified = gmdate("D, d M Y H:i:s \G\M\T", $timestamp);
  $etag = '"'.md5($last-modified).'"';
  header("Last-Modified: $last-modified");
  header("ETag: $etag");
  $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) return;
  if($if-none-match && $if-none-match != $etag) return;
  if($if-modified-since && $if-modified-since != $last-modified) return;
  header("HTTP/1.0 304 Not Modified");
  exit;
}

To use the function, work out the timestamp for when the document was last modified and call the function with:

conditionalGET($timestamp);

See Also

External Links

Personal tools