1. Home
  2. Computing & Technology
  3. Perl

Working with CGI.pm In-Depth - Creating HTTP Headers

From About.com

4 of 5

Expiring Documents

Some special header options can be used to control browser and search engine caching by setting a specific expiration date on your documents. Although we can't maintain total control over what a browser or a search engine does, setting a proper expiration date is a big plus.

Let's say, for example, that you have a dynamic page on your web site that changes once a week, you want to inform the client that the documents will expire in seven days, prompting it to check back for the new updates if the page is accessed a week later. Using CGI.pm's header function, it's as simple as adding an -expires option to the function.

#!/usr/bin/perl -w

use strict;
use CGI qw/:standard/;
my $cgi = new CGI;

print $cgi->header( -expires => '+7d' );
Running this script will produce the following output (differing depending on when you run the script, obviously).
Expires: Fri, 01 Dec 2006 15:58:27 GMT
Date: Fri, 24 Nov 2006 15:58:27 GMT
Content-Type: text/html; charset=ISO-8859-1
Or maybe you don't want the client to cache the page at all, always ensuring that they have the latest version of a specific document. This could be accomplished by expiring the document right as you create it using now:
print $cgi->header( -expires => 'now' );
Or even expiring the document in the past by setting the expiration date to a negative value (one day ago):
print $cgi->header( -expires => '-1d' );
If your content does not change at all, or changes very infrequently, you can pass a larger value and allow clients to cache the data for a longer time. In this example, we're expiring the document after three months:
print $cgi->header( -expires => '+3M' );
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. CGI & Web
  5. Working with CGI.pm In-Depth - How to create HTTP Headers, Content, Attachments and Redirect with CGI.pm

©2009 About.com, a part of The New York Times Company.

All rights reserved.