Example: Last-Modified Headers in Scripts
This Perl CGI script shows one way to use Last-Modified header in scripts, for demonstration purposes.
#!/usr/bin/perl use strict; use warnings; use CGI; use CGI::Util; use Date::Parse; my $q = new CGI; my $last_mod = $ENV{HTTP_IF_MODIFIED_SINCE}; if (defined $last_mod) { $last_mod = str2time($last_mod); if (time() - $last_mod < 60) { print $q->header(-status=>304); exit 0; } } print $q->header(-type => "text/html", -status => 200, -last_modified => CGI::Util::expires("now")); print "<html><body>\n<h1>Last-Modified Test</h1>\n" . "<p>Date: ".scalar localtime()."</p>\n" . "<table>\n"; foreach my $var (sort keys %ENV) { next unless $var =~ /^HTTP_/; print "<tr><td>$var</td><td>$ENV{$var}</td></tr>\n"; } print "</table></body></html>\n"; exit 0;
The script starts by checking for an HTTP If-Modified-Since header from the browser. If it gets one, and the modification date was within the last 60 seconds, it sends a 304 Not Modified response.
If not, it sends a response body with a Last-Modified header set to the current time, which the browser will send back on subsequent requests in the If-Modified-Since header.
The effect is that when you load the script through a CGI web server, it will display a response like this:
Last-Modified Test
Date: Fri Aug 3 17:02:08 2007
HTTP_ACCEPT | text/xml,application/xml,application/xhtml+xml,... |
HTTP_ACCEPT_CHARSET | ISO-8859-1,utf-8;q=0.7,*;q=0.7 |
HTTP_ACCEPT_ENCODING | gzip,deflate |
HTTP_ACCEPT_LANGUAGE | en-us,en;q=0.5 |
HTTP_CONNECTION | keep-alive |
HTTP_COOKIE | 200 |
HTTP_HOST | localhost |
HTTP_IF_MODIFIED_SINCE | Wed, 01 Aug 2007 15:59:49 GMT |
HTTP_KEEP_ALIVE | 300 |
HTTP_USER_AGENT | Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.5) Gecko/20060601 Firefox/2.0.0.5 (Ubuntu-edgy) |
If you reload the page within the next 60 seconds, the server will not send a new response, and you will see the same page instead of a newly generated page. The easiest way to tell is that the Date and HTTP_IF_MODIFIED_SINCE will not change when you reload.
One minute after you load the page, it will expire from the cache, and a subsequent request will load it again, setting a new expiry time in the cache.