C.9 The CGI .pm Module


C.9 The CGI .pm Module

C.9.1 Introduction

The 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.

[6] Stein, L., Official Guide to Programming with CGI.pm, The Standard for Building Web Scripts, Wiley Computer Publishing, 1998.

C.9.2 Advantages

  1. CGI.pm allows you to keep a fillout form (HTML) and the script that parses it, all in one file under the cgi-bin directory. In this way your HTML file (that holds the form) and your CGI script (that reads, parses, and handles the form data) are not so far apart. [7]

    [7] Ibid.

  2. After the user has filled out a form, the results appear on the same page; in other words, the user doesn't have to backpage to see what was on the form and the fillout form does not lose data, it maintains its state. Data that doesn't disappear is called "sticky." To override stickiness, see "The override Argument" on page 690.

  3. All the reading and parsing of form data is handled by the module.

  4. Methods are used to replace HTML tags for creating text boxes, radio buttons , menus , etc. to create the form, as well as for assigning standard tags such as headers, titles, paragraph breaks, horizontal rule lines, breaks, etc.

  5. To see what HTML tags are produced by the CGI.pm module, from the View menu, select Source (in Internet Explorer) after the form has been displayed.

  6. Accepting uploaded files and managing cookies is easier with the CGI.pm module.

C.9.3 Two Styles of Programming with CGI .pm

The Object-Oriented Style

Using 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.29
 1   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.

graphics/ap03fig20.jpg

Function-Oriented Style

The 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]

[8] A default object called $CGI::Q is created, which can be accessed directly if needed.

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.

graphics/ap03fig21.jpg

C.9.4 How Input from Forms Is Processed

A 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 Form

Methods 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:

  • Named arguments ” passed as key/value pairs. Argument names are preceded by a leading dash and are case insensitive.

    Example C.31
     (Named Arguments) 1   print popup_menu(-name=>'place',                      -values=>['Hawaii','Europe','Mexico', 'Japan' ],                      -default=>'Hawaii',                     ); 2   print popup_menu(-name=>'place',                      -values=> \@countries,                      -default=>'Hawaii',                     ); 

    EXPLANATION

    1. The arguments being passed to the popup_menu method are called named parameters or argument lists . The argument names in this examples are -name, -values , and -default . These arguments are always preceded by a leading dash and are case insensitive. If the argument name might conflict with some built-in Perl function or reserved word, quote the argument. Note that the arguments are passed to the method as a set of key/value pairs. The -values key has a corresponding value consisting of an anonymous array of countries.

    2. This is exactly like the previous example, except that the value for the -values key is a reference to an array of countries. Somewhere else in the program, the array @ countries was created and given values.

  • Positional arguments ” passed as strings, they represent a value. They are used with simple HTML tags. For example, CGI .pm provides the h1() method to produce the HTML tags, <H1> and </H1> . The argument for h1() is the string of text that is normally inserted between the tags. The method is called as follows :

     
     print  h1("This is a positional argument"); 

    which translates to

     
     <H1>This is a positional argument</H1> 

    If using HTML attributes, [9] and the first argument is a reference to an anonymous hash, the attribute and its values are added after the leading tag into the list. For example:

    [9] Attributes do not require a leading dash.

     
     print h1({-align=>CENTER}, "This heading is centered"); 

    translates to

     
     <H1 ALIGN="CENTER">This heading is centered</H1> 

    If the arguments are a reference to an anonymous list, each item in the list will be properly distributed within the tag. For example:

     
     print li( ['apples', 'pears', 'peaches'] ); 

    translates to three bulleted list items:

     
     <LI>apples</LI> <LI>pears</LI> <LI>peaches</LI> 

    whereas

     
     print li( 'apples', 'pears', 'peaches' ); 

    translates to one bulleted list item:

     
     <LI>apples pears peaches</LI> 
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

  1. The function-oriented style of the CGI .pm module is used. The START_HTML method generates the header information and starts the body of the HTML document.

  2. The p() (paragraph method) generates a paragraph tag that takes no arguments. It is a start tag only.

  3. The quoted list of comma-separated arguments produces a single string argument. The paragraph's text is displayed as one line on the brower: red green yellow. It consists of a start tag, the arguments as a single string, and an end tag.

  4. The string is also displayed as a single string. It consists of a start tag, the string, and and end tag.

  5. The string is a centered paragraph. This paragraph tag consists of a start tag, attributes, arguments, and an end tag.

  6. This paragraph tag displays each word, left-justified, on a line by itself. It consists of a start tag, with the attributes for left alignment distributed across each of the listed arguments. The arguments are listed as a reference to an anonymous array.

