1. Home
  2. Computing & Technology
  3. Perl

Working with CGI.pm In-Depth

Setting a Cookie in a Browser

From About.com

Since HTTP is by definition a stateless protocol, we need a method to retain sessions across transactions. This can be done in several ways, but the most clean and common is by setting a cookie in the client's browser. A cookie is basically a key / value pair that is stored in a tiny text file on the clients machine. Cookies are sent in the HTTP headers, and can thus be used to track a user across transactions.

CGI.pm has a nice, simple set of functions for setting and reading cookies on clients that access your site. Let's take a look at the cookie function in its simplest form:

print $cgi->cookie(
-name => 'my_cookie',
-value => 'This is what I keep in my cookie.'
);
This will produce the following output, which is the basic format for a standard HTTP cookie:
my_cookie=This%20is%20what%20I%20keep%20in%20my%20cookie.; path=/
There are a few useful attributes we need to learn as well, starting with -domain. The domain attribute is used to designate (or limit) the domains that the cookie will operate. The most common setting is to leave off the sub-domain and specify the wild-card of .example.com like so:
-domain => '.example.com'
You can also limit the specific directories that the cookie can operate by specifying the -path attribute:
-path => '/cgi-bin'
Finally, you can specify an expiration date for the cookie to allow it to be saved beyond the user shutting down their browser. This is done with the -expires attribute:
-expires => '+1d'
The -expires attribute uses a special form of notation that looks like <modifier><number><timespan> where modifier is a plus or minus, and timespan is one of s (seconds), m (minutes), h (hours), d (days), M (months), or y (years). So to set a cookie that lasts 6 months:
print $cgi->cookie(
-name => 'my_six_month_cookie',
-value => 'Six months!',
-expires => '+6M',
-domain => '.example.com'
);
or 10 minutes:
print $cgi->cookie( -name => 'my_ten_minute_cookie',
-value => 'Ten Minutes',
-expires => '+106m',
-domain => '.example.com'
);
Or, you can expire it in the past to negate the cookie entirely:
print $cgi->cookie(
-name => 'my_old_cookie',
-value => 'Expired!',
-expires => '-1d',
-domain => '.example.com'
);

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. CGI & Web
  5. Working with CGI.pm In-Depth - How to set a cookie

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

All rights reserved.