» Perl CGI » Using Cookies in CGI Program
Using Cookies in CGI Program
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:
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<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.