To avoid conflicts and warnings ( -w switch), enclose all arguments in quotes.

Table C.14. HTML methods.

Method

What it Does

Attributes

a()

Anchor tag

<A>

-href, -name, -onClick, -onMouseOver, -target

applet() (:html3 group )

Embedding applets

<APPLET>

-align, -alt, -code, - codebase , -height, -hspace, -name, -vspace, -width

b()

Bold text

<B>

 

basefont() (:html3)

Set size of base font

<FONT>

-size (sizes 1 “7)

big (:netscape group)

Increase text size

<BIG>

 

blink (:netscape group)

Creates blinking text

<BLINK>

 

br()

Creates a line break

<BR>

 

button()

Creates a push button to start a JavaScript event handler when pressed

-name, -onClick, -value, -label

caption (:html3)

Inserts a caption above a table

<CAPTION>

-align, -valign

center() (:netscape group)

Center text

<CENTER>

Doesn't seem to work Use the <CENTER> tag.

cite()

Creates text in a proportional italic font

<CITE>

 

checkbox()

Creates a single named checkbox and label

-checked, -selected, -on, -label, -name, -onClick, -override, -force, -value

checkbox_group()

Creates a set of checkboxes linked by one name

- columns , -cols, -colheaders, -default, -defaults, -labels, -linebreak, -name, -nolabels, -onClick, -override, -force, -rows, -rowheaders, -value, -values

code()

Creates text in a monospace font

<CODE>

 

dd()

Definition item of definition list <DD>

 

defaults()

Creates a fillout button for submitting a form as though for the first time; clears the old parameter list

 

dl()

Creates a definition list

<DL> ; see dd()

-compact

dt()

Term part of definition list

<DT>

 

em()

Emphatic (italic) text

 

end_form(), endform()

Terminate a form

</FORM>

 

end_html()

Ends an HTML document

</BODY></HTML>

 

font() (:netscape group)

Changes font

- color , -face, -size

frame() (:netscape group)

Defines a frame

-marginheight, -marginwidth, -name, -noresize, -scrolling, -src

frameset() (:netscape group)

Creates a frameset <FRAMESET>

-cols, -rows

h1()...h6()

Creates heading levels 1 “6 <H1>, <H2> ... <H6>

 

hidden()

Creates a hidden, invisible text field, uneditable by the user

 

hr()

Creates a horizontal rule

<HR>

-align, -noshade, -size, -width

i()

Creates italic text

<I>

 

img()

Creates an inline image

<IMG>

-align, -alt, -border, -height, -width, -hspace, -ismap, -src, -lowsrc, -vrspace, -usemap

image_button()

Produces an inline image that doubles as a form submission button

-align, -alt.-height, -name, -src, -width

kbd()

Creates text with keyboard style

 

li()

Creates list item for an ordered or unordered list

-type, -value

ol()

Start an ordered list

-compact, -start, -type

p()

Creates a paragraph

<P>

-align, -class

password_field()

Creates a password field; text entered will be stars

 

popup_menu()

Creates a pop-up menu

<SELECT><OPTION>

-default, -labels, -name, -onBlur, -onChange, -onFocus, -override, -force, -value, -values

pre()

Creates preformatted typewriter text for maintaining line breaks, etc.

