C.9 The CGI .pm ModuleC.9.1 IntroductionThe most popular Perl 5 library for writing dynamic CGI programs such as guestbooks, page counters, feedback forms, etc., is the CGI .pm module written by Lincoln Stein; it is included in the standard Perl library starting with version 5.004. The most recent version of CGI .pm can be found at www.perl.com/CPAN . CGI .pm not only takes advantage of the object-oriented features that were introduced in Perl 5, it also provides methods ( GET and POST ) to interpret query strings, handle forms, and hide the details of HTML syntax. Lincoln Stein has also written Official Guide to Programming with CGI.pm [6] (www. wiley .com/compbooks/stein), an excellent , easy-to-read guide from which much of the following information was gleaned.
C.9.2 Advantages
C.9.3 Two Styles of Programming with CGI .pmThe Object-Oriented StyleUsing the object-oriented style, you create one or more CGI objects and then use object methods to create the various elements of the page. Each CGI object starts out with the list of named parameters that were passed to your CGI script by the server. You can modify the objects and send them to a file or database. Each object is independent; it has its own parameter list. If a form has been filled out, its contents can be saved from one run of the script to the next ; that is, it maintains its state . (Normally the HTML documents are stateless , in other words, everything is lost when the page exits.) Example C.291 use CGI; 2 $obj=new CGI; # Create the CGI object 3 print $obj->header, # Use functions to create the HTML page 4 $obj->start_html("Object oriented syntax"), 5 $obj->h1("This is a test..."), $obj->h2("This is a test..."), $obj->h3("This is a test..."), 6 $obj->end_html; EXPLANATION The following output can be seen by viewing the source from the browser. It demonstrates the HTML output produced by the CGI .pm module. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <head><title>Object oriented syntax</title></head><body> <h1>This is a test...</h1> <h2>This is a test...</h2> <h3>This is a test...</h3> </body </html> Figure C.20. Output from the object-oriented CGI script in Example C.29.
Function-Oriented StyleThe function-oriented style is easier to use than the objectoriented style, because you don't create or manipulate the CGI object directly. The module creates a default CGI object for you. You use the same built-in functions to manipulate the object, pass parameters to the functions to create the HTML tags, and retrieve the information passed into the form. Although the function-oriented style provides a cleaner programming interface, it limits you to using one CGI object at a time. The following example uses the function-oriented interface. The main differences are that the :standard functions must be imported into the program's namespace, and you don't create a CGI object. It is created for you. [8]
Example C.30#!/usr/bin/perl 1 use CGI qw(:standard); # Function-oriented style uses a set of # standard functions 2 print header, 3 start_html("Function oriented syntax"), 4 h1("This is a test..."), h2("This is a test..."), h3("This is a test..."), 5 end_html; Figure C.21. Output from the function-oriented CGI script in Example C.30.
C.9.4 How Input from Forms Is ProcessedA CGI script consists of two parts : the part that creates the form that will be displayed in the browser, and the part that retrieves the input from the form, parses it, and handles the information by sending it back to the browser, to a database, to e-mail, etc. Creating the HTML FormMethods are provided to simplify the task of creating the HTML form. For example, there are methods to start and end the HTML form, methods for creating headers, checkboxes, pop-up menus, radio buttons, Submit and Reset buttons, etc. Table C.14 lists the most used of the HTML methods provided by CGI .pm . When passing arguments to the CGI .pm methods, two styles can be used:
Example C.32(The CGI script) # Shortcut calling styles with HTML methods use CGI qw(:standard); # Function-oriented style print header 1 start_html("Testing arguments"), b(), 2 p(), 3 p("red", "green", "yellow"), 4 p("This is a string"), 5 p({-align=>center}, "red", "green", "yellow"), 6 p({-align=>left}, ["red","green","yellow"]), end_html; ( Output produced by CGI.pm methods ) 1 Content-Type: text/html; charset=ISO-8859-1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <head><title>Testing arguments</title></head> <body> <b /> 2 <p /> 3 <p>red green yellow</p> 4 <p>This is a string</p> 5 <p align="center">red green yellow</p> 6 <p align="left">red</p> <p align="left">green</p> <p align="left">yellow</p> </body> </html> EXPLANATION
To avoid conflicts and warnings ( -w switch), enclose all arguments in quotes. Table C.14. HTML methods.
Processing the Form's Data with param()After the user has filled in a form, CGI .pm will take the input from the form and store it in name/value pairs. The names and values can be retrieved with the param() function. When param() is called, if null is returned, then the form has not yet been filled out. If the param() function returns true (non-null), then the form must have been filled out, and the param() function can be used to retrieve the form information. If you want an individual value, the param() can retrieve it by its name. The following example illustrates the two parts to the CGI program: the HTML form, and how to get the information with the param() function. For a list of other methods used to process parameters, see Table C.16. Example C.33#!/usr/bin/perl 1 use CGI qw(:standard); 2 print header ; 3 print start_html (-title=> 'Using the Function-Oriented Syntax', -BGCOLOR=>'yellow'); 4 print img({-src=>'/Images/GreenBalloon.gif', -align=LEFT}), 5 h1("Let's Hear From You!"), h2("I'm interested."), 6 start_form, 7 "What's your name? ", textfield('name') , 8 p, "What's your occupation? ", textfield('job'), p, 9 "Select a vacation spot. ", popup_menu( -name=>'place', -values=>['Hawaii','Europe','Mexico', 'Japan' ], ), p, 10 submit, 11 end_form; print hr; 12 if ( param () ){ # If the form has been filled out, # there are parameters 13 print "Your name is ", em( param('name') ), p, "Your occupation is ", em( param('job') ), p, "Your vacation spot is", em( param('place') ), hr; } EXPLANATION
Figure C.22. Output from lines 1 “11 in Example C.33 before filling out the form.
Figure C.23. The completed form and result of CGI.pm processing.
Checking the Form at the Command LineIf you want to see the HTML tags generated by the CGI .pm form, you can run your script at the command line, but you will probably see the following error message: (Offline mode: enter name=value pairs on standard input) You can handle this by typing in key/value pairs and then pressing <Ctrl>-d (UNIX) or <Ctrl>-z (Windows) or by passing an empty parameter list. When the parameter list is empty, the output will let you see the HTML tags that were produced without any values assigned. See Example C.34. Example C.34(At the Command Line) 1 $ perl talkaboutyou.pl (Offline mode: enter name=value pairs on standard input) name=Dan job=Father place=Hawaii <Now press Ctrl-d or Ctrl-z> (Output) Content-Type: text/html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML><HEAD><TITLE>Using the Function Oriented Syntax</TITLE> </HEAD><BODY BGCOLOR="yellow"> <H1>Let's Hear From You!</H1> <H2>I'm internested.</H2> <FORM METHOD="POST" ENCTYPE="application/x-www-form-urlencoded"> What's your name? <INPUT TYPE="text" NAME="name" VALUE="Dan"><P>What's your occupation? <INPUT TYPE="text" NAME="job" VALUE="Father"><P>Select a vacation spot. <SELECT NAME="place"> <OPTION SELECTED VALUE="Hawaii">Hawaii <OPTION VALUE="Europe">Europe <OPTION VALUE="Mexico">Mexico <OPTION VALUE="Japan">Japan </SELECT> <P><INPUT TYPE="submit" NAME=".submit"></FORM> <HR>Your name is <EM>Dan</EM><P>Your occupation is <EM>Father </EM><P>Your vacation spot is <EM>Hawaii</EM><HR> (At the Command Line) 2 $ perl talkaboutyou.pl < /dev/null or perl talkaboutyou.pl ' ' Content-Type: text/html (Output) <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML><HEAD><TITLE>Using the Function Oriented Syntax</TITLE> </HEAD><BODY BGCOLOR="yellow"> <H1>Let's Hear From You!</H1> <H2>I'm interested.</H2><FORM METHOD="POST" ENCTYPE="application/x-wwwform-urlencoded"> What's your name? <INPUT TYPE="text" NAME="name" VALUE=""><P>What's your occupation? <INPUT TYPE="text" NAME="job" VALUE=""><P>Select a vacation spot. <SELECT NAME="place"> <OPTION VALUE="Hawaii">Hawaii <OPTION VALUE="Europe">Europe <OPTION VALUE="Mexico">Mexico <OPTION VALUE="Japan">Japan </SELECT> <P><INPUT TYPE="submit" NAME=".submit"></FORM><HR>Your name is <EM><P>Your occupation is <EM><P>Your vacation spot is <EM><HR> EXPLANATION
C.9.5 CGI .pm Form ElementsTable C.15. CGI methods.
Table C.16. CGI parameter methods.
Methods For Generating Form Input FieldsThe following examples use the object-oriented style, and can easily be replaced with the function-oriented style by removing all object references. The print_form subroutine will cause the form to be displayed in the browser window and the do_work subroutine will produce output when the param method returns a true value, meaning that the form was filled out and processed. The texfield() MethodThe textfield method creates a text field. The text field allows the user to type in a single line of text into a rectangular box. The box dimensions can be specified with the -size argument, where the size is the width in characters , and -maxlength (a positive integer) sets an upper limit on how many characters the user can enter. If -maxlength is not specified, the default is to enter as many characters as you like. With the -value argument, the field can be given a default value, text that will appear in the box when it is first displayed. FORMAT print $obj->textfield('name_of_textfield'); print $obj->textfield( -name=>'name_of_textfield', -value=>'default starting text', -size=>'60', # Width in characters -maxlength=>'90'); # Upper width limit Example C.35#!/usr/bin/perl 1 use CGI; 2 $query = new CGI; # Create a CGI object 3 print $query->header; 4 print $query->start_html("Forms and Text Fields"); 5 print $query->h2("Example: The textfield method"); 6 &print_form($query); 7 &do_work($query) if ($query->param); print $query->end_html; 8 sub print_form{ 9 my($query) = @_; 10 print $query->startform; print "What is your name? "; 11 print $query->textfield('name'); # A simple text field print $query->br(); 12 print "What is your occupation? "; 13 print $query->textfield(-name=>'occupation', # Giving values -default=>'Retired', # to the -size=>60, # text field -maxlength=>120, ); print $query->br(); 14 print $query->submit('action', 'Enter '); 15 print $query->reset(); 16 print $query->endform; print $query->hr(); } 17 sub do_work{ my ($query) = @_; my (@values, $key); print $query->("<H2>Here are the settings</H2>"); 18 foreach $key ($query->param) { print "$key: \n"; 19 @values=$query->param($key); print join(", ",@values), "<BR>"; } } EXPLANATION
Figure C.25. Output after the form was filled out and processed, Example C.35.
Figure C.26. The HTML source that was produced by CGI.pm .
The checkbox() MethodThe checkbox() method is used to create a simple checkbox for a yes or no (Boolean) response. The checkbox has NAME and VALUE attributes, where -name gives the CGI parameter a name and -value contains one item or a reference to a list of items that can be selected. If the -checked is assigned 1 , the box will start as checked. If -label assigned a value, it will be printed next to the checkbox; if not, the -name value of the checkbox will be printed. If not selected, the checkbox will contain an empty parameter. The checkbox_group() method creates a set of checkboxes all linked by a single name. The options are not mutually exclusive; that is, the user can check one or more items. If -linebreak is assigned a non-zero number, the options will be vertically aligned. Ordinarily, the options would be displayed in a horizontal row. (See Example C.36.) FORMAT print $obj->checkbox (-name=>'name_of_checkbox', -checked=>1, -value=>'ON' -label=>'Click on me' ); %labels = ('choice1'=>'red', 'choice2'=>'blue', 'choice3'=>'yellow', ); print $obj->checkbox_group (-name=>'name_of_checkbox', -values=>[ 'choice1', 'choice2', 'choice3', 'green',...], -default=>[ 'choice1', 'green' ], -linebreak => 1, -labels=>\%labels ); Example C.36#!/usr/bin/perl use CGI; $query = new CGI; print $query->header; print $query->start_html("The Object Oriented CGI and Forms"); print "<H2> Example using Forms with Checkboxes </H2>\n"; &print_formstuff($query); &do_work($query) if ($query->param); print $query->end_html; sub print_formstuff{ my($query) = @_; 1 print $query->startform; print "What is your name? "; print $query->textfield('name'); # A simple text field print "<BR>"; print "Are you married? <BR>"; 2 print $query->checkbox (-name=>'Married', -label=>'If not, click me' ); # Simple checkbox print "<BR><BR>"; print "What age group(s) do you hang out with? <BR>"; 3 print $query->checkbox_group(-name=>'age_group', -values=>[ '12-18', '19-38', '39-58','59-100' ], -default=>[ '19-38' ], -linebreak=>'true', ); 4 print $query->submit('action', 'Select'); 5 print $query->reset('Clear'); print $query->endform; print "<HR>\n"; } 6 sub do_work{ my ($query) = @_; my (@values, $key); print "<H2>Here are the settings</H2>"; 7 foreach $key ($query->param){ print "$key: \n"; 8 @values=$query->param($key); print join(", ",@values) , "<BR>"; } } EXPLANATION
Figure C.27. Output for checkbox form in Example C.36.
Figure C.28. Output after the form was filled out and processed, Example C.36.
The radio_group() and popup_menu() MethodsTo select among a set of mutually exclusive choices, you can use radio buttons or pop-up menus. Radio button groups allow a small number of choices to be grouped together to fit in the form; for a large number of choices, the pop-up menu is better. They both have arguments consisting of name/value pairs. Since the value argument consists of more than one selection, it takes a reference to an array. The -default argument is the value that is displayed when the menu first appears. The optional argument -labels is provided if you want to use different values for the user-visible label inside the radio group or pop-up menu and the value returned to your script. It's a pointer to an associative array relating menu values to corresponding user-visible labels. If a default isn't given, the first item is selected in the pop-up menu. FORMAT %labels = ('choice1'=>'red', 'choice2'=>'blue', 'choice3'=>'yellow', ); print $obj->radio_group(-name=>'name_of_radio_group', -values=>['choice1','choice2', 'choice3', 'green', ...], -default=>[ 'choice1', 'green' ], -linebreak => 1, -labels=>\%labels ); %labels = ('choice1'=>'red', 'choice2'=>'blue', 'choice3'=>'yellow', ); print $obj->popup_menu(-name=>'name_of_popup_menu', -values=>['choice1','choice2','choice3', 'green',...], -default=>[ 'choice1', 'green' ], -linebreak => 1, -labels=>\%labels ); Example C.37#!/bin/perl 1 use CGI; $query = new CGI; print $query->header; print $query->start_html("The Object-Oriented CGI and Forms"); print "<H2> Example using Forms with Radio Buttons </H2>\n"; &print_formstuff($query); &do_work($query) if ($query->param); print $query->end_html; sub print_formstuff{ my($query) = @_; print $query-> startform; print "What is your name? "; print $query->textfield('name'); # A simple text field print "<BR>"; print "Select your favorite color? <BR>"; 2 print $query->radio_group(-name=>'color', -values=>[ 'red', 'green', 'blue','yellow' ], -default=>'green', -linebreak=>'true', ); print $query->submit('action', 'submit'); print $query->reset('Clear'); print $query-> endform ; print "<HR>\n"; } sub do_work{ my ($query) = @_; my (@values, $key); print "<H2>Here are the settings</H2>"; 3 foreach $key ($query->param){ print "$key: \n"; 4 @values=$query->param($key); print join(", ",@values), "<BR>"; } } EXPLANATION
Figure C.29. Output for radio button form, Example C.37.
Figure C.30. Output after form was filled out and processed, Example C.37.
LabelsLabels allow the buttons to have user-friendly names that are associated with different corresponding values within the program. In the following example, the labels stop, go , and warn will appear beside radio buttons in the browser window. The values returned by the param method will be red, green, and yellow , respectively. Example C.38( The -labels Parameter -- Segment from CGI script) print $query->startform; print "What is your name? "; print $query->textfield('name'); # A simple text field print "<BR>"; print "We're at a cross section. Pick your light.<BR>"; 1 print $query->radio_group(-name=>'color', 2 -values=>[ 'red', 'green', 'yellow' ], -linebreak=>'true', 3 -labels=>{red=>'stop', green=>'go', yellow=>'warn', }, 4 -default=>'green', ); print $query->submit('action', 'submit'); print $query->reset('Clear'); print $query->endform; } EXPLANATION
Figure C.31. Output for labels form after being filled out and processed, Example C.38.
The popup_menu() MethodThe pop-up menu is also referred to as a drop-down list . It is a list of selections that will be displayed when the user clicks on the scrollbar icon to the right of the text. Only one selection can be made. Example C.39#!/usr/bin/perl use CGI; $query = new CGI; print $query->header; print $query->start_html("The Object-Oriented CGI and Forms"); print "<H2> Example using Forms with Pop-up Menus </H2>\n"; &print_formstuff($query); &do_work($query) if ($query->param); print $query->end_html; sub print_formstuff{ my($query) = @_; print $query->startform; print "What is your name? "; print $query->textfield('name'); # A simple text field print "<BR>"; print "Select your favorite color? <BR>"; print $query->popup_menu(-name=>'color', -values=>[ 'red', 'green', 'blue', 'yellow' ], -default=>'green', -labels=>'\%labels', ); print $query->submit('action', 'submit'); print $query->reset('Clear'); print $query->endform; print "<HR>\n"; } sub do_work{ my ($query) = @_; my (@values, $key); print "<H2>Here are the settings</H2>"; foreach $key ($query->param){ print "$key: \n"; @values=$query->param($key); print join(", ",@values), "<BR>"; } } Figure C.32. Output for pop-up menu form, Example C.39.
Figure C.33. Output for pop-up menu form after being filled out and processed, Example C.39.
The submit() and reset() MethodsThe submit() method creates a button that, when pressed, sends form input to the CGI script. If given an argument, you can label the button, often for the purpose of distinguishing it from other buttons if several Submit buttons are used. The reset() method is used to clear all the entries in a form. It restores the form to the state it was in when last loaded, not to its default state. (See "The defaults Method," below.) Clearing FieldsThe override ArgumentNote that if you press the Reset button or restart the same form, the previous information is sticky; in other words, the input box is not cleared. You can force the entry to be cleared by using the -override or -force argument with a non-zero value; for example: textfield(-name=>'name', -override=>1); The defaults MethodThe defaults() method clears all entries in the form to the state of the form when it was first displayed in the browser window; that is, the parameter list is cleared. To create a user-readable button, call the defaults method; for example: print defaults(-name=>'Clear All Entries'); Error HandlingWhen your CGI .pm script contains errors, the error messages are normally sent by the server to error log files configured under the server's root. If the program aborts, the browser will display "Document contains no data" or "Server Error." These messages are not very helpful. The carpout and fatalsToBrowser MethodsCGI .pm provides methods, not only to store errors in your own log file, but also to see fatal error messages in the browser's window. The carpout function is provided for this purpose. Since is not exported by default, you must import it explicitly by writing: use CGI::Carp qw(carpout); The carpout function requires one argument, a reference to a user-defined filehandle where errors will be sent. It should be called in a BEGIN block at the top of the CGI application so that compiler errors will be caught. To cause fatal errors from die, croak , and confess to also appear in the browser window, the fatalsToBrowser function must also be imported. Example C.40#!/usr/bin/perl 1 use CGI; 2 BEGIN{ use CGI::Carp qw(fatalsToBrowser carpout ); 3 open(LOG,">>errors.log") die "Couldn't open log file\n"; 4 carpout(LOG); } $query = new CGI; <Program continues here> EXPLANATION
Figure C.34. Redirecting errors with carpout and fatalsToBrowser .
Changing the Default MessageBy default, the software error message is followed by a note to contact the Webmaster by e-mail with the time and date of the error. If you want to change the default message, you can use the set_message method, which must be imported into the programs namespace. FORMAT use CGI::Carp qw(fatalsToBrowser set_message); set_message ("Error message!"); set_message(\reference_to_subroutine); Example C.411 use CGI; 2 BEGIN{ use CGI::Carp qw(fatalsToBrowser carpout ); 3 open(LOG,">>errors.log") die "Couldn't open log file\n"; 4 carpout(LOG); 5 sub handle_errors { 6 my $msg = shift; 7 print "<h1>Software Error Alert!!</h1>"; print "<h2>Your program sent this error:<br><I> $msg</h2></I>"; } } 8 set_message(\&handle_errors) ; 9 die("Testing error messages from CGI script.\n"); EXPLANATION
Figure C.35. Output of error message from Example C.41.
Example C.42(Contents of the errors.log file created by carpout) carpout.pl syntax OK [Thu Feb 8 18:27:48 2001] C:\httpd\CGI-BIN\carpout.pl: Testing err rom CGI script. [Thu Feb 8 18:30:01 2001] C:\httpd\CGI-BIN\carpout.pl: <h1>Testing es from CGI script. [Thu Feb 8 18:55:53 2001] C:\httpd\CGI-BIN\carpout.pl: Undefined s in::set_message called at C:\httpd\CGI-BIN\carpout.pl line 11. [Thu Feb 8 18:55:53 2001] C:\httpd\CGI-BIN\carpout.pl: BEGIN faile n aborted at C:\httpd\CGI-BIN\carpout.pl line 12. [Thu Feb 8 18:56:49 2001] carpout.pl: Undefined subroutine &main:: alled at carpout.pl line 11. [Thu Feb 8 18:56:49 2001] carpout.pl: BEGIN failed--compilation ab out.pl line 12. CookiesThe HTTP protocol, by design, is stateless in order to keep the connections brief. After a transaction is completed, the connection is lost and the browser and server have no recollection of what transpired from one session to the next. But now that the Internet is used as a huge shopping center, it is often necessary to keep track of users and what they have purchased, their preferences, registration information, etc. Netscape introduced cookies in order to establish a persistent state; that is, keep information around that would normally be lost at the end of a transaction. Cookies offer a way to keep track of visitors and their preferences after they have visited a site. The cookie is a piece of data that is sent by the server from your CGI script to the visitor's browser where it is stored in a file (often called cookie.txt or just cookie ) for as long as you specify. It is a string assigned to an HTTP header that gets entered into the memory of the browser (client) and then stored in a file on the hard drive. The browser maintains a list of cookies on disk that belong to a particular Web server and returns them back to the Web server via the HTTP header during subsequent interactions. When the server gets the cookie it assigns the cookie values (name/value pairs) to the HTTP_COOKIE environment variable. The cookie, then, is passed back and forth between the browser and the server. The CGI program can set the cookie in a cookie response header ( Set-Cookie ) and retrieve values from the cookie from the environment variable, HTTP_COOKIE . By default, the cookie is short-term and expires when the current browser session terminates, but it can be made persistent by setting an expiration date to some later time, after which it will be discarded. The path decides where the cookie is valid for a particular server. If not set, it defaults to the location of the script that set the cookie. The path it refers to is the server's path, where the server's root is / . The domain name is the domain where the cookie is valid; that is, the current domain as in 127.0.0.1 or www.ellieq.com . Cookies are set in the HTTP cookie header as follows: Set-Cookie: Name=Value; expires=Date; path=Path; domain=Domainname; secure Example C.43#!/bin/perl # A simple CGI script to demonstrate setting and retrieving a cookie. # Run the program twice: the first time to set the cookie on the # client side, and second to retrieve the cookie from the browser # and get its value from the environment variable, # $ENV{HTTP_COOKIE, coming from the server. 1 my $name = "Ellie"; 2 my $expiration_date = "Friday, 17-Feb-01 00:00:00: GMT"; 3 my $path = "/cgi-bin"; 4 print " Set-Cookie: shopper=$name, expires=$expiration_date, path=$path\n"; print "Content-type: text/html\n\n"; 5 print <<EOF; <html><head><Title>Cookie Test</Title></Head> <body> <h1>Chocolate chip cookie!!</h1> <h2>Got milk?</h2> <hr> <p> What's in the HTTP_COOKIE environment variable? <br> 6 $ENV{HTTP_COOKIE} <p> <hr> </body></html> EOF EXPLANATION
Figure C.36. The HTTP_Cookie environment variable.
Table C.17. Cookie values.
The values of the cookie are stored in the HTTP_COOKIE environment variable. Netscape limits the number of cookies to 300. CGI .pm makes it easy to use cookies. See the following Example C.44. Example C.44#!/usr/bin/perl 1 use CGI; 2 $query = new CGI; 3 if ( $query->param && $query->param('color') ne ""){ 4 $color=$query->param('color') ; # Did the user pick a color } 5 elsif ( $query->cookie('preference')){ # Is there a cookie # already? 6 $color=$query->cookie('preference'); # Then go get it! } else{ 7 $color='yellow'; } # Set a default background color if # a cookie doesn't exist, and the user didn't # select a preference 8 $cookie=$query->cookie (-name=>'preference', -value=>"$color", # Set the cookie values -expires=>'+30d', ); 9 print $query->header(-cookie=>$cookie); # Setting the HTTP cookie header 10 print $query-> start_html (-title=>"Using Cookies", -bgcolor=>"$color", ); print $query->h2("Example: Making Cookies"); &print_prompt($query); & do_work($query) if ($query->param); print $query->end_html; 11 sub print_prompt{ my($query) = @_; print $query->startform; print "What is your name? "; print $query->textfield( -name=>'name', -size=>30); # A simple text field print "<BR>"; print "What is your occupation? "; print $query->textfield(-name=>'occupation', # Giving values -default=>'Retired', # to text field -size=>30, -maxlength=>120 ); print "<BR>"; print "What is your favorite color? "; print $query->textfield(-name=>'color'); # Giving values print $query->br(); print $query->submit('action', 'Enter'); print $query->reset(); print $query->endform; print $query->hr(); } 12 sub do_work{ my ($query) = @_; my (@values, $key); print "<H2>Here are the settings</H2>"; 13 foreach $key ($query->param ){ print "$key: \n"; @values=$query->param($key); print join(", ",@values), "<BR>"; } } EXPLANATION
Example C.45(What the Cookie HTTP header looks like) Set-Cookie: preference=yellow; path=/form1CGI.cgi; expires=Sun, 17-Sep-2000 09:46:26 GMT Figure C.37. The default background color was set to yellow.
Figure C.38. The user's preference, lightblue , is stored in a cookie.
C.9.6 HTTP Header MethodsA cookie is assigned to an HTTP header as shown in the previous example. Table C.18 lists other methods that can be used to create and retrieve information from HTTP headers. Table C.18. HTTP header methods.
Example C.46#!/usr/bin/perl use CGI qw(:standard); 1 print header; 2 print start_html(-title=>'Using header Methods'), h1("Let's find out about this session!"), p, 3 h4 "Your server is called ", server_name(), p, 4 "Your server port number is ", server_port(), p, 5 "This script name is: ", script_name(), p, 6 "Your browser is ", user_agent() , "and it's out of date!", p, 7 "The query string looks like this: ", query_string() , p, 8 "Where am I? Your URL is: \n", url() , p, 9 "Cookies set: ", raw_cookie(); 10 print end_html; Figure C.39. Output from Example C.46.
|