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:
This will produce the following output, which is the basic format for a standard HTTP cookie:
print $cgi->cookie( -name => 'my_cookie', -value => 'This is what I keep in my cookie.' );
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:
You can also limit the specific directories that the cookie can operate by specifying the -path attribute:
-domain => '.example.com'
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:
-path => '/cgi-bin'
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:
-expires => '+1d'
or 10 minutes:
print $cgi->cookie( -name => 'my_six_month_cookie', -value => 'Six months!', -expires => '+6M', -domain => '.example.com' );
Or, you can expire it in the past to negate the cookie entirely:
print $cgi->cookie( -name => 'my_ten_minute_cookie', -value => 'Ten Minutes', -expires => '+106m', -domain => '.example.com' );
print $cgi->cookie( -name => 'my_old_cookie', -value => 'Expired!', -expires => '-1d', -domain => '.example.com' );