Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / man / man3 / CGI.3
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "CGI 3"
.TH CGI 3 "2001-09-21" "perl v5.8.8" "Perl Programmers Reference Guide"
.SH "NAME"
CGI \- Simple Common Gateway Interface Class
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 2
\& # CGI script that creates a fill-out form
\& # and echoes back its values.
.Ve
.PP
.Vb 16
\& use CGI qw/:standard/;
\& print header,
\& start_html('A Simple Example'),
\& h1('A Simple Example'),
\& start_form,
\& "What's your name? ",textfield('name'),p,
\& "What's the combination?", p,
\& checkbox_group(-name=>'words',
\& -values=>['eenie','meenie','minie','moe'],
\& -defaults=>['eenie','minie']), p,
\& "What's your favorite color? ",
\& popup_menu(-name=>'color',
\& -values=>['red','green','blue','chartreuse']),p,
\& submit,
\& end_form,
\& hr;
.Ve
.PP
.Vb 9
\& if (param()) {
\& my $name = param('name');
\& my $keywords = join ', ',param('words');
\& my $color = param('color');
\& print "Your name is",em(escapeHTML($name)),p,
\& "The keywords are: ",em(escapeHTML($keywords)),p,
\& "Your favorite color is ",em(escapeHTML($color)),
\& hr;
\& }
.Ve
.SH "ABSTRACT"
.IX Header "ABSTRACT"
This perl library uses perl5 objects to make it easy to create Web
fill-out forms and parse their contents. This package defines \s-1CGI\s0
objects, entities that contain the values of the current query string
and other state variables. Using a \s-1CGI\s0 object's methods, you can
examine keywords and parameters passed to your script, and create
forms whose initial values are taken from the current query (thereby
preserving state information). The module provides shortcut functions
that produce boilerplate \s-1HTML\s0, reducing typing and coding errors. It
also provides functionality for some of the more advanced features of
\&\s-1CGI\s0 scripting, including support for file uploads, cookies, cascading
style sheets, server push, and frames.
.PP
\&\s-1CGI\s0.pm also provides a simple function-oriented programming style for
those who don't need its object-oriented features.
.PP
The current version of \s-1CGI\s0.pm is available at
.PP
.Vb 2
\& http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
\& ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
.Sh "\s-1PROGRAMMING\s0 \s-1STYLE\s0"
.IX Subsection "PROGRAMMING STYLE"
There are two styles of programming with \s-1CGI\s0.pm, an object-oriented
style and a function-oriented style. In the object-oriented style you
create one or more \s-1CGI\s0 objects and then use object methods to create
the various elements of the page. Each \s-1CGI\s0 object starts out with the
list of named parameters that were passed to your \s-1CGI\s0 script by the
server. You can modify the objects, save them to a file or database
and recreate them. Because each object corresponds to the \*(L"state\*(R" of
the \s-1CGI\s0 script, and because each object's parameter list is
independent of the others, this allows you to save the state of the
script and restore it later.
.PP
For example, using the object oriented style, here is how you create
a simple \*(L"Hello World\*(R" \s-1HTML\s0 page:
.PP
.Vb 7
\& #!/usr/local/bin/perl -w
\& use CGI; # load CGI routines
\& $q = new CGI; # create new CGI object
\& print $q->header, # create the HTTP header
\& $q->start_html('hello world'), # start the HTML
\& $q->h1('hello world'), # level 1 header
\& $q->end_html; # end the HTML
.Ve
.PP
In the function-oriented style, there is one default \s-1CGI\s0 object that
you rarely deal with directly. Instead you just call functions to
retrieve \s-1CGI\s0 parameters, create \s-1HTML\s0 tags, manage cookies, and so
on. This provides you with a cleaner programming interface, but
limits you to using one \s-1CGI\s0 object at a time. The following example
prints the same page, but uses the function-oriented interface.
The main differences are that we now need to import a set of functions
into our name space (usually the \*(L"standard\*(R" functions), and we don't
need to create the \s-1CGI\s0 object.
.PP
.Vb 6
\& #!/usr/local/bin/perl
\& use CGI qw/:standard/; # load standard CGI routines
\& print header, # create the HTTP header
\& start_html('hello world'), # start the HTML
\& h1('hello world'), # level 1 header
\& end_html; # end the HTML
.Ve
.PP
The examples in this document mainly use the object-oriented style.
See \s-1HOW\s0 \s-1TO\s0 \s-1IMPORT\s0 \s-1FUNCTIONS\s0 for important information on
function-oriented programming in \s-1CGI\s0.pm
.Sh "\s-1CALLING\s0 \s-1CGI\s0.PM \s-1ROUTINES\s0"
.IX Subsection "CALLING CGI.PM ROUTINES"
Most \s-1CGI\s0.pm routines accept several arguments, sometimes as many as 20
optional ones! To simplify this interface, all routines use a named
argument calling style that looks like this:
.PP
.Vb 1
\& print $q->header(-type=>'image/gif',-expires=>'+3d');
.Ve
.PP
Each argument name is preceded by a dash. Neither case nor order
matters in the argument list. \-type, \-Type, and \-TYPE are all
acceptable. In fact, only the first argument needs to begin with a
dash. If a dash is present in the first argument, \s-1CGI\s0.pm assumes
dashes for the subsequent ones.
.PP
Several routines are commonly called with just one argument. In the
case of these routines you can provide the single argument without an
argument name. \fIheader()\fR happens to be one of these routines. In this
case, the single argument is the document type.
.PP
.Vb 1
\& print $q->header('text/html');
.Ve
.PP
Other such routines are documented below.
.PP
Sometimes named arguments expect a scalar, sometimes a reference to an
array, and sometimes a reference to a hash. Often, you can pass any
type of argument and the routine will do whatever is most appropriate.
For example, the \fIparam()\fR routine is used to set a \s-1CGI\s0 parameter to a
single or a multi-valued value. The two cases are shown below:
.PP
.Vb 2
\& $q->param(-name=>'veggie',-value=>'tomato');
\& $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
.Ve
.PP
A large number of routines in \s-1CGI\s0.pm actually aren't specifically
defined in the module, but are generated automatically as needed.
These are the \*(L"\s-1HTML\s0 shortcuts,\*(R" routines that generate \s-1HTML\s0 tags for
use in dynamically-generated pages. \s-1HTML\s0 tags have both attributes
(the attribute=\*(L"value\*(R" pairs within the tag itself) and contents (the
part between the opening and closing pairs.) To distinguish between
attributes and contents, \s-1CGI\s0.pm uses the convention of passing \s-1HTML\s0
attributes as a hash reference as the first argument, and the
contents, if any, as any subsequent arguments. It works out like
this:
.PP
.Vb 6
\& Code Generated HTML
\& ---- --------------
\& h1() <h1>
\& h1('some','contents'); <h1>some contents</h1>
\& h1({-align=>left}); <h1 align="LEFT">
\& h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
.Ve
.PP
\&\s-1HTML\s0 tags are described in more detail later.
.PP
Many newcomers to \s-1CGI\s0.pm are puzzled by the difference between the
calling conventions for the \s-1HTML\s0 shortcuts, which require curly braces
around the \s-1HTML\s0 tag attributes, and the calling conventions for other
routines, which manage to generate attributes without the curly
brackets. Don't be confused. As a convenience the curly braces are
optional in all but the \s-1HTML\s0 shortcuts. If you like, you can use
curly braces when calling any routine that takes named arguments. For
example:
.PP
.Vb 1
\& print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
.Ve
.PP
If you use the \fB\-w\fR switch, you will be warned that some \s-1CGI\s0.pm argument
names conflict with built-in Perl functions. The most frequent of
these is the \-values argument, used to create multi-valued menus,
radio button clusters and the like. To get around this warning, you
have several choices:
.IP "1." 4
Use another name for the argument, if one is available.
For example, \-value is an alias for \-values.
.IP "2." 4
Change the capitalization, e.g. \-Values
.IP "3." 4
Put quotes around the argument name, e.g. '\-values'
.PP
Many routines will do something useful with a named argument that it
doesn't recognize. For example, you can produce non-standard \s-1HTTP\s0
header fields by providing them as named arguments:
.PP
.Vb 4
\& print $q->header(-type => 'text/html',
\& -cost => 'Three smackers',
\& -annoyance_level => 'high',
\& -complaints_to => 'bit bucket');
.Ve
.PP
This will produce the following nonstandard \s-1HTTP\s0 header:
.PP
.Vb 5
\& HTTP/1.0 200 OK
\& Cost: Three smackers
\& Annoyance-level: high
\& Complaints-to: bit bucket
\& Content-type: text/html
.Ve
.PP
Notice the way that underscores are translated automatically into
hyphens. HTML-generating routines perform a different type of
translation.
.PP
This feature allows you to keep up with the rapidly changing \s-1HTTP\s0 and
\&\s-1HTML\s0 \*(L"standards\*(R".
.Sh "\s-1CREATING\s0 A \s-1NEW\s0 \s-1QUERY\s0 \s-1OBJECT\s0 (\s-1OBJECT\-ORIENTED\s0 \s-1STYLE\s0):"
.IX Subsection "CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):"
.Vb 1
\& $query = new CGI;
.Ve
.PP
This will parse the input (from both \s-1POST\s0 and \s-1GET\s0 methods) and store
it into a perl5 object called \f(CW$query\fR.
.Sh "\s-1CREATING\s0 A \s-1NEW\s0 \s-1QUERY\s0 \s-1OBJECT\s0 \s-1FROM\s0 \s-1AN\s0 \s-1INPUT\s0 \s-1FILE\s0"
.IX Subsection "CREATING A NEW QUERY OBJECT FROM AN INPUT FILE"
.Vb 1
\& $query = new CGI(INPUTFILE);
.Ve
.PP
If you provide a file handle to the \fInew()\fR method, it will read
parameters from the file (or \s-1STDIN\s0, or whatever). The file can be in
any of the forms describing below under debugging (i.e. a series of
newline delimited TAG=VALUE pairs will work). Conveniently, this type
of file is created by the \fIsave()\fR method (see below). Multiple records
can be saved and restored.
.PP
Perl purists will be pleased to know that this syntax accepts
references to file handles, or even references to filehandle globs,
which is the \*(L"official\*(R" way to pass a filehandle:
.PP
.Vb 1
\& $query = new CGI(\e*STDIN);
.Ve
.PP
You can also initialize the \s-1CGI\s0 object with a FileHandle or IO::File
object.
.PP
If you are using the function-oriented interface and want to
initialize \s-1CGI\s0 state from a file handle, the way to do this is with
\&\fB\f(BIrestore_parameters()\fB\fR. This will (re)initialize the
default \s-1CGI\s0 object from the indicated file handle.
.PP
.Vb 3
\& open (IN,"test.in") || die;
\& restore_parameters(IN);
\& close IN;
.Ve
.PP
You can also initialize the query object from an associative array
reference:
.PP
.Vb 4
\& $query = new CGI( {'dinosaur'=>'barney',
\& 'song'=>'I love you',
\& 'friends'=>[qw/Jessica George Nancy/]}
\& );
.Ve
.PP
or from a properly formatted, URL-escaped query string:
.PP
.Vb 1
\& $query = new CGI('dinosaur=barney&color=purple');
.Ve
.PP
or from a previously existing \s-1CGI\s0 object (currently this clones the
parameter list, but none of the other object-specific fields, such as
autoescaping):
.PP
.Vb 2
\& $old_query = new CGI;
\& $new_query = new CGI($old_query);
.Ve
.PP
To create an empty query, initialize it from an empty string or hash:
.PP
.Vb 1
\& $empty_query = new CGI("");
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& $empty_query = new CGI({});
.Ve
.Sh "\s-1FETCHING\s0 A \s-1LIST\s0 \s-1OF\s0 \s-1KEYWORDS\s0 \s-1FROM\s0 \s-1THE\s0 \s-1QUERY:\s0"
.IX Subsection "FETCHING A LIST OF KEYWORDS FROM THE QUERY:"
.Vb 1
\& @keywords = $query->keywords
.Ve
.PP
If the script was invoked as the result of an <\s-1ISINDEX\s0> search, the
parsed keywords can be obtained as an array using the \fIkeywords()\fR method.
.Sh "\s-1FETCHING\s0 \s-1THE\s0 \s-1NAMES\s0 \s-1OF\s0 \s-1ALL\s0 \s-1THE\s0 \s-1PARAMETERS\s0 \s-1PASSED\s0 \s-1TO\s0 \s-1YOUR\s0 \s-1SCRIPT:\s0"
.IX Subsection "FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:"
.Vb 1
\& @names = $query->param
.Ve
.PP
If the script was invoked with a parameter list
(e.g. \*(L"name1=value1&name2=value2&name3=value3\*(R"), the \fIparam()\fR method
will return the parameter names as a list. If the script was invoked
as an <\s-1ISINDEX\s0> script and contains a string without ampersands
(e.g. \*(L"value1+value2+value3\*(R") , there will be a single parameter named
\&\*(L"keywords\*(R" containing the \*(L"+\*(R"\-delimited keywords.
.PP
\&\s-1NOTE:\s0 As of version 1.5, the array of parameter names returned will
be in the same order as they were submitted by the browser.
Usually this order is the same as the order in which the
parameters are defined in the form (however, this isn't part
of the spec, and so isn't guaranteed).
.Sh "\s-1FETCHING\s0 \s-1THE\s0 \s-1VALUE\s0 \s-1OR\s0 \s-1VALUES\s0 \s-1OF\s0 A \s-1SINGLE\s0 \s-1NAMED\s0 \s-1PARAMETER:\s0"
.IX Subsection "FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:"
.Vb 1
\& @values = $query->param('foo');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& $value = $query->param('foo');
.Ve
.PP
Pass the \fIparam()\fR method a single argument to fetch the value of the
named parameter. If the parameter is multivalued (e.g. from multiple
selections in a scrolling list), you can ask to receive an array. Otherwise
the method will return a single value.
.PP
If a value is not given in the query string, as in the queries
\&\*(L"name1=&name2=\*(R" or \*(L"name1&name2\*(R", it will be returned as an empty
string. This feature is new in 2.63.
.PP
If the parameter does not exist at all, then \fIparam()\fR will return undef
in a scalar context, and the empty list in a list context.
.Sh "\s-1SETTING\s0 \s-1THE\s0 \s-1VALUE\s0(S) \s-1OF\s0 A \s-1NAMED\s0 \s-1PARAMETER:\s0"
.IX Subsection "SETTING THE VALUE(S) OF A NAMED PARAMETER:"
.Vb 1
\& $query->param('foo','an','array','of','values');
.Ve
.PP
This sets the value for the named parameter 'foo' to an array of
values. This is one way to change the value of a field \s-1AFTER\s0
the script has been invoked once before. (Another way is with
the \-override parameter accepted by all methods that generate
form elements.)
.PP
\&\fIparam()\fR also recognizes a named parameter style of calling described
in more detail later:
.PP
.Vb 1
\& $query->param(-name=>'foo',-values=>['an','array','of','values']);
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& $query->param(-name=>'foo',-value=>'the value');
.Ve
.Sh "\s-1APPENDING\s0 \s-1ADDITIONAL\s0 \s-1VALUES\s0 \s-1TO\s0 A \s-1NAMED\s0 \s-1PARAMETER:\s0"
.IX Subsection "APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:"
.Vb 1
\& $query->append(-name=>'foo',-values=>['yet','more','values']);
.Ve
.PP
This adds a value or list of values to the named parameter. The
values are appended to the end of the parameter if it already exists.
Otherwise the parameter is created. Note that this method only
recognizes the named argument calling syntax.
.Sh "\s-1IMPORTING\s0 \s-1ALL\s0 \s-1PARAMETERS\s0 \s-1INTO\s0 A \s-1NAMESPACE:\s0"
.IX Subsection "IMPORTING ALL PARAMETERS INTO A NAMESPACE:"
.Vb 1
\& $query->import_names('R');
.Ve
.PP
This creates a series of variables in the 'R' namespace. For example,
\&\f(CW$R::foo\fR, \f(CW@R:foo\fR. For keyword lists, a variable \f(CW@R::keywords\fR will appear.
If no namespace is given, this method will assume 'Q'.
\&\s-1WARNING:\s0 don't import anything into 'main'; this is a major security
risk!!!!
.PP
\&\s-1NOTE\s0 1: Variable names are transformed as necessary into legal Perl
variable names. All non-legal characters are transformed into
underscores. If you need to keep the original names, you should use
the \fIparam()\fR method instead to access \s-1CGI\s0 variables by name.
.PP
\&\s-1NOTE\s0 2: In older versions, this method was called \fB\f(BIimport()\fB\fR. As of version 2.20,
this name has been removed completely to avoid conflict with the built-in
Perl module \fBimport\fR operator.
.Sh "\s-1DELETING\s0 A \s-1PARAMETER\s0 \s-1COMPLETELY:\s0"
.IX Subsection "DELETING A PARAMETER COMPLETELY:"
.Vb 1
\& $query->delete('foo','bar','baz');
.Ve
.PP
This completely clears a list of parameters. It sometimes useful for
resetting parameters that you don't want passed down between script
invocations.
.PP
If you are using the function call interface, use \*(L"\fIDelete()\fR\*(R" instead
to avoid conflicts with Perl's built-in delete operator.
.Sh "\s-1DELETING\s0 \s-1ALL\s0 \s-1PARAMETERS:\s0"
.IX Subsection "DELETING ALL PARAMETERS:"
.Vb 1
\& $query->delete_all();
.Ve
.PP
This clears the \s-1CGI\s0 object completely. It might be useful to ensure
that all the defaults are taken when you create a fill-out form.
.PP
Use \fIDelete_all()\fR instead if you are using the function call interface.
.Sh "\s-1HANDLING\s0 NON-URLENCODED \s-1ARGUMENTS\s0"
.IX Subsection "HANDLING NON-URLENCODED ARGUMENTS"
If POSTed data is not of type application/x\-www\-form\-urlencoded or
multipart/form\-data, then the POSTed data will not be processed, but
instead be returned as-is in a parameter named \s-1POSTDATA\s0. To retrieve
it, use code like this:
.PP
.Vb 1
\& my $data = $query->param('POSTDATA');
.Ve
.PP
(If you don't know what the preceding means, don't worry about it. It
only affects people trying to use \s-1CGI\s0 for \s-1XML\s0 processing and other
specialized tasks.)
.Sh "\s-1DIRECT\s0 \s-1ACCESS\s0 \s-1TO\s0 \s-1THE\s0 \s-1PARAMETER\s0 \s-1LIST:\s0"
.IX Subsection "DIRECT ACCESS TO THE PARAMETER LIST:"
.Vb 2
\& $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
\& unshift @{$q->param_fetch(-name=>'address')},'George Munster';
.Ve
.PP
If you need access to the parameter list in a way that isn't covered
by the methods above, you can obtain a direct reference to it by
calling the \fB\f(BIparam_fetch()\fB\fR method with the name of the . This
will return an array reference to the named parameters, which you then
can manipulate in any way you like.
.PP
You can also use a named argument style using the \fB\-name\fR argument.
.Sh "\s-1FETCHING\s0 \s-1THE\s0 \s-1PARAMETER\s0 \s-1LIST\s0 \s-1AS\s0 A \s-1HASH:\s0"
.IX Subsection "FETCHING THE PARAMETER LIST AS A HASH:"
.Vb 4
\& $params = $q->Vars;
\& print $params->{'address'};
\& @foo = split("\e0",$params->{'foo'});
\& %params = $q->Vars;
.Ve
.PP
.Vb 2
\& use CGI ':cgi-lib';
\& $params = Vars;
.Ve
.PP
Many people want to fetch the entire parameter list as a hash in which
the keys are the names of the \s-1CGI\s0 parameters, and the values are the
parameters' values. The \fIVars()\fR method does this. Called in a scalar
context, it returns the parameter list as a tied hash reference.
Changing a key changes the value of the parameter in the underlying
\&\s-1CGI\s0 parameter list. Called in a list context, it returns the
parameter list as an ordinary hash. This allows you to read the
contents of the parameter list, but not to change it.
.PP
When using this, the thing you must watch out for are multivalued \s-1CGI\s0
parameters. Because a hash cannot distinguish between scalar and
list context, multivalued parameters will be returned as a packed
string, separated by the \*(L"\e0\*(R" (null) character. You must split this
packed string in order to get at the individual values. This is the
convention introduced long ago by Steve Brenner in his cgi\-lib.pl
module for Perl version 4.
.PP
If you wish to use \fIVars()\fR as a function, import the \fI:cgi\-lib\fR set of
function calls (also see the section on CGI-LIB compatibility).
.Sh "\s-1SAVING\s0 \s-1THE\s0 \s-1STATE\s0 \s-1OF\s0 \s-1THE\s0 \s-1SCRIPT\s0 \s-1TO\s0 A \s-1FILE:\s0"
.IX Subsection "SAVING THE STATE OF THE SCRIPT TO A FILE:"
.Vb 1
\& $query->save(\e*FILEHANDLE)
.Ve
.PP
This will write the current state of the form to the provided
filehandle. You can read it back in by providing a filehandle
to the \fInew()\fR method. Note that the filehandle can be a file, a pipe,
or whatever!
.PP
The format of the saved file is:
.PP
.Vb 5
\& NAME1=VALUE1
\& NAME1=VALUE1'
\& NAME2=VALUE2
\& NAME3=VALUE3
\& =
.Ve
.PP
Both name and value are \s-1URL\s0 escaped. Multi-valued \s-1CGI\s0 parameters are
represented as repeated names. A session record is delimited by a
single = symbol. You can write out multiple records and read them
back in with several calls to \fBnew\fR. You can do this across several
sessions by opening the file in append mode, allowing you to create
primitive guest books, or to keep a history of users' queries. Here's
a short example of creating multiple session records:
.PP
.Vb 1
\& use CGI;
.Ve
.PP
.Vb 8
\& open (OUT,">>test.out") || die;
\& $records = 5;
\& foreach (0..$records) {
\& my $q = new CGI;
\& $q->param(-name=>'counter',-value=>$_);
\& $q->save(\e*OUT);
\& }
\& close OUT;
.Ve
.PP
.Vb 6
\& # reopen for reading
\& open (IN,"test.out") || die;
\& while (!eof(IN)) {
\& my $q = new CGI(\e*IN);
\& print $q->param('counter'),"\en";
\& }
.Ve
.PP
The file format used for save/restore is identical to that used by the
Whitehead Genome Center's data exchange format \*(L"Boulderio\*(R", and can be
manipulated and even databased using Boulderio utilities. See
.PP
.Vb 1
\& http://stein.cshl.org/boulder/
.Ve
.PP
for further details.
.PP
If you wish to use this method from the function-oriented (non\-OO)
interface, the exported name for this method is \fB\f(BIsave_parameters()\fB\fR.
.Sh "\s-1RETRIEVING\s0 \s-1CGI\s0 \s-1ERRORS\s0"
.IX Subsection "RETRIEVING CGI ERRORS"
Errors can occur while processing user input, particularly when
processing uploaded files. When these errors occur, \s-1CGI\s0 will stop
processing and return an empty parameter list. You can test for
the existence and nature of errors using the \fI\fIcgi_error()\fI\fR function.
The error messages are formatted as \s-1HTTP\s0 status codes. You can either
incorporate the error text into an \s-1HTML\s0 page, or use it as the value
of the \s-1HTTP\s0 status:
.PP
.Vb 8
\& my $error = $q->cgi_error;
\& if ($error) {
\& print $q->header(-status=>$error),
\& $q->start_html('Problems'),
\& $q->h2('Request not processed'),
\& $q->strong($error);
\& exit 0;
\& }
.Ve
.PP
When using the function-oriented interface (see the next section),
errors may only occur the first time you call \fI\fIparam()\fI\fR. Be ready
for this!
.Sh "\s-1USING\s0 \s-1THE\s0 FUNCTION-ORIENTED \s-1INTERFACE\s0"
.IX Subsection "USING THE FUNCTION-ORIENTED INTERFACE"
To use the function-oriented interface, you must specify which \s-1CGI\s0.pm
routines or sets of routines to import into your script's namespace.
There is a small overhead associated with this importation, but it
isn't much.
.PP
.Vb 1
\& use CGI <list of methods>;
.Ve
.PP
The listed methods will be imported into the current package; you can
call them directly without creating a \s-1CGI\s0 object first. This example
shows how to import the \fB\f(BIparam()\fB\fR and \fB\f(BIheader()\fB\fR
methods, and then use them directly:
.PP
.Vb 3
\& use CGI 'param','header';
\& print header('text/plain');
\& $zipcode = param('zipcode');
.Ve
.PP
More frequently, you'll import common sets of functions by referring
to the groups by name. All function sets are preceded with a \*(L":\*(R"
character as in \*(L":html3\*(R" (for tags defined in the \s-1HTML\s0 3 standard).
.PP
Here is a list of the function sets you can import:
.IP "\fB:cgi\fR" 4
.IX Item ":cgi"
Import all CGI-handling methods, such as \fB\f(BIparam()\fB\fR, \fB\f(BIpath_info()\fB\fR
and the like.
.IP "\fB:form\fR" 4
.IX Item ":form"
Import all fill-out form generating methods, such as \fB\f(BItextfield()\fB\fR.
.IP "\fB:html2\fR" 4
.IX Item ":html2"
Import all methods that generate \s-1HTML\s0 2.0 standard elements.
.IP "\fB:html3\fR" 4
.IX Item ":html3"
Import all methods that generate \s-1HTML\s0 3.0 elements (such as
<table>, <super> and <sub>).
.IP "\fB:html4\fR" 4
.IX Item ":html4"
Import all methods that generate \s-1HTML\s0 4 elements (such as
<abbrev>, <acronym> and <thead>).
.IP "\fB:netscape\fR" 4
.IX Item ":netscape"
Import all methods that generate Netscape-specific \s-1HTML\s0 extensions.
.IP "\fB:html\fR" 4
.IX Item ":html"
Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
\&'netscape')...
.IP "\fB:standard\fR" 4
.IX Item ":standard"
Import \*(L"standard\*(R" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
.IP "\fB:all\fR" 4
.IX Item ":all"
Import all the available methods. For the full list, see the \s-1CGI\s0.pm
code, where the variable \f(CW%EXPORT_TAGS\fR is defined.
.PP
If you import a function name that is not part of \s-1CGI\s0.pm, the module
will treat it as a new \s-1HTML\s0 tag and generate the appropriate
subroutine. You can then use it like any other \s-1HTML\s0 tag. This is to
provide for the rapidly-evolving \s-1HTML\s0 \*(L"standard.\*(R" For example, say
Microsoft comes out with a new tag called <gradient> (which causes the
user's desktop to be flooded with a rotating gradient fill until his
machine reboots). You don't need to wait for a new version of \s-1CGI\s0.pm
to start using it immediately:
.PP
.Vb 2
\& use CGI qw/:standard :html3 gradient/;
\& print gradient({-start=>'red',-end=>'blue'});
.Ve
.PP
Note that in the interests of execution speed \s-1CGI\s0.pm does \fBnot\fR use
the standard Exporter syntax for specifying load symbols. This may
change in the future.
.PP
If you import any of the state-maintaining \s-1CGI\s0 or form-generating
methods, a default \s-1CGI\s0 object will be created and initialized
automatically the first time you use any of the methods that require
one to be present. This includes \fB\f(BIparam()\fB\fR, \fB\f(BItextfield()\fB\fR,
\&\fB\f(BIsubmit()\fB\fR and the like. (If you need direct access to the \s-1CGI\s0
object, you can find it in the global variable \fB$CGI::Q\fR). By
importing \s-1CGI\s0.pm methods, you can create visually elegant scripts:
.PP
.Vb 17
\& use CGI qw/:standard/;
\& print
\& header,
\& start_html('Simple Script'),
\& h1('Simple Script'),
\& start_form,
\& "What's your name? ",textfield('name'),p,
\& "What's the combination?",
\& checkbox_group(-name=>'words',
\& -values=>['eenie','meenie','minie','moe'],
\& -defaults=>['eenie','moe']),p,
\& "What's your favorite color?",
\& popup_menu(-name=>'color',
\& -values=>['red','green','blue','chartreuse']),p,
\& submit,
\& end_form,
\& hr,"\en";
.Ve
.PP
.Vb 7
\& if (param) {
\& print
\& "Your name is ",em(param('name')),p,
\& "The keywords are: ",em(join(", ",param('words'))),p,
\& "Your favorite color is ",em(param('color')),".\en";
\& }
\& print end_html;
.Ve
.Sh "\s-1PRAGMAS\s0"
.IX Subsection "PRAGMAS"
In addition to the function sets, there are a number of pragmas that
you can import. Pragmas, which are always preceded by a hyphen,
change the way that \s-1CGI\s0.pm functions in various ways. Pragmas,
function sets, and individual functions can all be imported in the
same \fIuse()\fR line. For example, the following use statement imports the
standard set of functions and enables debugging mode (pragma
\&\-debug):
.PP
.Vb 1
\& use CGI qw/:standard -debug/;
.Ve
.PP
The current list of pragmas is as follows:
.IP "\-any" 4
.IX Item "-any"
When you \fIuse \s-1CGI\s0 \-any\fR, then any method that the query object
doesn't recognize will be interpreted as a new \s-1HTML\s0 tag. This allows
you to support the next \fIad hoc\fR Netscape or Microsoft \s-1HTML\s0
extension. This lets you go wild with new and unsupported tags:
.Sp
.Vb 3
\& use CGI qw(-any);
\& $q=new CGI;
\& print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
.Ve
.Sp
Since using <cite>any</cite> causes any mistyped method name
to be interpreted as an \s-1HTML\s0 tag, use it with care or not at
all.
.IP "\-compile" 4
.IX Item "-compile"
This causes the indicated autoloaded methods to be compiled up front,
rather than deferred to later. This is useful for scripts that run
for an extended period of time under FastCGI or mod_perl, and for
those destined to be crunched by Malcom Beattie's Perl compiler. Use
it in conjunction with the methods or method families you plan to use.
.Sp
.Vb 1
\& use CGI qw(-compile :standard :html3);
.Ve
.Sp
or even
.Sp
.Vb 1
\& use CGI qw(-compile :all);
.Ve
.Sp
Note that using the \-compile pragma in this way will always have
the effect of importing the compiled functions into the current
namespace. If you want to compile without importing use the
\&\fIcompile()\fR method instead:
.Sp
.Vb 2
\& use CGI();
\& CGI->compile();
.Ve
.Sp
This is particularly useful in a mod_perl environment, in which you
might want to precompile all \s-1CGI\s0 routines in a startup script, and
then import the functions individually in each mod_perl script.
.IP "\-nosticky" 4
.IX Item "-nosticky"
By default the \s-1CGI\s0 module implements a state-preserving behavior
called \*(L"sticky\*(R" fields. The way this works is that if you are
regenerating a form, the methods that generate the form field values
will interrogate \fIparam()\fR to see if similarly-named parameters are
present in the query string. If they find a like-named parameter, they
will use it to set their default values.
.Sp
Sometimes this isn't what you want. The \fB\-nosticky\fR pragma prevents
this behavior. You can also selectively change the sticky behavior in
each element that you generate.
.IP "\-tabindex" 4
.IX Item "-tabindex"
Automatically add tab index attributes to each form field. With this
option turned off, you can still add tab indexes manually by passing a
\&\-tabindex option to each field-generating method.
.IP "\-no_undef_params" 4
.IX Item "-no_undef_params"
This keeps \s-1CGI\s0.pm from including undef params in the parameter list.
.IP "\-no_xhtml" 4
.IX Item "-no_xhtml"
By default, \s-1CGI\s0.pm versions 2.69 and higher emit \s-1XHTML\s0
(http://www.w3.org/TR/xhtml1/). The \-no_xhtml pragma disables this
feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
feature.
.Sp
If \fIstart_html()\fR's \-dtd parameter specifies an \s-1HTML\s0 2.0 or 3.2 \s-1DTD\s0,
\&\s-1XHTML\s0 will automatically be disabled without needing to use this
pragma.
.IP "\-nph" 4
.IX Item "-nph"
This makes \s-1CGI\s0.pm produce a header appropriate for an \s-1NPH\s0 (no
parsed header) script. You may need to do other things as well
to tell the server that the script is \s-1NPH\s0. See the discussion
of \s-1NPH\s0 scripts below.
.IP "\-newstyle_urls" 4
.IX Item "-newstyle_urls"
Separate the name=value pairs in \s-1CGI\s0 parameter query strings with
semicolons rather than ampersands. For example:
.Sp
.Vb 1
\& ?name=fred;age=24;favorite_color=3
.Ve
.Sp
Semicolon-delimited query strings are always accepted, but will not be
emitted by \fIself_url()\fR and \fIquery_string()\fR unless the \-newstyle_urls
pragma is specified.
.Sp
This became the default in version 2.64.
.IP "\-oldstyle_urls" 4
.IX Item "-oldstyle_urls"
Separate the name=value pairs in \s-1CGI\s0 parameter query strings with
ampersands rather than semicolons. This is no longer the default.
.IP "\-autoload" 4
.IX Item "-autoload"
This overrides the autoloader so that any function in your program
that is not recognized is referred to \s-1CGI\s0.pm for possible evaluation.
This allows you to use all the \s-1CGI\s0.pm functions without adding them to
your symbol table, which is of concern for mod_perl users who are
worried about memory consumption. \fIWarning:\fR when
\&\fI\-autoload\fR is in effect, you cannot use \*(L"poetry mode\*(R"
(functions without the parenthesis). Use \fI\fIhr()\fI\fR rather
than \fIhr\fR, or add something like \fIuse subs qw/hr p header/\fR
to the top of your script.
.IP "\-no_debug" 4
.IX Item "-no_debug"
This turns off the command-line processing features. If you want to
run a \s-1CGI\s0.pm script from the command line to produce \s-1HTML\s0, and you
don't want it to read \s-1CGI\s0 parameters from the command line or \s-1STDIN\s0,
then use this pragma:
.Sp
.Vb 1
\& use CGI qw(-no_debug :standard);
.Ve
.IP "\-debug" 4
.IX Item "-debug"
This turns on full debugging. In addition to reading \s-1CGI\s0 arguments
from the command-line processing, \s-1CGI\s0.pm will pause and try to read
arguments from \s-1STDIN\s0, producing the message \*(L"(offline mode: enter
name=value pairs on standard input)\*(R" features.
.Sp
See the section on debugging for more details.
.IP "\-private_tempfiles" 4
.IX Item "-private_tempfiles"
\&\s-1CGI\s0.pm can process uploaded file. Ordinarily it spools the uploaded
file to a temporary directory, then deletes the file when done.
However, this opens the risk of eavesdropping as described in the file
upload section. Another \s-1CGI\s0 script author could peek at this data
during the upload, even if it is confidential information. On Unix
systems, the \-private_tempfiles pragma will cause the temporary file
to be unlinked as soon as it is opened and before any data is written
into it, reducing, but not eliminating the risk of eavesdropping
(there is still a potential race condition). To make life harder for
the attacker, the program chooses tempfile names by calculating a 32
bit checksum of the incoming \s-1HTTP\s0 headers.
.Sp
To ensure that the temporary file cannot be read by other \s-1CGI\s0 scripts,
use suEXEC or a \s-1CGI\s0 wrapper program to run your script. The temporary
file is created with mode 0600 (neither world nor group readable).
.Sp
The temporary directory is selected using the following algorithm:
.Sp
.Vb 2
\& 1. if the current user (e.g. "nobody") has a directory named
\& "tmp" in its home directory, use that (Unix systems only).
.Ve
.Sp
.Vb 2
\& 2. if the environment variable TMPDIR exists, use the location
\& indicated.
.Ve
.Sp
.Vb 2
\& 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\etemp,
\& /tmp, /temp, ::Temporary Items, and \eWWW_ROOT.
.Ve
.Sp
Each of these locations is checked that it is a directory and is
writable. If not, the algorithm tries the next choice.
.Sh "\s-1SPECIAL\s0 \s-1FORMS\s0 \s-1FOR\s0 \s-1IMPORTING\s0 HTML-TAG \s-1FUNCTIONS\s0"
.IX Subsection "SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS"
Many of the methods generate \s-1HTML\s0 tags. As described below, tag
functions automatically generate both the opening and closing tags.
For example:
.PP
.Vb 1
\& print h1('Level 1 Header');
.Ve
.PP
produces
.PP
.Vb 1
\& <h1>Level 1 Header</h1>
.Ve
.PP
There will be some times when you want to produce the start and end
tags yourself. In this case, you can use the form start_\fItag_name\fR
and end_\fItag_name\fR, as in:
.PP
.Vb 1
\& print start_h1,'Level 1 Header',end_h1;
.Ve
.PP
With a few exceptions (described below), start_\fItag_name\fR and
end_\fItag_name\fR functions are not generated automatically when you
\&\fIuse \s-1CGI\s0\fR. However, you can specify the tags you want to generate
\&\fIstart/end\fR functions for by putting an asterisk in front of their
name, or, alternatively, requesting either "start_\fItag_name\fR\*(L" or
\&\*(R"end_\fItag_name\fR" in the import list.
.PP
Example:
.PP
.Vb 1
\& use CGI qw/:standard *table start_ul/;
.Ve
.PP
In this example, the following functions are generated in addition to
the standard ones:
.IP "1. \fIstart_table()\fR (generates a <table> tag)" 4
.IX Item "1. start_table() (generates a <table> tag)"
.PD 0
.IP "2. \fIend_table()\fR (generates a </table> tag)" 4
.IX Item "2. end_table() (generates a </table> tag)"
.IP "3. \fIstart_ul()\fR (generates a <ul> tag)" 4
.IX Item "3. start_ul() (generates a <ul> tag)"
.IP "4. \fIend_ul()\fR (generates a </ul> tag)" 4
.IX Item "4. end_ul() (generates a </ul> tag)"
.PD
.SH "GENERATING DYNAMIC DOCUMENTS"
.IX Header "GENERATING DYNAMIC DOCUMENTS"
Most of \s-1CGI\s0.pm's functions deal with creating documents on the fly.
Generally you will produce the \s-1HTTP\s0 header first, followed by the
document itself. \s-1CGI\s0.pm provides functions for generating \s-1HTTP\s0
headers of various types as well as for generating \s-1HTML\s0. For creating
\&\s-1GIF\s0 images, see the \s-1GD\s0.pm module.
.PP
Each of these functions produces a fragment of \s-1HTML\s0 or \s-1HTTP\s0 which you
can print out directly so that it displays in the browser window,
append to a string, or save to a file for later use.
.Sh "\s-1CREATING\s0 A \s-1STANDARD\s0 \s-1HTTP\s0 \s-1HEADER:\s0"
.IX Subsection "CREATING A STANDARD HTTP HEADER:"
Normally the first thing you will do in any \s-1CGI\s0 script is print out an
\&\s-1HTTP\s0 header. This tells the browser what type of document to expect,
and gives other optional information, such as the language, expiration
date, and whether to cache the document. The header can also be
manipulated for special purposes, such as server push and pay per view
pages.
.PP
.Vb 1
\& print header;
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print header('image/gif');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print header('text/html','204 No response');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 8
\& print header(-type=>'image/gif',
\& -nph=>1,
\& -status=>'402 Payment required',
\& -expires=>'+3d',
\& -cookie=>$cookie,
\& -charset=>'utf-7',
\& -attachment=>'foo.gif',
\& -Cost=>'$2.00');
.Ve
.PP
\&\fIheader()\fR returns the Content\-type: header. You can provide your own
\&\s-1MIME\s0 type if you choose, otherwise it defaults to text/html. An
optional second parameter specifies the status code and a human-readable
message. For example, you can specify 204, \*(L"No response\*(R" to create a
script that tells the browser to do nothing at all.
.PP
The last example shows the named argument style for passing arguments
to the \s-1CGI\s0 methods using named parameters. Recognized parameters are
\&\fB\-type\fR, \fB\-status\fR, \fB\-expires\fR, and \fB\-cookie\fR. Any other named
parameters will be stripped of their initial hyphens and turned into
header fields, allowing you to specify any \s-1HTTP\s0 header you desire.
Internal underscores will be turned into hyphens:
.PP
.Vb 1
\& print header(-Content_length=>3002);
.Ve
.PP
Most browsers will not cache the output from \s-1CGI\s0 scripts. Every time
the browser reloads the page, the script is invoked anew. You can
change this behavior with the \fB\-expires\fR parameter. When you specify
an absolute or relative expiration interval with this parameter, some
browsers and proxy servers will cache the script's output until the
indicated expiration date. The following forms are all valid for the
\&\-expires field:
.PP
.Vb 8
\& +30s 30 seconds from now
\& +10m ten minutes from now
\& +1h one hour from now
\& -1d yesterday (i.e. "ASAP!")
\& now immediately
\& +3M in three months
\& +10y in ten years time
\& Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
.Ve
.PP
The \fB\-cookie\fR parameter generates a header that tells the browser to provide
a \*(L"magic cookie\*(R" during all subsequent transactions with your script.
Netscape cookies have a special format that includes interesting attributes
such as expiration time. Use the \fIcookie()\fR method to create and retrieve
session cookies.
.PP
The \fB\-nph\fR parameter, if set to a true value, will issue the correct
headers to work with a \s-1NPH\s0 (no\-parse\-header) script. This is important
to use with certain servers that expect all their scripts to be \s-1NPH\s0.
.PP
The \fB\-charset\fR parameter can be used to control the character set
sent to the browser. If not provided, defaults to \s-1ISO\-8859\-1\s0. As a
side effect, this sets the \fIcharset()\fR method as well.
.PP
The \fB\-attachment\fR parameter can be used to turn the page into an
attachment. Instead of displaying the page, some browsers will prompt
the user to save it to disk. The value of the argument is the
suggested name for the saved file. In order for this to work, you may
have to set the \fB\-type\fR to \*(L"application/octet\-stream\*(R".
.PP
The \fB\-p3p\fR parameter will add a P3P tag to the outgoing header. The
parameter can be an arrayref or a space-delimited string of P3P tags.
For example:
.PP
.Vb 2
\& print header(-p3p=>[qw(CAO DSP LAW CURa)]);
\& print header(-p3p=>'CAO DSP LAW CURa');
.Ve
.PP
In either case, the outgoing header will be formatted as:
.PP
.Vb 1
\& P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
.Ve
.Sh "\s-1GENERATING\s0 A \s-1REDIRECTION\s0 \s-1HEADER\s0"
.IX Subsection "GENERATING A REDIRECTION HEADER"
.Vb 1
\& print redirect('http://somewhere.else/in/movie/land');
.Ve
.PP
Sometimes you don't want to produce a document yourself, but simply
redirect the browser elsewhere, perhaps choosing a \s-1URL\s0 based on the
time of day or the identity of the user.
.PP
The \fIredirect()\fR function redirects the browser to a different \s-1URL\s0. If
you use redirection like this, you should \fBnot\fR print out a header as
well.
.PP
You should always use full URLs (including the http: or ftp: part) in
redirection requests. Relative URLs will not work correctly.
.PP
You can also use named arguments:
.PP
.Vb 3
\& print redirect(-uri=>'http://somewhere.else/in/movie/land',
\& -nph=>1,
\& -status=>301);
.Ve
.PP
The \fB\-nph\fR parameter, if set to a true value, will issue the correct
headers to work with a \s-1NPH\s0 (no\-parse\-header) script. This is important
to use with certain servers, such as Microsoft \s-1IIS\s0, which
expect all their scripts to be \s-1NPH\s0.
.PP
The \fB\-status\fR parameter will set the status of the redirect. \s-1HTTP\s0
defines three different possible redirection status codes:
.PP
.Vb 3
\& 301 Moved Permanently
\& 302 Found
\& 303 See Other
.Ve
.PP
The default if not specified is 302, which means \*(L"moved temporarily.\*(R"
You may change the status to another status code if you wish. Be
advised that changing the status to anything other than 301, 302 or
303 will probably break redirection.
.Sh "\s-1CREATING\s0 \s-1THE\s0 \s-1HTML\s0 \s-1DOCUMENT\s0 \s-1HEADER\s0"
.IX Subsection "CREATING THE HTML DOCUMENT HEADER"
.Vb 8
\& print start_html(-title=>'Secrets of the Pyramids',
\& -author=>'fred@capricorn.org',
\& -base=>'true',
\& -target=>'_blank',
\& -meta=>{'keywords'=>'pharaoh secret mummy',
\& 'copyright'=>'copyright 1996 King Tut'},
\& -style=>{'src'=>'/styles/style1.css'},
\& -BGCOLOR=>'blue');
.Ve
.PP
After creating the \s-1HTTP\s0 header, most \s-1CGI\s0 scripts will start writing
out an \s-1HTML\s0 document. The \fIstart_html()\fR routine creates the top of the
page, along with a lot of optional information that controls the
page's appearance and behavior.
.PP
This method returns a canned \s-1HTML\s0 header and the opening <body> tag.
All parameters are optional. In the named parameter form, recognized
parameters are \-title, \-author, \-base, \-xbase, \-dtd, \-lang and \-target
(see below for the explanation). Any additional parameters you
provide, such as the Netscape unofficial \s-1BGCOLOR\s0 attribute, are added
to the <body> tag. Additional parameters must be proceeded by a
hyphen.
.PP
The argument \fB\-xbase\fR allows you to provide an \s-1HREF\s0 for the <base> tag
different from the current location, as in
.PP
.Vb 1
\& -xbase=>"http://home.mcom.com/"
.Ve
.PP
All relative links will be interpreted relative to this tag.
.PP
The argument \fB\-target\fR allows you to provide a default target frame
for all the links and fill-out forms on the page. \fBThis is a
non-standard \s-1HTTP\s0 feature which only works with Netscape browsers!\fR
See the Netscape documentation on frames for details of how to
manipulate this.
.PP
.Vb 1
\& -target=>"answer_window"
.Ve
.PP
All relative links will be interpreted relative to this tag.
You add arbitrary meta information to the header with the \fB\-meta\fR
argument. This argument expects a reference to an associative array
containing name/value pairs of meta information. These will be turned
into a series of header <meta> tags that look something like this:
.PP
.Vb 2
\& <meta name="keywords" content="pharaoh secret mummy">
\& <meta name="description" content="copyright 1996 King Tut">
.Ve
.PP
To create an HTTP-EQUIV type of <meta> tag, use \fB\-head\fR, described
below.
.PP
The \fB\-style\fR argument is used to incorporate cascading stylesheets
into your code. See the section on \s-1CASCADING\s0 \s-1STYLESHEETS\s0 for more
information.
.PP
The \fB\-lang\fR argument is used to incorporate a language attribute into
the <html> tag. For example:
.PP
.Vb 1
\& print $q->start_html(-lang=>'fr-CA');
.Ve
.PP
The default if not specified is \*(L"en\-US\*(R" for \s-1US\s0 English, unless the
\&\-dtd parameter specifies an \s-1HTML\s0 2.0 or 3.2 \s-1DTD\s0, in which case the
lang attribute is left off. You can force the lang attribute to left
off in other cases by passing an empty string (\-lang=>'').
.PP
The \fB\-encoding\fR argument can be used to specify the character set for
\&\s-1XHTML\s0. It defaults to iso\-8859\-1 if not specified.
.PP
The \fB\-declare_xml\fR argument, when used in conjunction with \s-1XHTML\s0,
will put a <?xml> declaration at the top of the \s-1HTML\s0 header. The sole
purpose of this declaration is to declare the character set
encoding. In the absence of \-declare_xml, the output \s-1HTML\s0 will contain
a <meta> tag that specifies the encoding, allowing the \s-1HTML\s0 to pass
most validators. The default for \-declare_xml is false.
.PP
You can place other arbitrary \s-1HTML\s0 elements to the <head> section with the
\&\fB\-head\fR tag. For example, to place the rarely-used <link> element in the
head section, use this:
.PP
.Vb 2
\& print start_html(-head=>Link({-rel=>'next',
\& -href=>'http://www.capricorn.com/s2.html'}));
.Ve
.PP
To incorporate multiple \s-1HTML\s0 elements into the <head> section, just pass an
array reference:
.PP
.Vb 7
\& print start_html(-head=>[
\& Link({-rel=>'next',
\& -href=>'http://www.capricorn.com/s2.html'}),
\& Link({-rel=>'previous',
\& -href=>'http://www.capricorn.com/s1.html'})
\& ]
\& );
.Ve
.PP
And here's how to create an HTTP-EQUIV <meta> tag:
.PP
.Vb 2
\& print start_html(-head=>meta({-http_equiv => 'Content-Type',
\& -content => 'text/html'}))
.Ve
.PP
\&\s-1JAVASCRIPTING:\s0 The \fB\-script\fR, \fB\-noScript\fR, \fB\-onLoad\fR,
\&\fB\-onMouseOver\fR, \fB\-onMouseOut\fR and \fB\-onUnload\fR parameters are used
to add Netscape JavaScript calls to your pages. \fB\-script\fR should
point to a block of text containing JavaScript function definitions.
This block will be placed within a <script> block inside the \s-1HTML\s0 (not
\&\s-1HTTP\s0) header. The block is placed in the header in order to give your
page a fighting chance of having all its JavaScript functions in place
even if the user presses the stop button before the page has loaded
completely. \s-1CGI\s0.pm attempts to format the script in such a way that
JavaScript-naive browsers will not choke on the code: unfortunately
there are some browsers, such as Chimera for Unix, that get confused
by it nevertheless.
.PP
The \fB\-onLoad\fR and \fB\-onUnload\fR parameters point to fragments of JavaScript
code to execute when the page is respectively opened and closed by the
browser. Usually these parameters are calls to functions defined in the
\&\fB\-script\fR field:
.PP
.Vb 20
\& $query = new CGI;
\& print header;
\& $JSCRIPT=<<END;
\& // Ask a silly question
\& function riddle_me_this() {
\& var r = prompt("What walks on four legs in the morning, " +
\& "two legs in the afternoon, " +
\& "and three legs in the evening?");
\& response(r);
\& }
\& // Get a silly answer
\& function response(answer) {
\& if (answer == "man")
\& alert("Right you are!");
\& else
\& alert("Wrong! Guess again.");
\& }
\& END
\& print start_html(-title=>'The Riddle of the Sphinx',
\& -script=>$JSCRIPT);
.Ve
.PP
Use the \fB\-noScript\fR parameter to pass some \s-1HTML\s0 text that will be displayed on
browsers that do not have JavaScript (or browsers where JavaScript is turned
off).
.PP
Netscape 3.0 recognizes several attributes of the <script> tag,
including \s-1LANGUAGE\s0 and \s-1SRC\s0. The latter is particularly interesting,
as it allows you to keep the JavaScript code in a file or \s-1CGI\s0 script
rather than cluttering up each page with the source. To use these
attributes pass a \s-1HASH\s0 reference in the \fB\-script\fR parameter containing
one or more of \-language, \-src, or \-code:
.PP
.Vb 4
\& print $q->start_html(-title=>'The Riddle of the Sphinx',
\& -script=>{-language=>'JAVASCRIPT',
\& -src=>'/javascript/sphinx.js'}
\& );
.Ve
.PP
.Vb 4
\& print $q->(-title=>'The Riddle of the Sphinx',
\& -script=>{-language=>'PERLSCRIPT',
\& -code=>'print "hello world!\en;"'}
\& );
.Ve
.PP
A final feature allows you to incorporate multiple <script> sections into the
header. Just pass the list of script sections as an array reference.
this allows you to specify different source files for different dialects
of JavaScript. Example:
.PP
.Vb 16
\& print $q->start_html(-title=>'The Riddle of the Sphinx',
\& -script=>[
\& { -language => 'JavaScript1.0',
\& -src => '/javascript/utilities10.js'
\& },
\& { -language => 'JavaScript1.1',
\& -src => '/javascript/utilities11.js'
\& },
\& { -language => 'JavaScript1.2',
\& -src => '/javascript/utilities12.js'
\& },
\& { -language => 'JavaScript28.2',
\& -src => '/javascript/utilities219.js'
\& }
\& ]
\& );
.Ve
.PP
If this looks a bit extreme, take my advice and stick with straight \s-1CGI\s0 scripting.
.PP
See
.PP
.Vb 1
\& http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
.Ve
.PP
for more information about JavaScript.
.PP
The old-style positional parameters are as follows:
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The title
.IP "2." 4
The author's e\-mail address (will create a <link rev=\*(L"\s-1MADE\s0\*(R"> tag if present
.IP "3." 4
A 'true' flag if you want to include a <base> tag in the header. This
helps resolve relative addresses to absolute ones when the document is moved,
but makes the document hierarchy non\-portable. Use with care!
.IP "4, 5, 6..." 4
.IX Item "4, 5, 6..."
Any other parameters you want to include in the <body> tag. This is a good
place to put Netscape extensions, such as colors and wallpaper patterns.
.Sh "\s-1ENDING\s0 \s-1THE\s0 \s-1HTML\s0 \s-1DOCUMENT:\s0"
.IX Subsection "ENDING THE HTML DOCUMENT:"
.Vb 1
\& print end_html
.Ve
.PP
This ends an \s-1HTML\s0 document by printing the </body></html> tags.
.Sh "\s-1CREATING\s0 A SELF-REFERENCING \s-1URL\s0 \s-1THAT\s0 \s-1PRESERVES\s0 \s-1STATE\s0 \s-1INFORMATION:\s0"
.IX Subsection "CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:"
.Vb 2
\& $myself = self_url;
\& print q(<a href="$myself">I'm talking to myself.</a>);
.Ve
.PP
\&\fIself_url()\fR will return a \s-1URL\s0, that, when selected, will reinvoke
this script with all its state information intact. This is most
useful when you want to jump around within the document using
internal anchors but you don't want to disrupt the current contents
of the form(s). Something like this will do the trick.
.PP
.Vb 4
\& $myself = self_url;
\& print "<a href=\e"$myself#table1\e">See table 1</a>";
\& print "<a href=\e"$myself#table2\e">See table 2</a>";
\& print "<a href=\e"$myself#yourself\e">See for yourself</a>";
.Ve
.PP
If you want more control over what's returned, using the \fB\f(BIurl()\fB\fR
method instead.
.PP
You can also retrieve the unprocessed query string with \fIquery_string()\fR:
.PP
.Vb 1
\& $the_string = query_string;
.Ve
.Sh "\s-1OBTAINING\s0 \s-1THE\s0 \s-1SCRIPT\s0'S \s-1URL\s0"
.IX Subsection "OBTAINING THE SCRIPT'S URL"
.Vb 7
\& $full_url = url();
\& $full_url = url(-full=>1); #alternative syntax
\& $relative_url = url(-relative=>1);
\& $absolute_url = url(-absolute=>1);
\& $url_with_path = url(-path_info=>1);
\& $url_with_path_and_query = url(-path_info=>1,-query=>1);
\& $netloc = url(-base => 1);
.Ve
.PP
\&\fB\f(BIurl()\fB\fR returns the script's \s-1URL\s0 in a variety of formats. Called
without any arguments, it returns the full form of the \s-1URL\s0, including
host name and port number
.PP
.Vb 1
\& http://your.host.com/path/to/script.cgi
.Ve
.PP
You can modify this format with the following named arguments:
.IP "\fB\-absolute\fR" 4
.IX Item "-absolute"
If true, produce an absolute \s-1URL\s0, e.g.
.Sp
.Vb 1
\& /path/to/script.cgi
.Ve
.IP "\fB\-relative\fR" 4
.IX Item "-relative"
Produce a relative \s-1URL\s0. This is useful if you want to reinvoke your
script with different parameters. For example:
.Sp
.Vb 1
\& script.cgi
.Ve
.IP "\fB\-full\fR" 4
.IX Item "-full"
Produce the full \s-1URL\s0, exactly as if called without any arguments.
This overrides the \-relative and \-absolute arguments.
.IP "\fB\-path\fR (\fB\-path_info\fR)" 4
.IX Item "-path (-path_info)"
Append the additional path information to the \s-1URL\s0. This can be
combined with \fB\-full\fR, \fB\-absolute\fR or \fB\-relative\fR. \fB\-path_info\fR
is provided as a synonym.
.IP "\fB\-query\fR (\fB\-query_string\fR)" 4
.IX Item "-query (-query_string)"
Append the query string to the \s-1URL\s0. This can be combined with
\&\fB\-full\fR, \fB\-absolute\fR or \fB\-relative\fR. \fB\-query_string\fR is provided
as a synonym.
.IP "\fB\-base\fR" 4
.IX Item "-base"
Generate just the protocol and net location, as in http://www.foo.com:8000
.IP "\fB\-rewrite\fR" 4
.IX Item "-rewrite"
If Apache's mod_rewrite is turned on, then the script name and path
info probably won't match the request that the user sent. Set
\&\-rewrite=>1 (default) to return URLs that match what the user sent
(the original request \s-1URI\s0). Set \-rewrite\->0 to return URLs that match
the \s-1URL\s0 after mod_rewrite's rules have run. Because the additional
path information only makes sense in the context of the rewritten \s-1URL\s0,
\&\-rewrite is set to false when you request path info in the \s-1URL\s0.
.Sh "\s-1MIXING\s0 \s-1POST\s0 \s-1AND\s0 \s-1URL\s0 \s-1PARAMETERS\s0"
.IX Subsection "MIXING POST AND URL PARAMETERS"
.Vb 1
\& $color = url_param('color');
.Ve
.PP
It is possible for a script to receive \s-1CGI\s0 parameters in the \s-1URL\s0 as
well as in the fill-out form by creating a form that POSTs to a \s-1URL\s0
containing a query string (a \*(L"?\*(R" mark followed by arguments). The
\&\fB\f(BIparam()\fB\fR method will always return the contents of the POSTed
fill-out form, ignoring the \s-1URL\s0's query string. To retrieve \s-1URL\s0
parameters, call the \fB\f(BIurl_param()\fB\fR method. Use it in the same way as
\&\fB\f(BIparam()\fB\fR. The main difference is that it allows you to read the
parameters, but not set them.
.PP
Under no circumstances will the contents of the \s-1URL\s0 query string
interfere with similarly-named \s-1CGI\s0 parameters in POSTed forms. If you
try to mix a \s-1URL\s0 query string with a form submitted with the \s-1GET\s0
method, the results will not be what you expect.
.SH "CREATING STANDARD HTML ELEMENTS:"
.IX Header "CREATING STANDARD HTML ELEMENTS:"
\&\s-1CGI\s0.pm defines general \s-1HTML\s0 shortcut methods for most, if not all of
the \s-1HTML\s0 3 and \s-1HTML\s0 4 tags. \s-1HTML\s0 shortcuts are named after a single
\&\s-1HTML\s0 element and return a fragment of \s-1HTML\s0 text that you can then
print or manipulate as you like. Each shortcut returns a fragment of
\&\s-1HTML\s0 code that you can append to a string, save to a file, or, most
commonly, print out so that it displays in the browser window.
.PP
This example shows how to use the \s-1HTML\s0 methods:
.PP
.Vb 7
\& print $q->blockquote(
\& "Many years ago on the island of",
\& $q->a({href=>"http://crete.org/"},"Crete"),
\& "there lived a Minotaur named",
\& $q->strong("Fred."),
\& ),
\& $q->hr;
.Ve
.PP
This results in the following \s-1HTML\s0 code (extra newlines have been
added for readability):
.PP
.Vb 6
\& <blockquote>
\& Many years ago on the island of
\& <a href="http://crete.org/">Crete</a> there lived
\& a minotaur named <strong>Fred.</strong>
\& </blockquote>
\& <hr>
.Ve
.PP
If you find the syntax for calling the \s-1HTML\s0 shortcuts awkward, you can
import them into your namespace and dispense with the object syntax
completely (see the next section for more details):
.PP
.Vb 8
\& use CGI ':standard';
\& print blockquote(
\& "Many years ago on the island of",
\& a({href=>"http://crete.org/"},"Crete"),
\& "there lived a minotaur named",
\& strong("Fred."),
\& ),
\& hr;
.Ve
.Sh "\s-1PROVIDING\s0 \s-1ARGUMENTS\s0 \s-1TO\s0 \s-1HTML\s0 \s-1SHORTCUTS\s0"
.IX Subsection "PROVIDING ARGUMENTS TO HTML SHORTCUTS"
The \s-1HTML\s0 methods will accept zero, one or multiple arguments. If you
provide no arguments, you get a single tag:
.PP
.Vb 1
\& print hr; # <hr>
.Ve
.PP
If you provide one or more string arguments, they are concatenated
together with spaces and placed between opening and closing tags:
.PP
.Vb 1
\& print h1("Chapter","1"); # <h1>Chapter 1</h1>"
.Ve
.PP
If the first argument is an associative array reference, then the keys
and values of the associative array become the \s-1HTML\s0 tag's attributes:
.PP
.Vb 2
\& print a({-href=>'fred.html',-target=>'_new'},
\& "Open a new frame");
.Ve
.PP
.Vb 1
\& <a href="fred.html",target="_new">Open a new frame</a>
.Ve
.PP
You may dispense with the dashes in front of the attribute names if
you prefer:
.PP
.Vb 1
\& print img {src=>'fred.gif',align=>'LEFT'};
.Ve
.PP
.Vb 1
\& <img align="LEFT" src="fred.gif">
.Ve
.PP
Sometimes an \s-1HTML\s0 tag attribute has no argument. For example, ordered
lists can be marked as \s-1COMPACT\s0. The syntax for this is an argument that
that points to an undef string:
.PP
.Vb 1
\& print ol({compact=>undef},li('one'),li('two'),li('three'));
.Ve
.PP
Prior to \s-1CGI\s0.pm version 2.41, providing an empty ('') string as an
attribute argument was the same as providing undef. However, this has
changed in order to accommodate those who want to create tags of the form
<img alt="">. The difference is shown in these two pieces of code:
.PP
.Vb 3
\& CODE RESULT
\& img({alt=>undef}) <img alt>
\& img({alt=>''}) <img alt="">
.Ve
.Sh "\s-1THE\s0 \s-1DISTRIBUTIVE\s0 \s-1PROPERTY\s0 \s-1OF\s0 \s-1HTML\s0 \s-1SHORTCUTS\s0"
.IX Subsection "THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS"
One of the cool features of the \s-1HTML\s0 shortcuts is that they are
distributive. If you give them an argument consisting of a
\&\fBreference\fR to a list, the tag will be distributed across each
element of the list. For example, here's one way to make an ordered
list:
.PP
.Vb 3
\& print ul(
\& li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
\& );
.Ve
.PP
This example will result in \s-1HTML\s0 output that looks like this:
.PP
.Vb 6
\& <ul>
\& <li type="disc">Sneezy</li>
\& <li type="disc">Doc</li>
\& <li type="disc">Sleepy</li>
\& <li type="disc">Happy</li>
\& </ul>
.Ve
.PP
This is extremely useful for creating tables. For example:
.PP
.Vb 11
\& print table({-border=>undef},
\& caption('When Should You Eat Your Vegetables?'),
\& Tr({-align=>CENTER,-valign=>TOP},
\& [
\& th(['Vegetable', 'Breakfast','Lunch','Dinner']),
\& td(['Tomatoes' , 'no', 'yes', 'yes']),
\& td(['Broccoli' , 'no', 'no', 'yes']),
\& td(['Onions' , 'yes','yes', 'yes'])
\& ]
\& )
\& );
.Ve
.Sh "\s-1HTML\s0 \s-1SHORTCUTS\s0 \s-1AND\s0 \s-1LIST\s0 \s-1INTERPOLATION\s0"
.IX Subsection "HTML SHORTCUTS AND LIST INTERPOLATION"
Consider this bit of code:
.PP
.Vb 1
\& print blockquote(em('Hi'),'mom!'));
.Ve
.PP
It will ordinarily return the string that you probably expect, namely:
.PP
.Vb 1
\& <blockquote><em>Hi</em> mom!</blockquote>
.Ve
.PP
Note the space between the element \*(L"Hi\*(R" and the element \*(L"mom!\*(R".
\&\s-1CGI\s0.pm puts the extra space there using array interpolation, which is
controlled by the magic $\*(L" variable. Sometimes this extra space is
not what you want, for example, when you are trying to align a series
of images. In this case, you can simply change the value of $\*(R" to an
empty string.
.PP
.Vb 4
\& {
\& local($") = '';
\& print blockquote(em('Hi'),'mom!'));
\& }
.Ve
.PP
I suggest you put the code in a block as shown here. Otherwise the
change to $" will affect all subsequent code until you explicitly
reset it.
.Sh "NON-STANDARD \s-1HTML\s0 \s-1SHORTCUTS\s0"
.IX Subsection "NON-STANDARD HTML SHORTCUTS"
A few \s-1HTML\s0 tags don't follow the standard pattern for various
reasons.
.PP
\&\fB\f(BIcomment()\fB\fR generates an \s-1HTML\s0 comment (<!\-\- comment \-\->). Call it
like
.PP
.Vb 1
\& print comment('here is my comment');
.Ve
.PP
Because of conflicts with built-in Perl functions, the following functions
begin with initial caps:
.PP
.Vb 6
\& Select
\& Tr
\& Link
\& Delete
\& Accept
\& Sub
.Ve
.PP
In addition, \fIstart_html()\fR, \fIend_html()\fR, \fIstart_form()\fR, \fIend_form()\fR,
\&\fIstart_multipart_form()\fR and all the fill-out form tags are special.
See their respective sections.
.Sh "\s-1AUTOESCAPING\s0 \s-1HTML\s0"
.IX Subsection "AUTOESCAPING HTML"
By default, all \s-1HTML\s0 that is emitted by the form-generating functions
is passed through a function called \fIescapeHTML()\fR:
.ie n .IP "$escaped_string = escapeHTML(""unescaped string"");" 4
.el .IP "$escaped_string = escapeHTML(``unescaped string'');" 4
.IX Item "$escaped_string = escapeHTML(unescaped string);"
Escape \s-1HTML\s0 formatting characters in a string.
.PP
Provided that you have specified a character set of \s-1ISO\-8859\-1\s0 (the
default), the standard \s-1HTML\s0 escaping rules will be used. The \*(L"<\*(R"
character becomes \*(L"&lt;\*(R", \*(L">\*(R" becomes \*(L"&gt;\*(R", \*(L"&\*(R" becomes \*(L"&amp;\*(R", and
the quote character becomes \*(L"&quot;\*(R". In addition, the hexadecimal
0x8b and 0x9b characters, which some browsers incorrectly interpret
as the left and right angle-bracket characters, are replaced by their
numeric character entities (\*(L"&#8249\*(R" and \*(L"&#8250;\*(R"). If you manually change
the charset, either by calling the \fIcharset()\fR method explicitly or by
passing a \-charset argument to \fIheader()\fR, then \fBall\fR characters will
be replaced by their numeric entities, since \s-1CGI\s0.pm has no lookup
table for all the possible encodings.
.PP
The automatic escaping does not apply to other shortcuts, such as
\&\fIh1()\fR. You should call \fIescapeHTML()\fR yourself on untrusted data in
order to protect your pages against nasty tricks that people may enter
into guestbooks, etc.. To change the character set, use \fIcharset()\fR.
To turn autoescaping off completely, use \fIautoEscape\fR\|(0):
.IP "$charset = charset([$charset]);" 4
.IX Item "$charset = charset([$charset]);"
Get or set the current character set.
.IP "$flag = autoEscape([$flag]);" 4
.IX Item "$flag = autoEscape([$flag]);"
Get or set the value of the autoescape flag.
.Sh "PRETTY-PRINTING \s-1HTML\s0"
.IX Subsection "PRETTY-PRINTING HTML"
By default, all the \s-1HTML\s0 produced by these functions comes out as one
long line without carriage returns or indentation. This is yuck, but
it does reduce the size of the documents by 10\-20%. To get
pretty-printed output, please use CGI::Pretty, a subclass
contributed by Brian Paulsen.
.SH "CREATING FILL-OUT FORMS:"
.IX Header "CREATING FILL-OUT FORMS:"
\&\fIGeneral note\fR The various form-creating methods all return strings
to the caller, containing the tag or tags that will create the requested
form element. You are responsible for actually printing out these strings.
It's set up this way so that you can place formatting tags
around the form elements.
.PP
\&\fIAnother note\fR The default values that you specify for the forms are only
used the \fBfirst\fR time the script is invoked (when there is no query
string). On subsequent invocations of the script (when there is a query
string), the former values are used even if they are blank.
.PP
If you want to change the value of a field from its previous value, you have two
choices:
.PP
(1) call the \fIparam()\fR method to set it.
.PP
(2) use the \-override (alias \-force) parameter (a new feature in version 2.15).
This forces the default value to be used, regardless of the previous value:
.PP
.Vb 5
\& print textfield(-name=>'field_name',
\& -default=>'starting value',
\& -override=>1,
\& -size=>50,
\& -maxlength=>80);
.Ve
.PP
\&\fIYet another note\fR By default, the text and labels of form elements are
escaped according to \s-1HTML\s0 rules. This means that you can safely use
\&\*(L"<\s-1CLICK\s0 \s-1ME\s0>\*(R" as the label for a button. However, it also interferes with
your ability to incorporate special \s-1HTML\s0 character sequences, such as &Aacute;,
into your fields. If you wish to turn off automatic escaping, call the
\&\fIautoEscape()\fR method with a false value immediately after creating the \s-1CGI\s0 object:
.PP
.Vb 2
\& $query = new CGI;
\& autoEscape(undef);
.Ve
.PP
\&\fIA Lurking Trap!\fR Some of the form-element generating methods return
multiple tags. In a scalar context, the tags will be concatenated
together with spaces, or whatever is the current value of the $"
global. In a list context, the methods will return a list of
elements, allowing you to modify them if you wish. Usually you will
not notice this behavior, but beware of this:
.PP
.Vb 1
\& printf("%s\en",end_form())
.Ve
.PP
\&\fIend_form()\fR produces several tags, and only the first of them will be
printed because the format only expects one value.
.PP
<p>
.Sh "\s-1CREATING\s0 \s-1AN\s0 \s-1ISINDEX\s0 \s-1TAG\s0"
.IX Subsection "CREATING AN ISINDEX TAG"
.Vb 1
\& print isindex(-action=>$action);
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print isindex($action);
.Ve
.PP
Prints out an <isindex> tag. Not very exciting. The parameter
\&\-action specifies the \s-1URL\s0 of the script to process the query. The
default is to process the query with the current script.
.Sh "\s-1STARTING\s0 \s-1AND\s0 \s-1ENDING\s0 A \s-1FORM\s0"
.IX Subsection "STARTING AND ENDING A FORM"
.Vb 5
\& print start_form(-method=>$method,
\& -action=>$action,
\& -enctype=>$encoding);
\& <... various form stuff ...>
\& print endform;
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 3
\& print start_form($method,$action,$encoding);
\& <... various form stuff ...>
\& print endform;
.Ve
.PP
\&\fIstart_form()\fR will return a <form> tag with the optional method,
action and form encoding that you specify. The defaults are:
.PP
.Vb 3
\& method: POST
\& action: this script
\& enctype: application/x-www-form-urlencoded
.Ve
.PP
\&\fIendform()\fR returns the closing </form> tag.
.PP
\&\fIStart_form()\fR's enctype argument tells the browser how to package the various
fields of the form before sending the form to the server. Two
values are possible:
.PP
\&\fBNote:\fR This method was previously named \fIstartform()\fR, and \fIstartform()\fR
is still recognized as an alias.
.IP "\fBapplication/x\-www\-form\-urlencoded\fR" 4
.IX Item "application/x-www-form-urlencoded"
This is the older type of encoding used by all browsers prior to
Netscape 2.0. It is compatible with many \s-1CGI\s0 scripts and is
suitable for short fields containing text data. For your
convenience, \s-1CGI\s0.pm stores the name of this encoding
type in \fB&CGI::URL_ENCODED\fR.
.IP "\fBmultipart/form\-data\fR" 4
.IX Item "multipart/form-data"
This is the newer type of encoding introduced by Netscape 2.0.
It is suitable for forms that contain very large fields or that
are intended for transferring binary data. Most importantly,
it enables the \*(L"file upload\*(R" feature of Netscape 2.0 forms. For
your convenience, \s-1CGI\s0.pm stores the name of this encoding type
in \fB&CGI::MULTIPART\fR
.Sp
Forms that use this type of encoding are not easily interpreted
by \s-1CGI\s0 scripts unless they use \s-1CGI\s0.pm or another library designed
to handle them.
.Sp
If \s-1XHTML\s0 is activated (the default), then forms will be automatically
created using this type of encoding.
.PP
For compatibility, the \fIstart_form()\fR method uses the older form of
encoding by default. If you want to use the newer form of encoding
by default, you can call \fB\f(BIstart_multipart_form()\fB\fR instead of
\&\fB\f(BIstart_form()\fB\fR.
.PP
\&\s-1JAVASCRIPTING:\s0 The \fB\-name\fR and \fB\-onSubmit\fR parameters are provided
for use with JavaScript. The \-name parameter gives the
form a name so that it can be identified and manipulated by
JavaScript functions. \-onSubmit should point to a JavaScript
function that will be executed just before the form is submitted to your
server. You can use this opportunity to check the contents of the form
for consistency and completeness. If you find something wrong, you
can put up an alert box or maybe fix things up yourself. You can
abort the submission by returning false from this function.
.PP
Usually the bulk of JavaScript functions are defined in a <script>
block in the \s-1HTML\s0 header and \-onSubmit points to one of these function
call. See \fIstart_html()\fR for details.
.Sh "\s-1FORM\s0 \s-1ELEMENTS\s0"
.IX Subsection "FORM ELEMENTS"
After starting a form, you will typically create one or more
textfields, popup menus, radio groups and other form elements. Each
of these elements takes a standard set of named arguments. Some
elements also have optional arguments. The standard arguments are as
follows:
.IP "\fB\-name\fR" 4
.IX Item "-name"
The name of the field. After submission this name can be used to
retrieve the field's value using the \fIparam()\fR method.
.IP "\fB\-value\fR, \fB\-values\fR" 4
.IX Item "-value, -values"
The initial value of the field which will be returned to the script
after form submission. Some form elements, such as text fields, take
a single scalar \-value argument. Others, such as popup menus, take a
reference to an array of values. The two arguments are synonyms.
.IP "\fB\-tabindex\fR" 4
.IX Item "-tabindex"
A numeric value that sets the order in which the form element receives
focus when the user presses the tab key. Elements with lower values
receive focus first.
.IP "\fB\-id\fR" 4
.IX Item "-id"
A string identifier that can be used to identify this element to
JavaScript and \s-1DHTML\s0.
.IP "\fB\-override\fR" 4
.IX Item "-override"
A boolean, which, if true, forces the element to take on the value
specified by \fB\-value\fR, overriding the sticky behavior described
earlier for the \fB\-no_sticky\fR pragma.
.IP "\fB\-onChange\fR, \fB\-onFocus\fR, \fB\-onBlur\fR, \fB\-onMouseOver\fR, \fB\-onMouseOut\fR, \fB\-onSelect\fR" 4
.IX Item "-onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect"
These are used to assign JavaScript event handlers. See the
JavaScripting section for more details.
.PP
Other common arguments are described in the next section. In addition
to these, all attributes described in the \s-1HTML\s0 specifications are
supported.
.Sh "\s-1CREATING\s0 A \s-1TEXT\s0 \s-1FIELD\s0"
.IX Subsection "CREATING A TEXT FIELD"
.Vb 5
\& print textfield(-name=>'field_name',
\& -value=>'starting value',
\& -size=>50,
\& -maxlength=>80);
\& -or-
.Ve
.PP
.Vb 1
\& print textfield('field_name','starting value',50,80);
.Ve
.PP
\&\fItextfield()\fR will return a text input field.
.IP "\fBParameters\fR" 4
.IX Item "Parameters"
.PD 0
.IP "1." 4
.PD
The first parameter is the required name for the field (\-name).
.IP "2." 4
The optional second parameter is the default starting value for the field
contents (\-value, formerly known as \-default).
.IP "3." 4
The optional third parameter is the size of the field in
characters (\-size).
.IP "4." 4
The optional fourth parameter is the maximum number of characters the
field will accept (\-maxlength).
.PP
As with all these methods, the field will be initialized with its
previous contents from earlier invocations of the script.
When the form is processed, the value of the text field can be
retrieved with:
.PP
.Vb 1
\& $value = param('foo');
.Ve
.PP
If you want to reset it from its initial value after the script has been
called once, you can do so like this:
.PP
.Vb 1
\& param('foo',"I'm taking over this value!");
.Ve
.Sh "\s-1CREATING\s0 A \s-1BIG\s0 \s-1TEXT\s0 \s-1FIELD\s0"
.IX Subsection "CREATING A BIG TEXT FIELD"
.Vb 4
\& print textarea(-name=>'foo',
\& -default=>'starting value',
\& -rows=>10,
\& -columns=>50);
.Ve
.PP
.Vb 1
\& -or
.Ve
.PP
.Vb 1
\& print textarea('foo','starting value',10,50);
.Ve
.PP
\&\fItextarea()\fR is just like textfield, but it allows you to specify
rows and columns for a multiline text entry box. You can provide
a starting value for the field, which can be long and contain
multiple lines.
.Sh "\s-1CREATING\s0 A \s-1PASSWORD\s0 \s-1FIELD\s0"
.IX Subsection "CREATING A PASSWORD FIELD"
.Vb 5
\& print password_field(-name=>'secret',
\& -value=>'starting value',
\& -size=>50,
\& -maxlength=>80);
\& -or-
.Ve
.PP
.Vb 1
\& print password_field('secret','starting value',50,80);
.Ve
.PP
\&\fIpassword_field()\fR is identical to \fItextfield()\fR, except that its contents
will be starred out on the web page.
.Sh "\s-1CREATING\s0 A \s-1FILE\s0 \s-1UPLOAD\s0 \s-1FIELD\s0"
.IX Subsection "CREATING A FILE UPLOAD FIELD"
.Vb 5
\& print filefield(-name=>'uploaded_file',
\& -default=>'starting value',
\& -size=>50,
\& -maxlength=>80);
\& -or-
.Ve
.PP
.Vb 1
\& print filefield('uploaded_file','starting value',50,80);
.Ve
.PP
\&\fIfilefield()\fR will return a file upload field for Netscape 2.0 browsers.
In order to take full advantage of this \fIyou must use the new
multipart encoding scheme\fR for the form. You can do this either
by calling \fB\f(BIstart_form()\fB\fR with an encoding type of \fB&CGI::MULTIPART\fR,
or by calling the new method \fB\f(BIstart_multipart_form()\fB\fR instead of
vanilla \fB\f(BIstart_form()\fB\fR.
.IP "\fBParameters\fR" 4
.IX Item "Parameters"
.PD 0
.IP "1." 4
.PD
The first parameter is the required name for the field (\-name).
.IP "2." 4
The optional second parameter is the starting value for the field contents
to be used as the default file name (\-default).
.Sp
For security reasons, browsers don't pay any attention to this field,
and so the starting value will always be blank. Worse, the field
loses its \*(L"sticky\*(R" behavior and forgets its previous contents. The
starting value field is called for in the \s-1HTML\s0 specification, however,
and possibly some browser will eventually provide support for it.
.IP "3." 4
The optional third parameter is the size of the field in
characters (\-size).
.IP "4." 4
The optional fourth parameter is the maximum number of characters the
field will accept (\-maxlength).
.PP
When the form is processed, you can retrieve the entered filename
by calling \fIparam()\fR:
.PP
.Vb 1
\& $filename = param('uploaded_file');
.Ve
.PP
Different browsers will return slightly different things for the
name. Some browsers return the filename only. Others return the full
path to the file, using the path conventions of the user's machine.
Regardless, the name returned is always the name of the file on the
\&\fIuser's\fR machine, and is unrelated to the name of the temporary file
that \s-1CGI\s0.pm creates during upload spooling (see below).
.PP
The filename returned is also a file handle. You can read the contents
of the file using standard Perl file reading calls:
.PP
.Vb 4
\& # Read a text file and print it out
\& while (<$filename>) {
\& print;
\& }
.Ve
.PP
.Vb 5
\& # Copy a binary file to somewhere safe
\& open (OUTFILE,">>/usr/local/web/users/feedback");
\& while ($bytesread=read($filename,$buffer,1024)) {
\& print OUTFILE $buffer;
\& }
.Ve
.PP
However, there are problems with the dual nature of the upload fields.
If you \f(CW\*(C`use strict\*(C'\fR, then Perl will complain when you try to use a
string as a filehandle. You can get around this by placing the file
reading code in a block containing the \f(CW\*(C`no strict\*(C'\fR pragma. More
seriously, it is possible for the remote user to type garbage into the
upload field, in which case what you get from \fIparam()\fR is not a
filehandle at all, but a string.
.PP
To be safe, use the \fI\fIupload()\fI\fR function (new in version 2.47). When
called with the name of an upload field, \fI\fIupload()\fI\fR returns a
filehandle, or undef if the parameter is not a valid filehandle.
.PP
.Vb 4
\& $fh = upload('uploaded_file');
\& while (<$fh>) {
\& print;
\& }
.Ve
.PP
In an list context, \fIupload()\fR will return an array of filehandles.
This makes it possible to create forms that use the same name for
multiple upload fields.
.PP
This is the recommended idiom.
.PP
When a file is uploaded the browser usually sends along some
information along with it in the format of headers. The information
usually includes the \s-1MIME\s0 content type. Future browsers may send
other information as well (such as modification date and size). To
retrieve this information, call \fIuploadInfo()\fR. It returns a reference to
an associative array containing all the document headers.
.PP
.Vb 5
\& $filename = param('uploaded_file');
\& $type = uploadInfo($filename)->{'Content-Type'};
\& unless ($type eq 'text/html') {
\& die "HTML FILES ONLY!";
\& }
.Ve
.PP
If you are using a machine that recognizes \*(L"text\*(R" and \*(L"binary\*(R" data
modes, be sure to understand when and how to use them (see the Camel book).
Otherwise you may find that binary files are corrupted during file
uploads.
.PP
There are occasionally problems involving parsing the uploaded file.
This usually happens when the user presses \*(L"Stop\*(R" before the upload is
finished. In this case, \s-1CGI\s0.pm will return undef for the name of the
uploaded file and set \fI\fIcgi_error()\fI\fR to the string \*(L"400 Bad request
(malformed multipart \s-1POST\s0)\*(R". This error message is designed so that
you can incorporate it into a status code to be sent to the browser.
Example:
.PP
.Vb 5
\& $file = upload('uploaded_file');
\& if (!$file && cgi_error) {
\& print header(-status=>cgi_error);
\& exit 0;
\& }
.Ve
.PP
You are free to create a custom \s-1HTML\s0 page to complain about the error,
if you wish.
.PP
You can set up a callback that will be called whenever a file upload
is being read during the form processing. This is much like the
\&\s-1UPLOAD_HOOK\s0 facility available in Apache::Request, with the exception
that the first argument to the callback is an Apache::Upload object,
here it's the remote filename.
.PP
.Vb 1
\& $q = CGI->new(\e&hook,$data);
.Ve
.PP
.Vb 5
\& sub hook
\& {
\& my ($filename, $buffer, $bytes_read, $data) = @_;
\& print "Read $bytes_read bytes of $filename\en";
\& }
.Ve
.PP
If using the function-oriented interface, call the \fICGI::upload_hook()\fR
method before calling \fIparam()\fR or any other \s-1CGI\s0 functions:
.PP
.Vb 1
\& CGI::upload_hook(\e&hook,$data);
.Ve
.PP
This method is not exported by default. You will have to import it
explicitly if you wish to use it without the \s-1CGI::\s0 prefix.
.PP
If you are using \s-1CGI\s0.pm on a Windows platform and find that binary
files get slightly larger when uploaded but that text files remain the
same, then you have forgotten to activate binary mode on the output
filehandle. Be sure to call \fIbinmode()\fR on any handle that you create
to write the uploaded file to disk.
.PP
\&\s-1JAVASCRIPTING:\s0 The \fB\-onChange\fR, \fB\-onFocus\fR, \fB\-onBlur\fR,
\&\fB\-onMouseOver\fR, \fB\-onMouseOut\fR and \fB\-onSelect\fR parameters are
recognized. See \fItextfield()\fR for details.
.Sh "\s-1CREATING\s0 A \s-1POPUP\s0 \s-1MENU\s0"
.IX Subsection "CREATING A POPUP MENU"
.Vb 3
\& print popup_menu('menu_name',
\& ['eenie','meenie','minie'],
\& 'meenie');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 7
\& %labels = ('eenie'=>'your first choice',
\& 'meenie'=>'your second choice',
\& 'minie'=>'your third choice');
\& %attributes = ('eenie'=>{'class'=>'class of first choice'});
\& print popup_menu('menu_name',
\& ['eenie','meenie','minie'],
\& 'meenie',\e%labels,\e%attributes);
.Ve
.PP
.Vb 1
\& -or (named parameter style)-
.Ve
.PP
.Vb 5
\& print popup_menu(-name=>'menu_name',
\& -values=>['eenie','meenie','minie'],
\& -default=>'meenie',
\& -labels=>\e%labels,
\& -attributes=>\e%attributes);
.Ve
.PP
\&\fIpopup_menu()\fR creates a menu.
.IP "1." 4
The required first argument is the menu's name (\-name).
.IP "2." 4
The required second argument (\-values) is an array \fBreference\fR
containing the list of menu items in the menu. You can pass the
method an anonymous array, as shown in the example, or a reference to
a named array, such as \*(L"\e@foo\*(R".
.IP "3." 4
The optional third parameter (\-default) is the name of the default
menu choice. If not specified, the first item will be the default.
The values of the previous choice will be maintained across queries.
.IP "4." 4
The optional fourth parameter (\-labels) is provided for people who
want to use different values for the user-visible label inside the
popup menu and the value returned to your script. It's a pointer to an
associative array relating menu values to user-visible labels. If you
leave this parameter blank, the menu values will be displayed by
default. (You can also leave a label undefined if you want to).
.IP "5." 4
The optional fifth parameter (\-attributes) is provided to assign
any of the common \s-1HTML\s0 attributes to an individual menu item. It's
a pointer to an associative array relating menu values to another
associative array with the attribute's name as the key and the
attribute's value as the value.
.PP
When the form is processed, the selected value of the popup menu can
be retrieved using:
.PP
.Vb 1
\& $popup_menu_value = param('menu_name');
.Ve
.Sh "\s-1CREATING\s0 \s-1AN\s0 \s-1OPTION\s0 \s-1GROUP\s0"
.IX Subsection "CREATING AN OPTION GROUP"
Named parameter style
.PP
.Vb 9
\& print popup_menu(-name=>'menu_name',
\& -values=>[qw/eenie meenie minie/,
\& optgroup(-name=>'optgroup_name',
\& -values => ['moe','catch'],
\& -attributes=>{'catch'=>{'class'=>'red'}})],
\& -labels=>{'eenie'=>'one',
\& 'meenie'=>'two',
\& 'minie'=>'three'},
\& -default=>'meenie');
.Ve
.PP
.Vb 6
\& Old style
\& print popup_menu('menu_name',
\& ['eenie','meenie','minie',
\& optgroup('optgroup_name', ['moe', 'catch'],
\& {'catch'=>{'class'=>'red'}})],'meenie',
\& {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
.Ve
.PP
\&\fIoptgroup()\fR creates an option group within a popup menu.
.IP "1." 4
The required first argument (\fB\-name\fR) is the label attribute of the
optgroup and is \fBnot\fR inserted in the parameter list of the query.
.IP "2." 4
The required second argument (\fB\-values\fR) is an array reference
containing the list of menu items in the menu. You can pass the
method an anonymous array, as shown in the example, or a reference
to a named array, such as \e@foo. If you pass a \s-1HASH\s0 reference,
the keys will be used for the menu values, and the values will be
used for the menu labels (see \-labels below).
.IP "3." 4
The optional third parameter (\fB\-labels\fR) allows you to pass a reference
to an associative array containing user-visible labels for one or more
of the menu items. You can use this when you want the user to see one
menu string, but have the browser return your program a different one.
If you don't specify this, the value string will be used instead
(\*(L"eenie\*(R", \*(L"meenie\*(R" and \*(L"minie\*(R" in this example). This is equivalent
to using a hash reference for the \-values parameter.
.IP "4." 4
An optional fourth parameter (\fB\-labeled\fR) can be set to a true value
and indicates that the values should be used as the label attribute
for each option element within the optgroup.
.IP "5." 4
An optional fifth parameter (\-novals) can be set to a true value and
indicates to suppress the val attribut in each option element within
the optgroup.
.Sp
See the discussion on optgroup at W3C
(http://www.w3.org/TR/REC\-html40/interact/forms.html#edef\-OPTGROUP)
for details.
.IP "6." 4
An optional sixth parameter (\-attributes) is provided to assign
any of the common \s-1HTML\s0 attributes to an individual menu item. It's
a pointer to an associative array relating menu values to another
associative array with the attribute's name as the key and the
attribute's value as the value.
.Sh "\s-1CREATING\s0 A \s-1SCROLLING\s0 \s-1LIST\s0"
.IX Subsection "CREATING A SCROLLING LIST"
.Vb 4
\& print scrolling_list('list_name',
\& ['eenie','meenie','minie','moe'],
\& ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
\& -or-
.Ve
.PP
.Vb 4
\& print scrolling_list('list_name',
\& ['eenie','meenie','minie','moe'],
\& ['eenie','moe'],5,'true',
\& \e%labels,%attributes);
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 7
\& print scrolling_list(-name=>'list_name',
\& -values=>['eenie','meenie','minie','moe'],
\& -default=>['eenie','moe'],
\& -size=>5,
\& -multiple=>'true',
\& -labels=>\e%labels,
\& -attributes=>\e%attributes);
.Ve
.PP
\&\fIscrolling_list()\fR creates a scrolling list.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first and second arguments are the list name (\-name) and values
(\-values). As in the popup menu, the second argument should be an
array reference.
.IP "2." 4
The optional third argument (\-default) can be either a reference to a
list containing the values to be selected by default, or can be a
single value to select. If this argument is missing or undefined,
then nothing is selected when the list first appears. In the named
parameter version, you can use the synonym \*(L"\-defaults\*(R" for this
parameter.
.IP "3." 4
The optional fourth argument is the size of the list (\-size).
.IP "4." 4
The optional fifth argument can be set to true to allow multiple
simultaneous selections (\-multiple). Otherwise only one selection
will be allowed at a time.
.IP "5." 4
The optional sixth argument is a pointer to an associative array
containing long user-visible labels for the list items (\-labels).
If not provided, the values will be displayed.
.IP "6." 4
The optional sixth parameter (\-attributes) is provided to assign
any of the common \s-1HTML\s0 attributes to an individual menu item. It's
a pointer to an associative array relating menu values to another
associative array with the attribute's name as the key and the
attribute's value as the value.
.Sp
When this form is processed, all selected list items will be returned as
a list under the parameter name 'list_name'. The values of the
selected items can be retrieved with:
.Sp
.Vb 1
\& @selected = param('list_name');
.Ve
.Sh "\s-1CREATING\s0 A \s-1GROUP\s0 \s-1OF\s0 \s-1RELATED\s0 \s-1CHECKBOXES\s0"
.IX Subsection "CREATING A GROUP OF RELATED CHECKBOXES"
.Vb 6
\& print checkbox_group(-name=>'group_name',
\& -values=>['eenie','meenie','minie','moe'],
\& -default=>['eenie','moe'],
\& -linebreak=>'true',
\& -labels=>\e%labels,
\& -attributes=>\e%attributes);
.Ve
.PP
.Vb 4
\& print checkbox_group('group_name',
\& ['eenie','meenie','minie','moe'],
\& ['eenie','moe'],'true',\e%labels,
\& {'moe'=>{'class'=>'red'}});
.Ve
.PP
.Vb 1
\& HTML3-COMPATIBLE BROWSERS ONLY:
.Ve
.PP
.Vb 3
\& print checkbox_group(-name=>'group_name',
\& -values=>['eenie','meenie','minie','moe'],
\& -rows=2,-columns=>2);
.Ve
.PP
\&\fIcheckbox_group()\fR creates a list of checkboxes that are related
by the same name.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first and second arguments are the checkbox name and values,
respectively (\-name and \-values). As in the popup menu, the second
argument should be an array reference. These values are used for the
user-readable labels printed next to the checkboxes as well as for the
values passed to your script in the query string.
.IP "2." 4
The optional third argument (\-default) can be either a reference to a
list containing the values to be checked by default, or can be a
single value to checked. If this argument is missing or undefined,
then nothing is selected when the list first appears.
.IP "3." 4
The optional fourth argument (\-linebreak) can be set to true to place
line breaks between the checkboxes so that they appear as a vertical
list. Otherwise, they will be strung together on a horizontal line.
.PP
The optional b<\-labels> argument is a pointer to an associative array
relating the checkbox values to the user-visible labels that will be
printed next to them. If not provided, the values will be used as the
default.
.PP
Modern browsers can take advantage of the optional parameters
\&\fB\-rows\fR, and \fB\-columns\fR. These parameters cause \fIcheckbox_group()\fR to
return an \s-1HTML3\s0 compatible table containing the checkbox group
formatted with the specified number of rows and columns. You can
provide just the \-columns parameter if you wish; checkbox_group will
calculate the correct number of rows for you.
.PP
The optional \fB\-attributes\fR argument is provided to assign any of the
common \s-1HTML\s0 attributes to an individual menu item. It's a pointer to
an associative array relating menu values to another associative array
with the attribute's name as the key and the attribute's value as the
value.
.PP
The optional \fB\-tabindex\fR argument can be used to control the order in which
radio buttons receive focus when the user presses the tab button. If
passed a scalar numeric value, the first element in the group will
receive this tab index and subsequent elements will be incremented by
one. If given a reference to an array of radio button values, then
the indexes will be jiggered so that the order specified in the array
will correspond to the tab order. You can also pass a reference to a
hash in which the hash keys are the radio button values and the values
are the tab indexes of each button. Examples:
.PP
.Vb 3
\& -tabindex => 100 # this group starts at index 100 and counts up
\& -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
\& -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
.Ve
.PP
When the form is processed, all checked boxes will be returned as
a list under the parameter name 'group_name'. The values of the
\&\*(L"on\*(R" checkboxes can be retrieved with:
.PP
.Vb 1
\& @turned_on = param('group_name');
.Ve
.PP
The value returned by \fIcheckbox_group()\fR is actually an array of button
elements. You can capture them and use them within tables, lists,
or in other creative ways:
.PP
.Vb 2
\& @h = checkbox_group(-name=>'group_name',-values=>\e@values);
\& &use_in_creative_way(@h);
.Ve
.Sh "\s-1CREATING\s0 A \s-1STANDALONE\s0 \s-1CHECKBOX\s0"
.IX Subsection "CREATING A STANDALONE CHECKBOX"
.Vb 4
\& print checkbox(-name=>'checkbox_name',
\& -checked=>1,
\& -value=>'ON',
\& -label=>'CLICK ME');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print checkbox('checkbox_name','checked','ON','CLICK ME');
.Ve
.PP
\&\fIcheckbox()\fR is used to create an isolated checkbox that isn't logically
related to any others.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first parameter is the required name for the checkbox (\-name). It
will also be used for the user-readable label printed next to the
checkbox.
.IP "2." 4
The optional second parameter (\-checked) specifies that the checkbox
is turned on by default. Synonyms are \-selected and \-on.
.IP "3." 4
The optional third parameter (\-value) specifies the value of the
checkbox when it is checked. If not provided, the word \*(L"on\*(R" is
assumed.
.IP "4." 4
The optional fourth parameter (\-label) is the user-readable label to
be attached to the checkbox. If not provided, the checkbox name is
used.
.PP
The value of the checkbox can be retrieved using:
.PP
.Vb 1
\& $turned_on = param('checkbox_name');
.Ve
.Sh "\s-1CREATING\s0 A \s-1RADIO\s0 \s-1BUTTON\s0 \s-1GROUP\s0"
.IX Subsection "CREATING A RADIO BUTTON GROUP"
.Vb 6
\& print radio_group(-name=>'group_name',
\& -values=>['eenie','meenie','minie'],
\& -default=>'meenie',
\& -linebreak=>'true',
\& -labels=>\e%labels,
\& -attributes=>\e%attributes);
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 2
\& print radio_group('group_name',['eenie','meenie','minie'],
\& 'meenie','true',\e%labels,\e%attributes);
.Ve
.PP
.Vb 1
\& HTML3-COMPATIBLE BROWSERS ONLY:
.Ve
.PP
.Vb 3
\& print radio_group(-name=>'group_name',
\& -values=>['eenie','meenie','minie','moe'],
\& -rows=2,-columns=>2);
.Ve
.PP
\&\fIradio_group()\fR creates a set of logically-related radio buttons
(turning one member of the group on turns the others off)
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first argument is the name of the group and is required (\-name).
.IP "2." 4
The second argument (\-values) is the list of values for the radio
buttons. The values and the labels that appear on the page are
identical. Pass an array \fIreference\fR in the second argument, either
using an anonymous array, as shown, or by referencing a named array as
in \*(L"\e@foo\*(R".
.IP "3." 4
The optional third parameter (\-default) is the name of the default
button to turn on. If not specified, the first item will be the
default. You can provide a nonexistent button name, such as \*(L"\-\*(R" to
start up with no buttons selected.
.IP "4." 4
The optional fourth parameter (\-linebreak) can be set to 'true' to put
line breaks between the buttons, creating a vertical list.
.IP "5." 4
The optional fifth parameter (\-labels) is a pointer to an associative
array relating the radio button values to user-visible labels to be
used in the display. If not provided, the values themselves are
displayed.
.PP
All modern browsers can take advantage of the optional parameters
\&\fB\-rows\fR, and \fB\-columns\fR. These parameters cause \fIradio_group()\fR to
return an \s-1HTML3\s0 compatible table containing the radio group formatted
with the specified number of rows and columns. You can provide just
the \-columns parameter if you wish; radio_group will calculate the
correct number of rows for you.
.PP
To include row and column headings in the returned table, you
can use the \fB\-rowheader\fR and \fB\-colheader\fR parameters. Both
of these accept a pointer to an array of headings to use.
The headings are just decorative. They don't reorganize the
interpretation of the radio buttons \*(-- they're still a single named
unit.
.PP
The optional \fB\-tabindex\fR argument can be used to control the order in which
radio buttons receive focus when the user presses the tab button. If
passed a scalar numeric value, the first element in the group will
receive this tab index and subsequent elements will be incremented by
one. If given a reference to an array of radio button values, then
the indexes will be jiggered so that the order specified in the array
will correspond to the tab order. You can also pass a reference to a
hash in which the hash keys are the radio button values and the values
are the tab indexes of each button. Examples:
.PP
.Vb 3
\& -tabindex => 100 # this group starts at index 100 and counts up
\& -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
\& -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
.Ve
.PP
The optional \fB\-attributes\fR argument is provided to assign any of the
common \s-1HTML\s0 attributes to an individual menu item. It's a pointer to
an associative array relating menu values to another associative array
with the attribute's name as the key and the attribute's value as the
value.
.PP
When the form is processed, the selected radio button can
be retrieved using:
.PP
.Vb 1
\& $which_radio_button = param('group_name');
.Ve
.PP
The value returned by \fIradio_group()\fR is actually an array of button
elements. You can capture them and use them within tables, lists,
or in other creative ways:
.PP
.Vb 2
\& @h = radio_group(-name=>'group_name',-values=>\e@values);
\& &use_in_creative_way(@h);
.Ve
.Sh "\s-1CREATING\s0 A \s-1SUBMIT\s0 \s-1BUTTON\s0"
.IX Subsection "CREATING A SUBMIT BUTTON"
.Vb 2
\& print submit(-name=>'button_name',
\& -value=>'value');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print submit('button_name','value');
.Ve
.PP
\&\fIsubmit()\fR will create the query submission button. Every form
should have one of these.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first argument (\-name) is optional. You can give the button a
name if you have several submission buttons in your form and you want
to distinguish between them.
.IP "2." 4
The second argument (\-value) is also optional. This gives the button
a value that will be passed to your script in the query string. The
name will also be used as the user-visible label.
.IP "3." 4
You can use \-label as an alias for \-value. I always get confused
about which of \-name and \-value changes the user-visible label on the
button.
.PP
You can figure out which button was pressed by using different
values for each one:
.PP
.Vb 1
\& $which_one = param('button_name');
.Ve
.Sh "\s-1CREATING\s0 A \s-1RESET\s0 \s-1BUTTON\s0"
.IX Subsection "CREATING A RESET BUTTON"
.Vb 1
\& print reset
.Ve
.PP
\&\fIreset()\fR creates the \*(L"reset\*(R" button. Note that it restores the
form to its value from the last time the script was called,
\&\s-1NOT\s0 necessarily to the defaults.
.PP
Note that this conflicts with the Perl \fIreset()\fR built\-in. Use
\&\fICORE::reset()\fR to get the original reset function.
.Sh "\s-1CREATING\s0 A \s-1DEFAULT\s0 \s-1BUTTON\s0"
.IX Subsection "CREATING A DEFAULT BUTTON"
.Vb 1
\& print defaults('button_label')
.Ve
.PP
\&\fIdefaults()\fR creates a button that, when invoked, will cause the
form to be completely reset to its defaults, wiping out all the
changes the user ever made.
.Sh "\s-1CREATING\s0 A \s-1HIDDEN\s0 \s-1FIELD\s0"
.IX Subsection "CREATING A HIDDEN FIELD"
.Vb 2
\& print hidden(-name=>'hidden_name',
\& -default=>['value1','value2'...]);
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print hidden('hidden_name','value1','value2'...);
.Ve
.PP
\&\fIhidden()\fR produces a text field that can't be seen by the user. It
is useful for passing state variable information from one invocation
of the script to the next.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first argument is required and specifies the name of this
field (\-name).
.IP "2." 4
The second argument is also required and specifies its value
(\-default). In the named parameter style of calling, you can provide
a single value here or a reference to a whole list
.PP
Fetch the value of a hidden field this way:
.PP
.Vb 1
\& $hidden_value = param('hidden_name');
.Ve
.PP
Note, that just like all the other form elements, the value of a
hidden field is \*(L"sticky\*(R". If you want to replace a hidden field with
some other values after the script has been called once you'll have to
do it manually:
.PP
.Vb 1
\& param('hidden_name','new','values','here');
.Ve
.Sh "\s-1CREATING\s0 A \s-1CLICKABLE\s0 \s-1IMAGE\s0 \s-1BUTTON\s0"
.IX Subsection "CREATING A CLICKABLE IMAGE BUTTON"
.Vb 3
\& print image_button(-name=>'button_name',
\& -src=>'/source/URL',
\& -align=>'MIDDLE');
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print image_button('button_name','/source/URL','MIDDLE');
.Ve
.PP
\&\fIimage_button()\fR produces a clickable image. When it's clicked on the
position of the click is returned to your script as \*(L"button_name.x\*(R"
and \*(L"button_name.y\*(R", where \*(L"button_name\*(R" is the name you've assigned
to it.
.IP "\fBParameters:\fR" 4
.IX Item "Parameters:"
.PD 0
.IP "1." 4
.PD
The first argument (\-name) is required and specifies the name of this
field.
.IP "2." 4
The second argument (\-src) is also required and specifies the \s-1URL\s0
.IP "3. The third option (\-align, optional) is an alignment type, and may be \s-1TOP\s0, \s-1BOTTOM\s0 or \s-1MIDDLE\s0" 4
.IX Item "3. The third option (-align, optional) is an alignment type, and may be TOP, BOTTOM or MIDDLE"
.PP
Fetch the value of the button this way:
\f(CW$x\fR = param('button_name.x');
\f(CW$y\fR = param('button_name.y');
.Sh "\s-1CREATING\s0 A \s-1JAVASCRIPT\s0 \s-1ACTION\s0 \s-1BUTTON\s0"
.IX Subsection "CREATING A JAVASCRIPT ACTION BUTTON"
.Vb 3
\& print button(-name=>'button_name',
\& -value=>'user visible label',
\& -onClick=>"do_something()");
.Ve
.PP
.Vb 1
\& -or-
.Ve
.PP
.Vb 1
\& print button('button_name',"do_something()");
.Ve
.PP
\&\fIbutton()\fR produces a button that is compatible with Netscape 2.0's
JavaScript. When it's pressed the fragment of JavaScript code
pointed to by the \fB\-onClick\fR parameter will be executed. On
non-Netscape browsers this form element will probably not even
display.
.SH "HTTP COOKIES"
.IX Header "HTTP COOKIES"
Netscape browsers versions 1.1 and higher, and all versions of
Internet Explorer, support a so-called \*(L"cookie\*(R" designed to help
maintain state within a browser session. \s-1CGI\s0.pm has several methods
that support cookies.
.PP
A cookie is a name=value pair much like the named parameters in a \s-1CGI\s0
query string. \s-1CGI\s0 scripts create one or more cookies and send
them to the browser in the \s-1HTTP\s0 header. The browser maintains a list
of cookies that belong to a particular Web server, and returns them
to the \s-1CGI\s0 script during subsequent interactions.
.PP
In addition to the required name=value pair, each cookie has several
optional attributes:
.IP "1. an expiration time" 4
.IX Item "1. an expiration time"
This is a time/date string (in a special \s-1GMT\s0 format) that indicates
when a cookie expires. The cookie will be saved and returned to your
script until this expiration date is reached if the user exits
the browser and restarts it. If an expiration date isn't specified, the cookie
will remain active until the user quits the browser.
.IP "2. a domain" 4
.IX Item "2. a domain"
This is a partial or complete domain name for which the cookie is
valid. The browser will return the cookie to any host that matches
the partial domain name. For example, if you specify a domain name
of \*(L".capricorn.com\*(R", then the browser will return the cookie to
Web servers running on any of the machines \*(L"www.capricorn.com\*(R",
\&\*(L"www2.capricorn.com\*(R", \*(L"feckless.capricorn.com\*(R", etc. Domain names
must contain at least two periods to prevent attempts to match
on top level domains like \*(L".edu\*(R". If no domain is specified, then
the browser will only return the cookie to servers on the host the
cookie originated from.
.IP "3. a path" 4
.IX Item "3. a path"
If you provide a cookie path attribute, the browser will check it
against your script's \s-1URL\s0 before returning the cookie. For example,
if you specify the path \*(L"/cgi\-bin\*(R", then the cookie will be returned
to each of the scripts \*(L"/cgi\-bin/tally.pl\*(R", \*(L"/cgi\-bin/order.pl\*(R",
and \*(L"/cgi\-bin/customer_service/complain.pl\*(R", but not to the script
\&\*(L"/cgi\-private/site_admin.pl\*(R". By default, path is set to \*(L"/\*(R", which
causes the cookie to be sent to any \s-1CGI\s0 script on your site.
.ie n .IP "4. a ""secure"" flag" 4
.el .IP "4. a ``secure'' flag" 4
.IX Item "4. a secure flag"
If the \*(L"secure\*(R" attribute is set, the cookie will only be sent to your
script if the \s-1CGI\s0 request is occurring on a secure channel, such as \s-1SSL\s0.
.PP
The interface to \s-1HTTP\s0 cookies is the \fB\f(BIcookie()\fB\fR method:
.PP
.Vb 7
\& $cookie = cookie(-name=>'sessionID',
\& -value=>'xyzzy',
\& -expires=>'+1h',
\& -path=>'/cgi-bin/database',
\& -domain=>'.capricorn.org',
\& -secure=>1);
\& print header(-cookie=>$cookie);
.Ve
.PP
\&\fB\f(BIcookie()\fB\fR creates a new cookie. Its parameters include:
.IP "\fB\-name\fR" 4
.IX Item "-name"
The name of the cookie (required). This can be any string at all.
Although browsers limit their cookie names to non-whitespace
alphanumeric characters, \s-1CGI\s0.pm removes this restriction by escaping
and unescaping cookies behind the scenes.
.IP "\fB\-value\fR" 4
.IX Item "-value"
The value of the cookie. This can be any scalar value,
array reference, or even associative array reference. For example,
you can store an entire associative array into a cookie this way:
.Sp
.Vb 2
\& $cookie=cookie(-name=>'family information',
\& -value=>\e%childrens_ages);
.Ve
.IP "\fB\-path\fR" 4
.IX Item "-path"
The optional partial path for which this cookie will be valid, as described
above.
.IP "\fB\-domain\fR" 4
.IX Item "-domain"
The optional partial domain for which this cookie will be valid, as described
above.
.IP "\fB\-expires\fR" 4
.IX Item "-expires"
The optional expiration date for this cookie. The format is as described
in the section on the \fB\f(BIheader()\fB\fR method:
.Sp
.Vb 1
\& "+1h" one hour from now
.Ve
.IP "\fB\-secure\fR" 4
.IX Item "-secure"
If set to true, this cookie will only be used within a secure
\&\s-1SSL\s0 session.
.PP
The cookie created by \fIcookie()\fR must be incorporated into the \s-1HTTP\s0
header within the string returned by the \fIheader()\fR method:
.PP
.Vb 1
\& print header(-cookie=>$my_cookie);
.Ve
.PP
To create multiple cookies, give \fIheader()\fR an array reference:
.PP
.Vb 5
\& $cookie1 = cookie(-name=>'riddle_name',
\& -value=>"The Sphynx's Question");
\& $cookie2 = cookie(-name=>'answers',
\& -value=>\e%answers);
\& print header(-cookie=>[$cookie1,$cookie2]);
.Ve
.PP
To retrieve a cookie, request it by name by calling \fIcookie()\fR method
without the \fB\-value\fR parameter:
.PP
.Vb 4
\& use CGI;
\& $query = new CGI;
\& $riddle = cookie('riddle_name');
\& %answers = cookie('answers');
.Ve
.PP
Cookies created with a single scalar value, such as the \*(L"riddle_name\*(R"
cookie, will be returned in that form. Cookies with array and hash
values can also be retrieved.
.PP
The cookie and \s-1CGI\s0 namespaces are separate. If you have a parameter
named 'answers' and a cookie named 'answers', the values retrieved by
\&\fIparam()\fR and \fIcookie()\fR are independent of each other. However, it's
simple to turn a \s-1CGI\s0 parameter into a cookie, and vice\-versa:
.PP
.Vb 4
\& # turn a CGI parameter into a cookie
\& $c=cookie(-name=>'answers',-value=>[param('answers')]);
\& # vice-versa
\& param(-name=>'answers',-value=>[cookie('answers')]);
.Ve
.PP
See the \fBcookie.cgi\fR example script for some ideas on how to use
cookies effectively.
.SH "WORKING WITH FRAMES"
.IX Header "WORKING WITH FRAMES"
It's possible for \s-1CGI\s0.pm scripts to write into several browser panels
and windows using the \s-1HTML\s0 4 frame mechanism. There are three
techniques for defining new frames programmatically:
.IP "1. Create a <Frameset> document" 4
.IX Item "1. Create a <Frameset> document"
After writing out the \s-1HTTP\s0 header, instead of creating a standard
\&\s-1HTML\s0 document using the \fIstart_html()\fR call, create a <frameset>
document that defines the frames on the page. Specify your script(s)
(with appropriate parameters) as the \s-1SRC\s0 for each of the frames.
.Sp
There is no specific support for creating <frameset> sections
in \s-1CGI\s0.pm, but the \s-1HTML\s0 is very simple to write. See the frame
documentation in Netscape's home pages for details
.Sp
.Vb 1
\& http://home.netscape.com/assist/net_sites/frames.html
.Ve
.IP "2. Specify the destination for the document in the \s-1HTTP\s0 header" 4
.IX Item "2. Specify the destination for the document in the HTTP header"
You may provide a \fB\-target\fR parameter to the \fIheader()\fR method:
.Sp
.Vb 1
\& print header(-target=>'ResultsWindow');
.Ve
.Sp
This will tell the browser to load the output of your script into the
frame named \*(L"ResultsWindow\*(R". If a frame of that name doesn't already
exist, the browser will pop up a new window and load your script's
document into that. There are a number of magic names that you can
use for targets. See the frame documents on Netscape's home pages for
details.
.IP "3. Specify the destination for the document in the <form> tag" 4
.IX Item "3. Specify the destination for the document in the <form> tag"
You can specify the frame to load in the \s-1FORM\s0 tag itself. With
\&\s-1CGI\s0.pm it looks like this:
.Sp
.Vb 1
\& print start_form(-target=>'ResultsWindow');
.Ve
.Sp
When your script is reinvoked by the form, its output will be loaded
into the frame named \*(L"ResultsWindow\*(R". If one doesn't already exist
a new window will be created.
.PP
The script \*(L"frameset.cgi\*(R" in the examples directory shows one way to
create pages in which the fill-out form and the response live in
side-by-side frames.
.SH "SUPPORT FOR JAVASCRIPT"
.IX Header "SUPPORT FOR JAVASCRIPT"
Netscape versions 2.0 and higher incorporate an interpreted language
called JavaScript. Internet Explorer, 3.0 and higher, supports a
closely-related dialect called JScript. JavaScript isn't the same as
Java, and certainly isn't at all the same as Perl, which is a great
pity. JavaScript allows you to programatically change the contents of
fill-out forms, create new windows, and pop up dialog box from within
Netscape itself. From the point of view of \s-1CGI\s0 scripting, JavaScript
is quite useful for validating fill-out forms prior to submitting
them.
.PP
You'll need to know JavaScript in order to use it. There are many good
sources in bookstores and on the web.
.PP
The usual way to use JavaScript is to define a set of functions in a
<\s-1SCRIPT\s0> block inside the \s-1HTML\s0 header and then to register event
handlers in the various elements of the page. Events include such
things as the mouse passing over a form element, a button being
clicked, the contents of a text field changing, or a form being
submitted. When an event occurs that involves an element that has
registered an event handler, its associated JavaScript code gets
called.
.PP
The elements that can register event handlers include the <\s-1BODY\s0> of an
\&\s-1HTML\s0 document, hypertext links, all the various elements of a fill-out
form, and the form itself. There are a large number of events, and
each applies only to the elements for which it is relevant. Here is a
partial list:
.IP "\fBonLoad\fR" 4
.IX Item "onLoad"
The browser is loading the current document. Valid in:
.Sp
.Vb 1
\& + The HTML <BODY> section only.
.Ve
.IP "\fBonUnload\fR" 4
.IX Item "onUnload"
The browser is closing the current page or frame. Valid for:
.Sp
.Vb 1
\& + The HTML <BODY> section only.
.Ve
.IP "\fBonSubmit\fR" 4
.IX Item "onSubmit"
The user has pressed the submit button of a form. This event happens
just before the form is submitted, and your function can return a
value of false in order to abort the submission. Valid for:
.Sp
.Vb 1
\& + Forms only.
.Ve
.IP "\fBonClick\fR" 4
.IX Item "onClick"
The mouse has clicked on an item in a fill-out form. Valid for:
.Sp
.Vb 3
\& + Buttons (including submit, reset, and image buttons)
\& + Checkboxes
\& + Radio buttons
.Ve
.IP "\fBonChange\fR" 4
.IX Item "onChange"
The user has changed the contents of a field. Valid for:
.Sp
.Vb 6
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
\& + Popup Menus
\& + Scrolling lists
.Ve
.IP "\fBonFocus\fR" 4
.IX Item "onFocus"
The user has selected a field to work with. Valid for:
.Sp
.Vb 6
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
\& + Popup Menus
\& + Scrolling lists
.Ve
.IP "\fBonBlur\fR" 4
.IX Item "onBlur"
The user has deselected a field (gone to work somewhere else). Valid
for:
.Sp
.Vb 6
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
\& + Popup Menus
\& + Scrolling lists
.Ve
.IP "\fBonSelect\fR" 4
.IX Item "onSelect"
The user has changed the part of a text field that is selected. Valid
for:
.Sp
.Vb 4
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
.Ve
.IP "\fBonMouseOver\fR" 4
.IX Item "onMouseOver"
The mouse has moved over an element.
.Sp
.Vb 6
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
\& + Popup Menus
\& + Scrolling lists
.Ve
.IP "\fBonMouseOut\fR" 4
.IX Item "onMouseOut"
The mouse has moved off an element.
.Sp
.Vb 6
\& + Text fields
\& + Text areas
\& + Password fields
\& + File fields
\& + Popup Menus
\& + Scrolling lists
.Ve
.PP
In order to register a JavaScript event handler with an \s-1HTML\s0 element,
just use the event name as a parameter when you call the corresponding
\&\s-1CGI\s0 method. For example, to have your \fIvalidateAge()\fR JavaScript code
executed every time the textfield named \*(L"age\*(R" changes, generate the
field like this:
.PP
.Vb 1
\& print textfield(-name=>'age',-onChange=>"validateAge(this)");
.Ve
.PP
This example assumes that you've already declared the \fIvalidateAge()\fR
function by incorporating it into a <\s-1SCRIPT\s0> block. The \s-1CGI\s0.pm
\&\fIstart_html()\fR method provides a convenient way to create this section.
.PP
Similarly, you can create a form that checks itself over for
consistency and alerts the user if some essential value is missing by
creating it this way:
print startform(\-onSubmit=>\*(L"validateMe(this)\*(R");
.PP
See the javascript.cgi script for a demonstration of how this all
works.
.SH "LIMITED SUPPORT FOR CASCADING STYLE SHEETS"
.IX Header "LIMITED SUPPORT FOR CASCADING STYLE SHEETS"
\&\s-1CGI\s0.pm has limited support for \s-1HTML3\s0's cascading style sheets (css).
To incorporate a stylesheet into your document, pass the
\&\fIstart_html()\fR method a \fB\-style\fR parameter. The value of this
parameter may be a scalar, in which case it is treated as the source
\&\s-1URL\s0 for the stylesheet, or it may be a hash reference. In the latter
case you should provide the hash with one or more of \fB\-src\fR or
\&\fB\-code\fR. \fB\-src\fR points to a \s-1URL\s0 where an externally-defined
stylesheet can be found. \fB\-code\fR points to a scalar value to be
incorporated into a <style> section. Style definitions in \fB\-code\fR
override similarly-named ones in \fB\-src\fR, hence the name \*(L"cascading.\*(R"
.PP
You may also specify the type of the stylesheet by adding the optional
\&\fB\-type\fR parameter to the hash pointed to by \fB\-style\fR. If not
specified, the style defaults to 'text/css'.
.PP
To refer to a style within the body of your document, add the
\&\fB\-class\fR parameter to any \s-1HTML\s0 element:
.PP
.Vb 1
\& print h1({-class=>'Fancy'},'Welcome to the Party');
.Ve
.PP
Or define styles on the fly with the \fB\-style\fR parameter:
.PP
.Vb 1
\& print h1({-style=>'Color: red;'},'Welcome to Hell');
.Ve
.PP
You may also use the new \fB\f(BIspan()\fB\fR element to apply a style to a
section of text:
.PP
.Vb 4
\& print span({-style=>'Color: red;'},
\& h1('Welcome to Hell'),
\& "Where did that handbasket get to?"
\& );
.Ve
.PP
Note that you must import the \*(L":html3\*(R" definitions to have the
\&\fB\f(BIspan()\fB\fR method available. Here's a quick and dirty example of using
\&\s-1CSS\s0's. See the \s-1CSS\s0 specification at
http://www.w3.org/pub/WWW/TR/Wd\-css\-1.html for more information.
.PP
.Vb 1
\& use CGI qw/:standard :html3/;
.Ve
.PP
.Vb 29
\& #here's a stylesheet incorporated directly into the page
\& $newStyle=<<END;
\& <!--
\& P.Tip {
\& margin-right: 50pt;
\& margin-left: 50pt;
\& color: red;
\& }
\& P.Alert {
\& font-size: 30pt;
\& font-family: sans-serif;
\& color: red;
\& }
\& -->
\& END
\& print header();
\& print start_html( -title=>'CGI with Style',
\& -style=>{-src=>'http://www.capricorn.com/style/st1.css',
\& -code=>$newStyle}
\& );
\& print h1('CGI with Style'),
\& p({-class=>'Tip'},
\& "Better read the cascading style sheet spec before playing with this!"),
\& span({-style=>'color: magenta'},
\& "Look Mom, no hands!",
\& p(),
\& "Whooo wee!"
\& );
\& print end_html;
.Ve
.PP
Pass an array reference to \fB\-code\fR or \fB\-src\fR in order to incorporate
multiple stylesheets into your document.
.PP
Should you wish to incorporate a verbatim stylesheet that includes
arbitrary formatting in the header, you may pass a \-verbatim tag to
the \-style hash, as follows:
.PP
print start_html (\-STYLE => {\-verbatim => '@import
url(\*(L"/server\-common/css/'.$cssFile.'\*(R");',
\-src => '/server\-common/css/core.css'});
</blockquote></pre>
.PP
This will generate an \s-1HTML\s0 header that contains this:
.PP
.Vb 4
\& <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
\& <style type="text/css">
\& @import url("/server-common/css/main.css");
\& </style>
.Ve
.PP
Any additional arguments passed in the \-style value will be
incorporated into the <link> tag. For example:
.PP
.Vb 2
\& start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
\& -media => 'all'});
.Ve
.PP
This will give:
.PP
.Vb 2
\& <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
\& <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
.Ve
.PP
<p>
.PP
To make more complicated <link> tags, use the \fILink()\fR function
and pass it to \fIstart_html()\fR in the \-head argument, as in:
.PP
.Vb 3
\& @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
\& Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
\& print start_html({-head=>\e@h})
.Ve
.SH "DEBUGGING"
.IX Header "DEBUGGING"
If you are running the script from the command line or in the perl
debugger, you can pass the script a list of keywords or
parameter=value pairs on the command line or from standard input (you
don't have to worry about tricking your script into reading from
environment variables). You can pass keywords like this:
.PP
.Vb 1
\& your_script.pl keyword1 keyword2 keyword3
.Ve
.PP
or this:
.PP
.Vb 1
\& your_script.pl keyword1+keyword2+keyword3
.Ve
.PP
or this:
.PP
.Vb 1
\& your_script.pl name1=value1 name2=value2
.Ve
.PP
or this:
.PP
.Vb 1
\& your_script.pl name1=value1&name2=value2
.Ve
.PP
To turn off this feature, use the \-no_debug pragma.
.PP
To test the \s-1POST\s0 method, you may enable full debugging with the \-debug
pragma. This will allow you to feed newline-delimited name=value
pairs to the script on standard input.
.PP
When debugging, you can use quotes and backslashes to escape
characters in the familiar shell manner, letting you place
spaces and other funny characters in your parameter=value
pairs:
.PP
.Vb 1
\& your_script.pl "name1='I am a long value'" "name2=two\e words"
.Ve
.PP
Finally, you can set the path info for the script by prefixing the first
name/value parameter with the path followed by a question mark (?):
.PP
.Vb 1
\& your_script.pl /your/path/here?name1=value1&name2=value2
.Ve
.Sh "\s-1DUMPING\s0 \s-1OUT\s0 \s-1ALL\s0 \s-1THE\s0 \s-1NAME/VALUE\s0 \s-1PAIRS\s0"
.IX Subsection "DUMPING OUT ALL THE NAME/VALUE PAIRS"
The \fIDump()\fR method produces a string consisting of all the query's
name/value pairs formatted nicely as a nested list. This is useful
for debugging purposes:
.PP
.Vb 1
\& print Dump
.Ve
.PP
Produces something that looks like:
.PP
.Vb 11
\& <ul>
\& <li>name1
\& <ul>
\& <li>value1
\& <li>value2
\& </ul>
\& <li>name2
\& <ul>
\& <li>value1
\& </ul>
\& </ul>
.Ve
.PP
As a shortcut, you can interpolate the entire \s-1CGI\s0 object into a string
and it will be replaced with the a nice \s-1HTML\s0 dump shown above:
.PP
.Vb 2
\& $query=new CGI;
\& print "<h2>Current Values</h2> $query\en";
.Ve
.SH "FETCHING ENVIRONMENT VARIABLES"
.IX Header "FETCHING ENVIRONMENT VARIABLES"
Some of the more useful environment variables can be fetched
through this interface. The methods are as follows:
.IP "\fB\f(BIAccept()\fB\fR" 4
.IX Item "Accept()"
Return a list of \s-1MIME\s0 types that the remote browser accepts. If you
give this method a single argument corresponding to a \s-1MIME\s0 type, as in
Accept('text/html'), it will return a floating point value
corresponding to the browser's preference for this type from 0.0
(don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
list are handled correctly.
.Sp
Note that the capitalization changed between version 2.43 and 2.44 in
order to avoid conflict with Perl's \fIaccept()\fR function.
.IP "\fB\f(BIraw_cookie()\fB\fR" 4
.IX Item "raw_cookie()"
Returns the \s-1HTTP_COOKIE\s0 variable, an \s-1HTTP\s0 extension implemented by
Netscape browsers version 1.1 and higher, and all versions of Internet
Explorer. Cookies have a special format, and this method call just
returns the raw form (?cookie dough). See \fIcookie()\fR for ways of
setting and retrieving cooked cookies.
.Sp
Called with no parameters, \fIraw_cookie()\fR returns the packed cookie
structure. You can separate it into individual cookies by splitting
on the character sequence \*(L"; \*(R". Called with the name of a cookie,
retrieves the \fBunescaped\fR form of the cookie. You can use the
regular \fIcookie()\fR method to get the names, or use the \fIraw_fetch()\fR
method from the CGI::Cookie module.
.IP "\fB\f(BIuser_agent()\fB\fR" 4
.IX Item "user_agent()"
Returns the \s-1HTTP_USER_AGENT\s0 variable. If you give
this method a single argument, it will attempt to
pattern match on it, allowing you to do something
like user_agent(netscape);
.IP "\fB\f(BIpath_info()\fB\fR" 4
.IX Item "path_info()"
Returns additional path information from the script \s-1URL\s0.
E.G. fetching /cgi\-bin/your_script/additional/stuff will result in
\&\fIpath_info()\fR returning \*(L"/additional/stuff\*(R".
.Sp
\&\s-1NOTE:\s0 The Microsoft Internet Information Server
is broken with respect to additional path information. If
you use the Perl \s-1DLL\s0 library, the \s-1IIS\s0 server will attempt to
execute the additional path information as a Perl script.
If you use the ordinary file associations mapping, the
path information will be present in the environment,
but incorrect. The best thing to do is to avoid using additional
path information in \s-1CGI\s0 scripts destined for use with \s-1IIS\s0.
.IP "\fB\f(BIpath_translated()\fB\fR" 4
.IX Item "path_translated()"
As per \fIpath_info()\fR but returns the additional
path information translated into a physical path, e.g.
\&\*(L"/usr/local/etc/httpd/htdocs/additional/stuff\*(R".
.Sp
The Microsoft \s-1IIS\s0 is broken with respect to the translated
path as well.
.IP "\fB\f(BIremote_host()\fB\fR" 4
.IX Item "remote_host()"
Returns either the remote host name or \s-1IP\s0 address.
if the former is unavailable.
.IP "\fB\f(BIscript_name()\fB\fR Return the script name as a partial \s-1URL\s0, for self-refering scripts." 4
.IX Item "script_name() Return the script name as a partial URL, for self-refering scripts."
.PD 0
.IP "\fB\f(BIreferer()\fB\fR" 4
.IX Item "referer()"
.PD
Return the \s-1URL\s0 of the page the browser was viewing
prior to fetching your script. Not available for all
browsers.
.IP "\fBauth_type ()\fR" 4
.IX Item "auth_type ()"
Return the authorization/verification method in use for this
script, if any.
.IP "\fBserver_name ()\fR" 4
.IX Item "server_name ()"
Returns the name of the server, usually the machine's host
name.
.IP "\fBvirtual_host ()\fR" 4
.IX Item "virtual_host ()"
When using virtual hosts, returns the name of the host that
the browser attempted to contact
.IP "\fBserver_port ()\fR" 4
.IX Item "server_port ()"
Return the port that the server is listening on.
.IP "\fBvirtual_port ()\fR" 4
.IX Item "virtual_port ()"
Like \fIserver_port()\fR except that it takes virtual hosts into account.
Use this when running with virtual hosts.
.IP "\fBserver_software ()\fR" 4
.IX Item "server_software ()"
Returns the server software and version number.
.IP "\fBremote_user ()\fR" 4
.IX Item "remote_user ()"
Return the authorization/verification name used for user
verification, if this script is protected.
.IP "\fBuser_name ()\fR" 4
.IX Item "user_name ()"
Attempt to obtain the remote user's name, using a variety of different
techniques. This only works with older browsers such as Mosaic.
Newer browsers do not report the user name for privacy reasons!
.IP "\fB\f(BIrequest_method()\fB\fR" 4
.IX Item "request_method()"
Returns the method used to access your script, usually
one of '\s-1POST\s0', '\s-1GET\s0' or '\s-1HEAD\s0'.
.IP "\fB\f(BIcontent_type()\fB\fR" 4
.IX Item "content_type()"
Returns the content_type of data submitted in a \s-1POST\s0, generally
multipart/form\-data or application/x\-www\-form\-urlencoded
.IP "\fB\f(BIhttp()\fB\fR" 4
.IX Item "http()"
Called with no arguments returns the list of \s-1HTTP\s0 environment
variables, including such things as \s-1HTTP_USER_AGENT\s0,
\&\s-1HTTP_ACCEPT_LANGUAGE\s0, and \s-1HTTP_ACCEPT_CHARSET\s0, corresponding to the
like-named \s-1HTTP\s0 header fields in the request. Called with the name of
an \s-1HTTP\s0 header field, returns its value. Capitalization and the use
of hyphens versus underscores are not significant.
.Sp
For example, all three of these examples are equivalent:
.Sp
.Vb 3
\& $requested_language = http('Accept-language');
\& $requested_language = http('Accept_language');
\& $requested_language = http('HTTP_ACCEPT_LANGUAGE');
.Ve
.IP "\fB\f(BIhttps()\fB\fR" 4
.IX Item "https()"
The same as \fI\fIhttp()\fI\fR, but operates on the \s-1HTTPS\s0 environment variables
present when the \s-1SSL\s0 protocol is in effect. Can be used to determine
whether \s-1SSL\s0 is turned on.
.SH "USING NPH SCRIPTS"
.IX Header "USING NPH SCRIPTS"
\&\s-1NPH\s0, or \*(L"no\-parsed\-header\*(R", scripts bypass the server completely by
sending the complete \s-1HTTP\s0 header directly to the browser. This has
slight performance benefits, but is of most use for taking advantage
of \s-1HTTP\s0 extensions that are not directly supported by your server,
such as server push and \s-1PICS\s0 headers.
.PP
Servers use a variety of conventions for designating \s-1CGI\s0 scripts as
\&\s-1NPH\s0. Many Unix servers look at the beginning of the script's name for
the prefix \*(L"nph\-\*(R". The Macintosh WebSTAR server and Microsoft's
Internet Information Server, in contrast, try to decide whether a
program is an \s-1NPH\s0 script by examining the first line of script output.
.PP
\&\s-1CGI\s0.pm supports \s-1NPH\s0 scripts with a special \s-1NPH\s0 mode. When in this
mode, \s-1CGI\s0.pm will output the necessary extra header information when
the \fIheader()\fR and \fIredirect()\fR methods are
called.
.PP
The Microsoft Internet Information Server requires \s-1NPH\s0 mode. As of
version 2.30, \s-1CGI\s0.pm will automatically detect when the script is
running under \s-1IIS\s0 and put itself into this mode. You do not need to
do this manually, although it won't hurt anything if you do. However,
note that if you have applied Service Pack 6, much of the
functionality of \s-1NPH\s0 scripts, including the ability to redirect while
setting a cookie, b<do not work at all> on \s-1IIS\s0 without a special patch
from Microsoft. See
http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
Non-Parsed Headers Stripped From \s-1CGI\s0 Applications That Have nph\-
Prefix in Name.
.IP "In the \fBuse\fR statement" 4
.IX Item "In the use statement"
Simply add the \*(L"\-nph\*(R" pragmato the list of symbols to be imported into
your script:
.Sp
.Vb 1
\& use CGI qw(:standard -nph)
.Ve
.IP "By calling the \fB\f(BInph()\fB\fR method:" 4
.IX Item "By calling the nph() method:"
Call \fB\f(BInph()\fB\fR with a non-zero parameter at any point after using \s-1CGI\s0.pm in your program.
.Sp
.Vb 1
\& CGI->nph(1)
.Ve
.IP "By using \fB\-nph\fR parameters" 4
.IX Item "By using -nph parameters"
in the \fB\f(BIheader()\fB\fR and \fB\f(BIredirect()\fB\fR statements:
.Sp
.Vb 1
\& print header(-nph=>1);
.Ve
.SH "Server Push"
.IX Header "Server Push"
\&\s-1CGI\s0.pm provides four simple functions for producing multipart
documents of the type needed to implement server push. These
functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
import these into your namespace, you must import the \*(L":push\*(R" set.
You are also advised to put the script into \s-1NPH\s0 mode and to set $| to
1 to avoid buffering problems.
.PP
Here is a simple script that demonstrates server push:
.PP
.Vb 14
\& #!/usr/local/bin/perl
\& use CGI qw/:push -nph/;
\& $| = 1;
\& print multipart_init(-boundary=>'----here we go!');
\& foreach (0 .. 4) {
\& print multipart_start(-type=>'text/plain'),
\& "The current time is ",scalar(localtime),"\en";
\& if ($_ < 4) {
\& print multipart_end;
\& } else {
\& print multipart_final;
\& }
\& sleep 1;
\& }
.Ve
.PP
This script initializes server push by calling \fB\f(BImultipart_init()\fB\fR.
It then enters a loop in which it begins a new multipart section by
calling \fB\f(BImultipart_start()\fB\fR, prints the current local time,
and ends a multipart section with \fB\f(BImultipart_end()\fB\fR. It then sleeps
a second, and begins again. On the final iteration, it ends the
multipart section with \fB\f(BImultipart_final()\fB\fR rather than with
\&\fB\f(BImultipart_end()\fB\fR.
.IP "\fImultipart_init()\fR" 4
.IX Item "multipart_init()"
.Vb 1
\& multipart_init(-boundary=>$boundary);
.Ve
.Sp
Initialize the multipart system. The \-boundary argument specifies
what \s-1MIME\s0 boundary string to use to separate parts of the document.
If not provided, \s-1CGI\s0.pm chooses a reasonable boundary for you.
.IP "\fImultipart_start()\fR" 4
.IX Item "multipart_start()"
.Vb 1
\& multipart_start(-type=>$type)
.Ve
.Sp
Start a new part of the multipart document using the specified \s-1MIME\s0
type. If not specified, text/html is assumed.
.IP "\fImultipart_end()\fR" 4
.IX Item "multipart_end()"
.Vb 1
\& multipart_end()
.Ve
.Sp
End a part. You must remember to call \fImultipart_end()\fR once for each
\&\fImultipart_start()\fR, except at the end of the last part of the multipart
document when \fImultipart_final()\fR should be called instead of \fImultipart_end()\fR.
.IP "\fImultipart_final()\fR" 4
.IX Item "multipart_final()"
.Vb 1
\& multipart_final()
.Ve
.Sp
End all parts. You should call \fImultipart_final()\fR rather than
\&\fImultipart_end()\fR at the end of the last part of the multipart document.
.PP
Users interested in server push applications should also have a look
at the CGI::Push module.
.PP
Only Netscape Navigator supports server push. Internet Explorer
browsers do not.
.SH "Avoiding Denial of Service Attacks"
.IX Header "Avoiding Denial of Service Attacks"
A potential problem with \s-1CGI\s0.pm is that, by default, it attempts to
process form POSTings no matter how large they are. A wily hacker
could attack your site by sending a \s-1CGI\s0 script a huge \s-1POST\s0 of many
megabytes. \s-1CGI\s0.pm will attempt to read the entire \s-1POST\s0 into a
variable, growing hugely in size until it runs out of memory. While
the script attempts to allocate the memory the system may slow down
dramatically. This is a form of denial of service attack.
.PP
Another possible attack is for the remote user to force \s-1CGI\s0.pm to
accept a huge file upload. \s-1CGI\s0.pm will accept the upload and store it
in a temporary directory even if your script doesn't expect to receive
an uploaded file. \s-1CGI\s0.pm will delete the file automatically when it
terminates, but in the meantime the remote user may have filled up the
server's disk space, causing problems for other programs.
.PP
The best way to avoid denial of service attacks is to limit the amount
of memory, \s-1CPU\s0 time and disk space that \s-1CGI\s0 scripts can use. Some Web
servers come with built-in facilities to accomplish this. In other
cases, you can use the shell \fIlimit\fR or \fIulimit\fR
commands to put ceilings on \s-1CGI\s0 resource usage.
.PP
\&\s-1CGI\s0.pm also has some simple built-in protections against denial of
service attacks, but you must activate them before you can use them.
These take the form of two global variables in the \s-1CGI\s0 name space:
.IP "\fB$CGI::POST_MAX\fR" 4
.IX Item "$CGI::POST_MAX"
If set to a non-negative integer, this variable puts a ceiling
on the size of POSTings, in bytes. If \s-1CGI\s0.pm detects a \s-1POST\s0
that is greater than the ceiling, it will immediately exit with an error
message. This value will affect both ordinary POSTs and
multipart POSTs, meaning that it limits the maximum size of file
uploads as well. You should set this to a reasonably high
value, such as 1 megabyte.
.IP "\fB$CGI::DISABLE_UPLOADS\fR" 4
.IX Item "$CGI::DISABLE_UPLOADS"
If set to a non-zero value, this will disable file uploads
completely. Other fill-out form values will work as usual.
.PP
You can use these variables in either of two ways.
.IP "\fB1. On a script-by-script basis\fR" 4
.IX Item "1. On a script-by-script basis"
Set the variable at the top of the script, right after the \*(L"use\*(R" statement:
.Sp
.Vb 4
\& use CGI qw/:standard/;
\& use CGI::Carp 'fatalsToBrowser';
\& $CGI::POST_MAX=1024 * 100; # max 100K posts
\& $CGI::DISABLE_UPLOADS = 1; # no uploads
.Ve
.IP "\fB2. Globally for all scripts\fR" 4
.IX Item "2. Globally for all scripts"
Open up \s-1CGI\s0.pm, find the definitions for \f(CW$POST_MAX\fR and
\&\f(CW$DISABLE_UPLOADS\fR, and set them to the desired values. You'll
find them towards the top of the file in a subroutine named
\&\fIinitialize_globals()\fR.
.PP
An attempt to send a \s-1POST\s0 larger than \f(CW$POST_MAX\fR bytes will cause
\&\fI\fIparam()\fI\fR to return an empty \s-1CGI\s0 parameter list. You can test for
this event by checking \fI\fIcgi_error()\fI\fR, either after you create the \s-1CGI\s0
object or, if you are using the function-oriented interface, call
<\fIparam()\fR> for the first time. If the \s-1POST\s0 was intercepted, then
\&\fIcgi_error()\fR will return the message \*(L"413 \s-1POST\s0 too large\*(R".
.PP
This error message is actually defined by the \s-1HTTP\s0 protocol, and is
designed to be returned to the browser as the \s-1CGI\s0 script's status
code. For example:
.PP
.Vb 5
\& $uploaded_file = param('upload');
\& if (!$uploaded_file && cgi_error()) {
\& print header(-status=>cgi_error());
\& exit 0;
\& }
.Ve
.PP
However it isn't clear that any browser currently knows what to do
with this status code. It might be better just to create an
\&\s-1HTML\s0 page that warns the user of the problem.
.SH "COMPATIBILITY WITH CGI\-LIB.PL"
.IX Header "COMPATIBILITY WITH CGI-LIB.PL"
To make it easier to port existing programs that use cgi\-lib.pl the
compatibility routine \*(L"ReadParse\*(R" is provided. Porting is simple:
.PP
\&\s-1OLD\s0 \s-1VERSION\s0
require \*(L"cgi\-lib.pl\*(R";
&ReadParse;
print \*(L"The value of the antique is \f(CW$in\fR{antique}.\en\*(R";
.PP
\&\s-1NEW\s0 \s-1VERSION\s0
use \s-1CGI\s0;
\fICGI::ReadParse()\fR;
print \*(L"The value of the antique is \f(CW$in\fR{antique}.\en\*(R";
.PP
\&\s-1CGI\s0.pm's \fIReadParse()\fR routine creates a tied variable named \f(CW%in\fR,
which can be accessed to obtain the query variables. Like
ReadParse, you can also provide your own variable. Infrequently
used features of ReadParse, such as the creation of \f(CW@in\fR and \f(CW$in\fR
variables, are not supported.
.PP
Once you use ReadParse, you can retrieve the query object itself
this way:
.PP
.Vb 3
\& $q = $in{CGI};
\& print textfield(-name=>'wow',
\& -value=>'does this really work?');
.Ve
.PP
This allows you to start using the more interesting features
of \s-1CGI\s0.pm without rewriting your old scripts from scratch.
.SH "AUTHOR INFORMATION"
.IX Header "AUTHOR INFORMATION"
Copyright 1995\-1998, Lincoln D. Stein. All rights reserved.
.PP
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
.PP
Address bug reports and comments to: lstein@cshl.org. When sending
bug reports, please provide the version of \s-1CGI\s0.pm, the version of
Perl, the name and version of your Web server, and the name and
version of the operating system you are using. If the problem is even
remotely browser dependent, please provide information about the
affected browers as well.
.SH "CREDITS"
.IX Header "CREDITS"
Thanks very much to:
.IP "Matt Heffron (heffron@falstaff.css.beckman.com)" 4
.IX Item "Matt Heffron (heffron@falstaff.css.beckman.com)"
.PD 0
.IP "James Taylor (james.taylor@srs.gov)" 4
.IX Item "James Taylor (james.taylor@srs.gov)"
.IP "Scott Anguish <sanguish@digifix.com>" 4
.IX Item "Scott Anguish <sanguish@digifix.com>"
.IP "Mike Jewell (mlj3u@virginia.edu)" 4
.IX Item "Mike Jewell (mlj3u@virginia.edu)"
.IP "Timothy Shimmin (tes@kbs.citri.edu.au)" 4
.IX Item "Timothy Shimmin (tes@kbs.citri.edu.au)"
.IP "Joergen Haegg (jh@axis.se)" 4
.IX Item "Joergen Haegg (jh@axis.se)"
.IP "Laurent Delfosse (delfosse@delfosse.com)" 4
.IX Item "Laurent Delfosse (delfosse@delfosse.com)"
.IP "Richard Resnick (applepi1@aol.com)" 4
.IX Item "Richard Resnick (applepi1@aol.com)"
.IP "Craig Bishop (csb@barwonwater.vic.gov.au)" 4
.IX Item "Craig Bishop (csb@barwonwater.vic.gov.au)"
.IP "Tony Curtis (tc@vcpc.univie.ac.at)" 4
.IX Item "Tony Curtis (tc@vcpc.univie.ac.at)"
.IP "Tim Bunce (Tim.Bunce@ig.co.uk)" 4
.IX Item "Tim Bunce (Tim.Bunce@ig.co.uk)"
.IP "Tom Christiansen (tchrist@convex.com)" 4
.IX Item "Tom Christiansen (tchrist@convex.com)"
.IP "Andreas Koenig (k@franz.ww.TU\-Berlin.DE)" 4
.IX Item "Andreas Koenig (k@franz.ww.TU-Berlin.DE)"
.IP "Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)" 4
.IX Item "Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)"
.IP "Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)" 4
.IX Item "Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)"
.IP "Stephen Dahmen (joyfire@inxpress.net)" 4
.IX Item "Stephen Dahmen (joyfire@inxpress.net)"
.IP "Ed Jordan (ed@fidalgo.net)" 4
.IX Item "Ed Jordan (ed@fidalgo.net)"
.IP "David Alan Pisoni (david@cnation.com)" 4
.IX Item "David Alan Pisoni (david@cnation.com)"
.IP "Doug MacEachern (dougm@opengroup.org)" 4
.IX Item "Doug MacEachern (dougm@opengroup.org)"
.IP "Robin Houston (robin@oneworld.org)" 4
.IX Item "Robin Houston (robin@oneworld.org)"
.IP "...and many many more..." 4
.IX Item "...and many many more..."
.PD
for suggestions and bug fixes.
.SH "A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT"
.IX Header "A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT"
.Vb 1
\& #!/usr/local/bin/perl
.Ve
.PP
.Vb 1
\& use CGI ':standard';
.Ve
.PP
.Vb 7
\& print header;
\& print start_html("Example CGI.pm Form");
\& print "<h1> Example CGI.pm Form</h1>\en";
\& print_prompt();
\& do_work();
\& print_tail();
\& print end_html;
.Ve
.PP
.Vb 5
\& sub print_prompt {
\& print start_form;
\& print "<em>What's your name?</em><br>";
\& print textfield('name');
\& print checkbox('Not my real name');
.Ve
.PP
.Vb 6
\& print "<p><em>Where can you find English Sparrows?</em><br>";
\& print checkbox_group(
\& -name=>'Sparrow locations',
\& -values=>[England,France,Spain,Asia,Hoboken],
\& -linebreak=>'yes',
\& -defaults=>[England,Asia]);
.Ve
.PP
.Vb 5
\& print "<p><em>How far can they fly?</em><br>",
\& radio_group(
\& -name=>'how far',
\& -values=>['10 ft','1 mile','10 miles','real far'],
\& -default=>'1 mile');
.Ve
.PP
.Vb 4
\& print "<p><em>What's your favorite color?</em> ";
\& print popup_menu(-name=>'Color',
\& -values=>['black','brown','red','yellow'],
\& -default=>'red');
.Ve
.PP
.Vb 1
\& print hidden('Reference','Monty Python and the Holy Grail');
.Ve
.PP
.Vb 7
\& print "<p><em>What have you got there?</em><br>";
\& print scrolling_list(
\& -name=>'possessions',
\& -values=>['A Coconut','A Grail','An Icon',
\& 'A Sword','A Ticket'],
\& -size=>5,
\& -multiple=>'true');
.Ve
.PP
.Vb 4
\& print "<p><em>Any parting comments?</em><br>";
\& print textarea(-name=>'Comments',
\& -rows=>10,
\& -columns=>50);
.Ve
.PP
.Vb 6
\& print "<p>",reset;
\& print submit('Action','Shout');
\& print submit('Action','Scream');
\& print endform;
\& print "<hr>\en";
\& }
.Ve
.PP
.Vb 2
\& sub do_work {
\& my(@values,$key);
.Ve
.PP
.Vb 1
\& print "<h2>Here are the current settings in this form</h2>";
.Ve
.PP
.Vb 6
\& foreach $key (param) {
\& print "<strong>$key</strong> -> ";
\& @values = param($key);
\& print join(", ",@values),"<br>\en";
\& }
\& }
.Ve
.PP
.Vb 7
\& sub print_tail {
\& print <<END;
\& <hr>
\& <address>Lincoln D. Stein</address><br>
\& <a href="/">Home Page</a>
\& END
\& }
.Ve
.SH "BUGS"
.IX Header "BUGS"
Please report them.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
CGI::Carp, CGI::Fast, CGI::Pretty