<PRE>

 

radio_group()

Creates a set of radio buttons all linked by one name

-columns, -cols, -colheaders, -default, -labels, -linebreak, -name, -nolabels, -onClick, -override, -force, -rows, -rowheaders, -value, -values

reset()

Creates form's Reset button

 

scrolling_list()

Controls a scrolling list box form element

-default, -defaults, -labels, -multiple, -name, -onBlur, -onChange, -onFocus, -override, -force, -size, -value, -values

Select()

Creates a select tag; Note the uppercase "S" to avoid conflict with Perl's built-in select function.

<SELECT>

 

small() (:netscape group)

Reduce size of text

 

start_form(),startform()

Starts an HTML form

<FORM>

 

start_multipart_form(),

Just like start_form , but used when uploading files

 

strong()

Bold text

 

submit()

Creates a Submit button for a form

-name, -onClick, -value, -label

sup() (:netscape group)

Superscripted text

 

table() (:html3 group)

Creates a table

-align, bgcolor , -border, -bordercolor, -bordercolor-dark, -bordercolorlight, - cellpadding , -hspace, -vspace, -width

td() (:html3 group)

Creates a table data cell

<TD>

-align, -bgcolor, -bordercolor, -bordercolorlight,-bordercolordark, -colspan, -nowrap, -rowspan, -valign, -width

textarea()

Creates a multiline text box

-cols, -columns, -name, -onChange, -onFocus,0nBlur, -onSelect, -override, -force, -value, -default, -wrap

textfield()

Produces a one-line text entry field

-maxLength, -name, -onChange, -onFocus, -onBlur, -onSelect, -override, -force, -size, -value, -default

th() (:html3 group)

Creates a table header

<TH>

 

Tr() (:html3 group)

Defines a table row; Note the uppercase "T" to avoid conflict with Perl's tr function.

<TR>

-align,bgcolor, -bordercolor, -bordercolordark, -bordercolorlight, -valign

tt()

Typewriter font

 

ul()

Start unordered list

 
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

  1. The use directive says that the CGI .pm module is being loaded and will import the :standard set of function calls, which use a syntax new in library versions 1.21 and higher. This syntax allows you to call methods without explicitly creating an object with the new constructor method; that is, the object is created for you. The Official Guide to Programming with CGI.pm by Lincoln Stein contains a complete list of shortcuts.

  2. The header method header returns the Content-type: header . You can provide your own MIME type if you choose, otherwise it defaults to text/html .

  3. This will return a canned HTML header and the opening <BODY> tag. Parameters are optional and are in the form -title, -author , and -base . Any additional parameters, such as the Netscape unofficial BGCOLOR attribute, are added to the <BODY> tag; for example, BGCOLOR=>yellow .

  4. The img method allows you to load an image. This GIF image is stored under the document's root in a directory called Images . It is aligned to the left of the text. Note: The print function here does not terminate until line 11. All of the CGI functions are passed as a comma-separated list to the print function.

  5. This will produce a level 1 heading tag. It's a shortcut and will produce the <H1> HTML tag.

  6. This method starts a form. The defaults for the form are the ACTION attribute, assigned the URL of this script, and the METHOD attribute, assigned the POST method.

  7. The textfield method creates a text field box. The first parameter is the NAME for the field, the second parameter representing the VALUE is optional. NAME is assigned name and VALUE is assigned "".

  8. The p is a shortcut for a paragraph <P>.

  9. The popup_menu method creates a menu. The required first argument is the menu's name ( -name ). The second argument, -values, is an array of menu items. It can be either anonymous or named.

  10. The submit method creates the Submit button.

  11. This line ends the form.

  12. If the param method returns non-null, each of the values associated with the parameters will be printed.

  13. The param method returns the value associated with name ; in other words, what the user typed as input for that parameter.

Figure C.22. Output from lines 1 “11 in Example C.33 before filling out the form.

graphics/ap03fig22.jpg

