Book HomeWebmaster in a Nutshell, 3rd EditionSearch this book

Chapter 14. The CGI.pm Module

Contents:

HTML Tag Generation
Importing Method Groups
Maintaining State
Named Parameters
Using JavaScript Features
Debugging
CGI.pm Reference

CGI.pm is a Perl module for creating and parsing CGI forms. It is distributed with core Perl as of Perl 5.004, but you can also retrieve CGI.pm from CPAN, and you can get the latest version at any time from http://stein.cshl.org/WWW/software/CGI/. This book doesn't include a complete reference for the Perl language, but if you already use Perl for CGI, you know how essential CGI.pm can be. So we include this chapter on CGI.pm as a convenience for Perl-savvy readers.

CGI.pm is an object-oriented module that is very easy to use, as evidenced by its overwhelming popularity among all levels of Perl programmers. To give you an idea of how easy it is to use CGI.pm, let's take a scenario in which a user fills out and submits a form containing her birthday. Without CGI.pm, the script would have to translate the URL-encoded input by hand (probably using a series of regular expressions) and assign it to a variable. For example, you might try something like this:

#!/usr/bin/perl 
# cgi script without CGI.pm
$size_of_form_info = $ENV{'CONTENT_LENGTH'};
read ($STDIN, $form_info, $size_of_form_info);
# Split up each pair of key=value pairs
foreach $pair (split (/&/, $form_info)) {

    # For each pair, split into $key and $value variables
     ($key, $value) = split (/=/, $pair);
    # Get rid of the pesky %xx encodings
     $key =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
     $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
    # Use $key as index for $parameters hash, $value as value
     $parameters{$key} = $value;
}
# Print out the obligatory content-ytype line
print "Content-type: text/plain\n\n";

# Tell the user what they said
print "Your birthday is on " . $parameters{birthday} . ".\n";

Regardless of whether this code actually works, you must admit it's ugly. With CGI.pm, the script could be written:

#!/usr/bin/perl -w
# cgi script with CGI.pm

use CGI;

$query = CGI::new( );
$bday = $query->param("birthday");
print $query->header( );
print $query->p("Your birthday is $bday.");

Even for this tiny program, you can see that CGI.pm can alleviate many of the headaches associated with CGI programming.

As with any Perl module, the first thing you do is call the module with use. You then call the constructor new( ), creating a new CGI object called $query. Next, get the value of the birthday parameter from the CGI program using the param method. Note that CGI.pm does all the work of determining whether the CGI program is being called by the GET or POST methods, and it also does all the URL decoding for you. To generate output, use the header method to return the content type header, and the p method to generate a paragraph marker <P> tag.

However, this is only the tip of the iceberg as far as what CGI.pm can do for you. There are three basic areas covered by CGI.pm methods: handling CGI queries, retrieving environment variables, and creating HTML elements. Table 14-1 lists these methods. They are also covered in more detail later in this chapter.

Table 14-1. CGI.pm methods

CGI handling

append

Append to a parameter

cgi_error

Get a CGI error

cookie

Get (or set) a cookie

delete

Delete a parameter

delete_all

Delete all parameters

dump

Print all name/value pairs

header

Create HTTP header

import_names

Import variables into a namespace

keywords

Get keywords from an <ISINDEX> search

param

Get (or set) the value of parameters

param_fetch

Get the value of parameters

redirect

Create redirection header

save

Save all parameters to a file

self_url

Create self-referencing URL

url

Get URL of current script without query information

url_param

Get submitted parameters appended to URLs as extra-path information

Handling environment variables

accept

Get accept types from ACCEPT header

auth_type

Get value of AUTH_TYPE header

content_type

Get the value of the CONTENT_TYPE header

http

Get the values of specified header variables

path_info

Get value of PATH_INFO header

path_translated

Get value of PATH_TRANSLATED header

query_string

Get the query information appended to the URL following a question mark (?)

raw_cookie

Get value of HTTP_COOKIE header

referer

Get value of REFERER header

remote_addr

Get value of REMOTE_ADDR header

remote_host

Get value of REMOTE_HOST header

request_method

Get value of REQUEST_METHOD header

script_name

Get value of SCRIPT_NAME header

user_agent

Get value of USER_AGENT header

user_name

Get user name (not via headers)

HTML and form generation

autoEscape

Set whether to use automatic escaping

button

Generate a JavaScript button

checkbox

Generate a single checkbox via a <INPUT TYPE=CHECKBOX> tag

checkbox_group

Generate a group of checkboxes via multiple <INPUT TYPE=CHECKBOX> tags

defaults

Generate a <DEFAULTS> tag

end_form

Generate a </FORM> end tag

end_html

Generate an </HTML> tag

end_multipart_form

Generate a </FORM> end tag for a multipart/form-data encoding

filefield

Generate an <INPUT TYPE=FILE> tag

hidden

Generate an <INPUT TYPE=HIDDEN> tag

image_button

Generate a clickable image button via a <SELECT> tag

password_field

Generate an <INPUT TYPE=PASSWORD> tag

popup_menu

Generate a pop-up menu via <SELECT SIZE=1> and <OPTION> tags

radio_group

Generate a group of radio buttons via <INPUT TYPE=RADIO> tags

reset

Generate a <RESET> tag.

scrolling_list

Generate a scrolling list via <SELECT> and <OPTION> tags

start_form

Generate a <FORM> tag

start_html

Generate an <HTML> tag

start_multipart_form

Generate a <FORM> tag for multipart/ form-data encoding

submit

Generate a <SUBMIT> tag

textarea

Generate an <TEXTAREA> tag

textfield

Generate an <INPUT TYPE=TEXT> tag

Each of these methods is covered later in this chapter.

14.1. HTML Tag Generation

In addition to the form-generation methods, CGI.pm also includes methods for generating HTML output. The names of the HTML output methods generally follow the HTML element names (e.g., p for <P>) and take named parameters that are assumed to be valid attributes for the tag (e.g., img(src=>'camel.gif') becomes <IMG SRC="camel.gif">). We do not list the HTML generating methods here, although the HTML element reference in Chapter 13 provides you with element names and attributes that are for the most part recognized by CGI.pm. See the CGI.pm manpage for complete information, or the book Official Guide to Programming with CGI.pm by Lincoln Stein (John Wiley & Sons, 1998).



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.