Mike Gossland’s Perl Tutorial Course for Windows

Chapter 7. CGI In Use

CGI In Use
Site search
Presenting data from a database
Handling Cookies
Uploading files to the server
Requesting info from other servers

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 );

To see this in action, bring up a small cookie handling form here, and try out the Set, Check and Clear buttons.

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.

Click here to look at the perl script that handles these cookies.

(Just for your information, 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.

Next Page

Search this site or the web:

Google
just this site the whole web

Questions? Feedback?

Email me your comments!