Save bandwidth with PHP caching

I have a php script that generates my list of amazon books, but due to the fact that this generates a lovely delay each time the page loads I set this to be a javascript page, using a document.write to output the html.

This has another side benefit, that I can use browser caching to save on my bandwidth by only refreshing the web service and outputting the whole page if its a old copy.

I decided that I’d only refresh the amazon javascript every day, anytime you see the books listed after that it’ll be a cached copy on your local system.

To implement this you need to be using apache, doesn’t work in IE.

You’re looking for a header called “If-Modified-Since” which the browser will send to see if a new copy is available.

$allheaders = getallheaders();
$if_modified_since = preg_replace(‘/;.*$/’, ”, $allheaders[‘If-Modified-Since’]);
$if_modified_time = strtotime($if_modified_since);

The getallheaders() function is a apache only function. Then you parse this header to get the time and convert to a time integer.

$part = 24 * 60 * 60;
$t = floor(time()/$part)*$part;

if ($if_modified_time > $t) {
   header(“HTTP/1.0 304 Not Modified”);
   exit;
}

This takes the current time, and flattens it to the nearest day. Then if the last modified since time if greater than this floored time send back the not modified header and exit.

Then, finally, if this is a ‘new’ file then send the last modified time as the current time.

$gmdate_mod = gmdate(‘D, d M Y H:i:s’, time()) . ‘ GMT’;
header(“Last-Modified: $gmdate_mod”);
header(“Content-Type: application/x-javascript”);

This output the Last-Modified header with the current timestamp. It also output the content-type as javascript, so it is handled properly.

Hope this helps.