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:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Cookies</title>
  5. </head>
  6. <body>
  7. <h3>Who is your favorite Sesame Street character?</h3>
  8. <form method="get" action="/cgi-bin/perl_tut/cookie_recieve.pl">
  9.   <p>
  10.     <input type="text" name="Monster">
  11.   </p>
  12.   <p>
  13.     <input type="submit" value="Vote Now">
  14.   </p>
  15. </form>
  16. </body>
  17. </html>

Then, a Perl program like the following will interpret the form and store a cookie on the user's browser:

  1. #!/usr/bin/perl
  2. use strict;
  3. use CGI;
  4. use CGI::Cookie;
  5.  
  6. my $cgi = new CGI;
  7.  
  8. print
  9.    $cgi->header( -cookie => new CGI::Cookie(-name => 'Monster',
  10.     -value => $cgi->param('Monster'),
  11.     -expires => '+3d',
  12.     -domain => 'perltutorial.org'
  13.    )
  14.        ) .
  15.    $cgi->start_html('Cookie Monster Catcher') .
  16.    $cgi->h3("I'm sending your browser a cookie right now to: " .
  17.    $cgi->param('Monster')) .
  18.    $cgi->p('<a href="cookie_reader.pl">Click here to read your cookie</a>') .
  19.    $cgi->end_html();
  20. exit (0);
  21.  

Finally, the following Perl program will read the cookie to see what it says:

  1. #!/usr/bin/perl
  2. use strict;
  3. use CGI;
  4. my $cgi = new CGI;
  5. print
  6.    $cgi->header() .
  7.    $cgi->start_html('Cookie Monster Reader') .
  8.    $cgi->h3("I see your cookie is: " . $cgi->cookie('Monster')) .
  9.    $cgi->p('<a href="http://www.perltutorial.org/">' .
  10.    'Click here to return to the Perl tutorial</a>') .
  11.    $cgi->end_html();
  12. exit (0);
  13.  

That's all there is to know about cookies (almost)! For more information, see the Perl documentation for CGI and CGI::Cookie.