Mike Gossland's Perl Tutorial Course for Windows


CGI In Use | Site Search | Presenting Data | Cookies


Chapter 7. CGI In Use

Handling Cookies

The CGI module makes setting and retrieving cookies very easy. There are special "cookie" functions that allow you to build a cookie header, and retrieve cookie values.

Basically, there are two functions; one for reading cookies

#Read the cookie variable
$ID = $cgi->cookie('ID');

and one for writing cookies

$ID_cookie = $cgi->cookie( -name => ID, -value => $name, -path => '/', -expires => '+1M' );

The function to create a cookie returns a string, in this case saved in $ID_cookie, which is then sent out as part of the header to set the cookie at the browser:

print $cgi->header( -cookie => $ID_cookie );

Here is a script that does that:


#!/usr/bin/perl
#cookie_demo.pl

use CGI;
use CGI::Carp qw(fatalsToBrowser);

$cgi = new CGI;

#Read the input variables
$name = $cgi->param('name');
$request = $cgi->param('request');

#Read the cookie variable
$ID = $cgi->cookie('ID');


#Leave the cookie as read unless
#it's being set to a new value
#or cleared.
if ( $request =~ /Set/ ) {

	#Update the cookie with the new variable
	if ( $name ) {
		$ID_cookie = $cgi->cookie( -name => ID, -value => $name,
								-path => '/', -expires => '+1M' );
		$ID = $name;
	}

} elsif ( $request =~ /Clear/ ) {

	#Clear the cookie. Set it to "" and expire yesterday
	$ID_cookie = $cgi->cookie( -name => ID, -value => "",
							-path => '/', -expires => '-1d' );
	$ID = "";
}

#Print a new "Content type" header
#And set the cookie at the same time;
print $cgi->header( -cookie => $ID_cookie );

#substitute the results into the original form
$form = "/home/mgossland/webapps/web2py/web2py/applications/perlcourse/views/cgi_use/cookie_form.html";
open (FORM, $form)
	or die "Can't open cookie_form page at $form: $!";

while ( <FORM> ) {
	
	#substitute the cookie value into the reserved place	
	s{<!-- cookie_results -->}{$ID};

	print;

}

close FORM;


The Set, Check and Clear buttons in the form action invoke the relevant sections in the script.

Next time you send any form in to the server, the cookie goes along for the ride. This cookie is available to any script on the server from then on.

Also as a handy trick, you can also check the value of a cookie with this little bit of javascript that runs on your local browser. This check does not involve the server. This is quite useful for debugging.

Note that you can use cookies to track your visitors, at least when they visit pages served by scripts. Just check their cookies and append the details of their visit to a log file.