Figure C.23. The completed form and result of CGI.pm processing.

graphics/ap03fig23.jpg

Checking the Form at the Command Line

If 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

  1. When running in offline mode, you can enter the key/value pairs as standard input. You need to check the form so that you get the right keys and then supply the values yourself. In this example, name=Dan, job=Father, place=Hawaii were supplied by the user. After pressing <Ctrl>-d (UNIX) or <Ctrl>-z (Windows), the input will be processed by CGI .pm .

  2. By passing an empty parameter list, you can see the HTML output as it appears without the values assigned. If using UNIX, /dev/null is the UNIX bit bucket (black hole), and reading from that directory is the same as reading from an empty file. By supplying a set of empty quotes as an argument, the effect is the same.

C.9.5 CGI .pm Form Elements

Table C.15. CGI methods.

Method

Example

What It Does

append

$query “>append(-name=>'value');

Appends values to parameter

checkbox

$query “>checkbox(-name=>'checkbox_name', -checked=>'checked', -value=>'on', -label=>'clickme');

Creates a standalone checkbox

checkbox_group

$query “>checkbox_group(-name=> 'group_name', -values=>[ list ], -default=>[ sublist ], -linebreak=>'true', -labels=>\%hash);

Creates a group of checkboxes

cookie

$query “>cookie(-name=>'sessionID', -value=>'whatever', - expires =>'+3h', - path =>'/', -domain=>'ucsc.edu', -secure=>1);

Creates a Netscape cookie

defaults

$query “>defaults;

Creates a button that resets the form to its defaults

delete

$query “>delete('param');

Deletes a parameter

delete_all

$query “>delete;

Deletes all parameters; clears $query , the object

endform

$query “>endform;

Ends the <FORM> tag

header

$query “>header(-cookie=>'cookiename');

Puts a cookie in the HTTP header

hidden

$query “>hidden(-name=>'hidden', -default=>[ list ] );

Creates a hidden-from-view text field

image_button

$query “>image_button(-name=>'button', -src=>'/source/URL', -align=>'MIDDLE');

Creates a clickable image button

import_names

$query “>import_names('namespace');

Imports variables into namespace

keywords

@keywords = $query “>keywords;

Obtains parsed keywords from the Isindex input string and returns an array

new

$query = new CGI ;

Parses input and puts it in object $query for both the GET and POST methods

 

$query = new CGI (INPUTFILE);

Reads contents of form from previously opened filehandle

param

@params = $query “>param(-name=>'name', -value=>'value');

Returns an array of parameter names passed into the script

 

$value = $query “>('arg');

Returns a value (or list of values) for the @values = $query “>('arg') parameter passed

password_field

$query “>password_field(-name=>'secret' -value=>'start', -size=>60, -maxlength=>80);

Creates a password field

popup_menu

$query “>popup_menu(-name=>'menu' -values=>@items, -defaults=>'name', -labels=>\%hash);

Creates a pop-up menu

radio_group

$query “>radio_group(-name=>'group_name', -values=>[ list ], -default=>'name', -linebreak=>'true', -labels=>\%hash);

Creates a group of radio buttons

reset

$query “>reset;

Creates the Reset button to clear a form boxes to former values

save

$query “>save(FILEHANDLE);

Saves the state of a form to a file

scrolling_list

$query “>scrolling_list(-name=>'listname', -values=>[ list ], -default=> [ sublist ], -multiple=>'true', -labels=>\%hash);

Creates a scrolling list

startform

$query “>startform(-method=> -action=>, -encoding);

Returns a <FORM> tag with optional method, action, and encoding

submit

$query “>submit(-name=>'button', -value=>'value');

Creates the Submit button for forms

textarea

 

Same as text field, but includes multiline text entry box

textfield

$query “>textfield(-name=>'field', -default=>'start', -size=>50, -maxlength=>90);

Creates a text field box

Table C.16. CGI parameter methods.

Method

What It Does

