Using Cookies in CGI Program
In this tutorial, you will learn how to work with Cookie which is a piece of text stored on client's PC by its web browser.
Let's store a cookie in the web client. First, here is a simple HTML page that asks for some input from the user that we will store:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cookies</title>
</head>
<body>
<h3>Who is your favorite Sesame Street character?</h3>
<form method="get"
action="/cgi-bin/perl_tut/cookie_recieve.pl">
<p>
<input type="text" name="Monster">
</p>
<p>
<input type="submit" value="Vote Now">
</p>
</form>
</body>
</html>
Then, a Perl program like the following will interpret the form and store a cookie on the user's browser:
!/usr/bin/perl
use strict;
use CGI;
use CGI::Cookie;
my $cgi = new CGI;
print
$cgi->header( -cookie => new CGI::Cookie(-name => 'Monster',
-value => $cgi->param('Monster'),
-expires => '+3d',
-domain => 'perltutorial.org'
)
) .
$cgi->start_html('Cookie Monster Catcher') .
$cgi->h3("I'm sending your browser a cookie right now to: " .
$cgi->param('Monster')) .
$cgi->p('<a href="cookie_reader.pl">Click here to read your cookie</a>') .
$cgi->end_html();
exit (0);
Finally, the following Perl program will read the cookie to see what it says:
!/usr/bin/perl
use strict;
use CGI;
my $cgi = new CGI;
print
$cgi->header() .
$cgi->start_html('Cookie Monster Reader') .
$cgi->h3("I see your cookie is: " . $cgi->cookie('Monster')) .
$cgi->p('<a href="http://www.perltutorial.org/">' .
'Click here to return to the Perl tutorial</a>') .
$cgi->end_html();
exit (0);
That's all there is to know about cookies (almost)! For more information, see the Perl documentation for CGI and CGI::Cookie.