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