Example

delete(), Delete()

Deletes a named parameter from parameter list. Delete must be used if you are using the function-oriented style of CGI .pm.

$obj “>delete('Joe');

$obj “>delete(-name=>'Joe');

Delete('Joe');

Delete(-name=>'Joe');

delete_all(), Delete_all()

Deletes all CGI parameters.

$obj “>delete_all();

Delete_all();

import_names()

Imports all CGI parameters into a specified namespace.

 

param()

Retrieves parameters from a fillout form in key/value pairs. Can return a list or a scalar.

print $obj “>param();

@list=$obj “>param();

print param('Joe');

$name=$obj “>param(-name=>'Joe');

Methods For Generating Form Input Fields

The 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() Method

The 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

  1. The CGI .pm module is loaded. It is an object-oriented module.

  2. The CGI constructor method, called new , is called and a reference to a CGI object is returned.

  3. The HTML header information is printed; for example, Content-type: text/html .

  4. The start_html method produces the HTML tags to start HTML, the title Forms and Textfields , and the body tag.

  5. The h2 method produces an <H2> , heading level 2, tag.

  6. This user-defined print_form function is called, with a reference to the CGI object is passed as an argument.

  7. The do_work function is called with a reference to the CGI object passed as an argument. This is a user-defined function that will only be called if the param function returns true, and param returns true only if the form has been filled out.

  8. The print_form function is defined.

  9. The first argument is a reference to the CGI object.

  10. The startform method produces the HTML <FORM> tag.

  11. The textfield method produces a text box with one parameter, name . Whatever is assigned to the text box will be assigned to name .

  12. The user is asked to provide input into the text box.

  13. This textfield method is sent arguments as key/value hash pairs to further define the text field. The default will show in the box. See the output of this example in Figure C.24.

    Figure C.24. Output for text field form, Example C.35.

    graphics/ap03fig24.jpg

  14. The submit method creates a Submit button with the text Enter in the button.

  15. The reset method creates a Reset button with the default text Reset in the the button.

  16. The endform method creates the HTML </FORM> tag.

  17. This is the user's do_work function that is called after the user fills out the form and presses the Submit ( Enter ) button. It processes the information supplied in the form with the param function.

  18. The param function returns a key and a list of values associated with that key. The key is the name of the parameter for the input form and the values are what were assigned to it either by the user or in the form. For example, the key named occupation was filled in by the user as jack of all trades, whereas the action key in the Submit button was assigned Enter within the form before it was processed.

Figure C.25. Output after the form was filled out and processed, Example C.35.

graphics/ap03fig25.jpg

Figure C.26. The HTML source that was produced by CGI.pm .

graphics/ap03fig26.jpg

The checkbox() Method

The 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

  1. The startform method produces the HTML <FORM> tag.

  2. The is the simplest kind of checkbox. If the user is not married, he should click the box. The name of the checkbox is Single , the label, If not, click me is displayed next to the checkbox. If -checked is assigned 1 , the box will be checked when it is first displayed.

  3. This an example of a checkbox group where a set of related checkboxes are linked by a common name, age_group . The -values argument is assigned a reference to a list of options that will appear to the right of each of the checkboxes. If -labels were used it would contain a hash consisting of key/value pairs that would be used as the labels on each of the checkboxes. The -default argument determines which boxes will be checked when the checkboxes are first displayed. The -linebreak argument is set to a non-zero value, true, which will cause the options to be displayed as a vertical list.

  4. When the user presses the Submit button, labeled Select , the form will be processed.

  5. The Reset button clears the screen only if the user has not yet submitted the form. To override "stickiness," that is, to set the checkboxes back to original default values, set the -override argument to a non-zero value.

  6. The do_work function is called when the form is submitted. This is where all the reading and parsing of the form input is handled.

  7. Each of the parameters that came in from the form (key/value pairs) are printed.

Figure C.27. Output for checkbox form in Example C.36.

graphics/ap03fig27.jpg

