Using Cookies

Overview
Objectives
Installing Apache
Installing Perl
Lesson 1
Hello World
Anatomy of a CGI Program
Hello World with CGI.pm
Lesson 2
HTML Forms and DOM
POST and GET
A Form Example
Lesson 3
Cookie Tutorial
Database Tutorial

Software Links
FAQ / Terminology
Contact the Author

 

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>
          <head>
            <title>Cookie Monster</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 => 'inconnu.isu.edu'
                                                   )
                       ) .
           $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://inconnu.isu.edu/~ink/perl_cgi">' .
                   'Click here to return to the tutorial</a>') .
           $cgi->end_html();
        exit (0);
	  

To see this all in action:

http://inconnu.isu.edu/~ink/perl_cgi/lesson3/cookie_send.html

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


All pages written by Craig Kelley unless otherwise specified. Please use the Contact link from the menu to submit changes or suggestions. Permission is given to use this tutorial in any way you wish including re-publishing or "mirroring". The most up-to-date version of this document currently resides at http://inconnu.isu.edu/~ink/perl_cgi.

This page updated: May 6, 2002 22:21