Figure C.28. Output after the form was filled out and processed, Example C.36.

graphics/ap03fig28.jpg

The radio_group() and popup_menu() Methods

To 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

  1. The CGI .pm module is loaded.

  2. A radio group is created in the form by calling the CGI radio_group method with its arguments. The values of the individual radio buttons will be seen to the right of each button. The default button that will be checked when the form is first displayed is green . The -linebreak argument places the buttons in a vertical position rather than in a horizontal line across the screen.The user can select only one button.

  3. After the user has filled out the form and pressed the Submit button, the param method will return the keys and values that were sent to the CGI script.

  4. The key/value pairs are displayed.

Figure C.29. Output for radio button form, Example C.37.

graphics/ap03fig29.jpg

Figure C.30. Output after form was filled out and processed, Example C.37.

graphics/ap03fig30.jpg

Labels

Labels 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

  1. The radio_group method is called with its arguments. Only one value can be selected.

  2. The values that the params function returns will be either red, green , or yellow .

  3. The labels are what actually appear next to each radio button. The user will see stop, go , and warn in the browser, but the CGI parameters associated with those labels are red, green , and yellow , respectively. If, for example, the user clicks on the stop button, the key/value pair passed to the script will be color=>red .

  4. The default button is to have the button labeled go checked.

Figure C.31. Output for labels form after being filled out and processed, Example C.38.

graphics/ap03fig31.jpg

The popup_menu() Method

The 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.

graphics/ap03fig32.jpg

Figure C.33. Output for pop-up menu form after being filled out and processed, Example C.39.

graphics/ap03fig33.jpg

The submit() and reset() Methods

The 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 Fields
The override Argument

Note 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 Method

The 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 Handling

When 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 Methods

CGI .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

  1. The CGI .pm module is loaded.

  2. The CGI ::Carp module is also loaded. This Carp module takes two arguments: fatalsToBrowser and carpout . The first argument, fatalstobrowswer , sends Perl errors to the browser and carpout makes it all possible by redirecting the standard error from the screen to the browser and error log.

  3. A file called errors.log is opened for creation/appending. This log file will contain the error messages that will also be seen in the browser.

  4. The carpout function will send errors to the errors.log file. Here is a line from that file:

    [Thu Feb 8 18:59:04 2001] C:\httpd\ CGI -BIN\carpout.pl: Testing error messages from CGI script.

Figure C.34. Redirecting errors with carpout and fatalsToBrowser .

graphics/ap03fig34.jpg

Changing the Default Message

By 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.41
 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); 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

  1. The CGI .pm module is loaded.

  2. The CGI ::Carp module is also loaded. The Carp.pm module takes two arguments: fatalsToBrowser and carpout . The first argument, fatalsToBrowser sends Perl errors to the browser and carpout makes it all possible by redirecting the standard error from the screen to the browser and error log.

  3. A file called errors.log is opened for creation/appending. This log file will contain the error messages that will also be seen in the browser.

  4. The carpout function will send errors to the errors.log file.

  5. A user-defined subroutine called handle_errors is defined. It will produce a customized error message in the user's browser window.

  6. The first argument to handle_errors subroutine is the error message coming from a die or croak. In this example, the die message on line 9 will be be assigned to $msg , unless the die on line 3 happens first. This message will also be sent to the log file, errors.log .

  7. This error message will be sent to the browser.

  8. The set_message method is called with a reference to the user-defined subroutine handle_errors , passed as an argument. handle_errors contains the customized error message.

  9. The die function will cause the program to exit, sending its error message to the handle_errors subroutine via set_message .

Figure C.35. Output of error message from Example C.41.

graphics/ap03fig35.jpg

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. 
Cookies

The 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

  1. The variable is set for the shopper's name.

  2. The expiration date is set for when the cookie will be deleted.

  3. This is the path on the server where the cookie is valid.

  4. This is the HTTP header that is assigned the information that will be stored in the cookie file in the browser.

  5. This is the start of the here document that will contain the HTML tags to be rendered by the browser.

  6. The value of the HTTP_COOKIE environment variable displays the cookie information that was retrieved and sent back to the server from the browser in an HTTP header.

Figure C.36. The HTTP_Cookie environment variable.

graphics/ap03fig36.jpg

Table C.17. Cookie values.

Name

Name of the cookie . The term Name is the actual name of the cookie; for example, it could be preference=blue where preference is the name of the cookie and blue is the data assigned to the cookie.

Value

Data assigned to the cookie; spaces, semicolons, commas, not allowed.

Date

When the cookie will expire : s = seconds; m = minutes; h = hours; d = days; now, M = months; y = years ; Fri,15-Mar-00 12:35:33 GMT ; e.g., +30m is 30 minutes from now; -1d is yesterday ; +2M is two months from now; and now is now.

Path

Path where cookie is valid.

Domain

Domain name refers to the domain where the script is running and the cookie is valid.

Secure

Makes the cookie invalid unless a secure connection is established.

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

  1. The module is loaded into this script.

  2. The CGI module's constructor, new , is called and a reference to a CGI object is returned and assigned to $query . We will be using the object-oriented form of CGI .pm in this example.

  3. If the form was filled out and if the user selected a color, the param function will return true; in other words, if param is not a null string, the value of the selected color will be assigned to the scalar, $color .

  4. If the form has been filled out, and a cookie was sent back to the server, the value of the cookie will be retrieved and store it in the scalar, $color .

  5. If the user didn't select a color, and there was no cookie, then the default background will be set to yellow .

  6. If a cookie was set, retrieve the value of the preference from the cookie. The cookie method will extract the value of the HTTP_COOKIE environment variable.

  7. If this is the first time this script has been run, a default value of yellow will be set for the background color.

  8. Key/value pairs for the cookie are set. The cookie is set to expire after 30 days. If no expiration date is set, the cookie is only good for the current session of the browser.

  9. The header method creates the HTTP cookie.

  10. The background color for the HTML page is set by the start_html method.

  11. The method that displays the HTML form is defined.

  12. The method that parses the form after it has been filled out is defined.

  13. Each of the key/value pairs produced by the param method are displayed.

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.

graphics/ap03fig37.jpg

Figure C.38. The user's preference, lightblue , is stored in a cookie.

graphics/ap03fig38.jpg

C.9.6 HTTP Header Methods

A 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.

HTTP Header Method

What It Does

accept()

Lists MIME types or type

auth_type()

Returns authorization type for the current session

cookie()

Creates and retreives cookies

header()

Returns a valid HTTP header and MIME type

https ()

Returns information about SSL for a session

path_info()

Sets and retrieves addtional path information

path_translated()

Returns additional path information

query_string()

Returns the URL encoded query string

raw_cookie()

Returns a list of unprocessed cookies sent from the browser

redirect()

Generates an HTTP header with a redirection request to the browser to load a page at that location

referer()

Returns the URL of the page the browser displayed before starting your script

remote_addr()

Returns the IP address of the remote host, possibly a proxy server

remote_ident()

Returns remote user's login name if the identity daemon is activiated

remote_host()

Returns the DNS name of the remote host

remote_user()

Returns the account name used to authenticate a password

request_method()

Returns the HTTP method, GET, POST , or HEAD

script_name()

Returns the URL of this script relative to the server's root

self_url()

Returns the URL of the CGI script: protocol, host, port, path, additional path info , and parameter list; can be used to reinvoke the current script

server_name()

Returns the name of the Web server

server_software()

Returns the name and version of the Web server

server_port()

Returns the port number for the current session (usually 80)

url()

Returns URL of the current script without additional path information and query string

user_agent()

Returns browser information

user_name()

Returns remote user's name if it can

virtual_host()

Returns the name of the virtual host being accessed by the browser

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.

graphics/ap03fig39.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net