CREATING FILL-OUT FORMS:
General note 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.
Another note The default values that you specify for the forms are only
used the first 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.
If you want to change the value of a field from its previous value, you
have two choices:
(1) call the param() method to set it.
(2) use the -override (alias -force) parameter (a new feature in ver-
sion 2.15). This forces the default value to be used, regardless of
the previous value:
print textfield(-name=>'field_name',
-default=>'starting value',
-override=>1,
-size=>50,
-maxlength=>80);
Yet another note By default, the text and labels of form elements are
escaped according to HTML rules. This means that you can safely use
"<CLICK ME>" as the label for a button. However, it also interferes
with your ability to incorporate special HTML character sequences, such
as Á, into your fields. If you wish to turn off automatic
escaping, call the autoEscape() method with a false value immediately
after creating the CGI object:
$query = new CGI;
autoEscape(undef);
A Lurking Trap! Some of the form-element generating methods return mul-
tiple 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:
printf("%s\n",end_form())
end_form() produces several tags, and only the first of them will be
printed because the format only expects one value.
<p>
CREATING AN ISINDEX TAG
print isindex(-action=>$action);
-or-
print isindex($action);
Prints out an <isindex> tag. Not very exciting. The parameter -action
specifies the URL of the script to process the query. The default is
to process the query with the current script.
STARTING AND ENDING A FORM
print start_form(-method=>$method,
-action=>$action,
-enctype=>$encoding);
<... various form stuff ...>
print endform;
-or-
print start_form($method,$action,$encoding);
<... various form stuff ...>
print endform;
start_form() will return a <form> tag with the optional method, action
and form encoding that you specify. The defaults are:
method: POST
action: this script
enctype: application/x-www-form-urlencoded
endform() returns the closing </form> tag.
Start_form()'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:
Note: This method was previously named startform(), and startform() is
still recognized as an alias.
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 CGI scripts and is suit-
able for short fields containing text data. For your convenience,
CGI.pm stores the name of this encoding type in &CGI::URL_ENCODED.
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 "file upload" feature of Netscape 2.0 forms. For your
convenience, CGI.pm stores the name of this encoding type in
&CGI::MULTIPART
Forms that use this type of encoding are not easily interpreted by
CGI scripts unless they use CGI.pm or another library designed to
handle them.
If XHTML is activated (the default), then forms will be automati-
cally created using this type of encoding.
For compatibility, the start_form() method uses the older form of
encoding by default. If you want to use the newer form of encoding by
default, you can call ssttaarrtt_mmuullttiippaarrtt_ffoorrmm(()) instead of ssttaarrtt_ffoorrmm(()).
JAVASCRIPTING: The -name and -onSubmit 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.
Usually the bulk of JavaScript functions are defined in a <script>
block in the HTML header and -onSubmit points to one of these function
call. See start_html() for details.
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:
-name
The name of the field. After submission this name can be used to
retrieve the field's value using the param() method.
-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 syn-
onyms.
-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.
-id A string identifier that can be used to identify this element to
JavaScript and DHTML.
-override
A boolean, which, if true, forces the element to take on the value
specified by -value, overriding the sticky behavior described ear-
lier for the -no_sticky pragma.
-onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect
These are used to assign JavaScript event handlers. See the
JavaScripting section for more details.
Other common arguments are described in the next section. In addition
to these, all attributes described in the HTML specifications are sup-
ported.
CREATING A TEXT FIELD
print textfield(-name=>'field_name',
-value=>'starting value',
-size=>50,
-maxlength=>80);
-or-
print textfield('field_name','starting value',50,80);
textfield() will return a text input field.
Parameters
1. The first parameter is the required name for the field (-name).
2. The optional second parameter is the default starting value for the
field contents (-value, formerly known as -default).
3. The optional third parameter is the size of the field in
characters (-size).
4. The optional fourth parameter is the maximum number of characters
the
field will accept (-maxlength).
As with all these methods, the field will be initialized with its pre-
vious contents from earlier invocations of the script. When the form
is processed, the value of the text field can be retrieved with:
$value = param('foo');
If you want to reset it from its initial value after the script has
been called once, you can do so like this:
param('foo',"I'm taking over this value!");
CREATING A BIG TEXT FIELD
print textarea(-name=>'foo',
-default=>'starting value',
-rows=>10,
-columns=>50);
-or
print textarea('foo','starting value',10,50);
textarea() 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.
CREATING A PASSWORD FIELD
print password_field(-name=>'secret',
-value=>'starting value',
-size=>50,
-maxlength=>80);
-or-
print password_field('secret','starting value',50,80);
password_field() is identical to textfield(), except that its contents
will be starred out on the web page.
CREATING A FILE UPLOAD FIELD
print filefield(-name=>'uploaded_file',
-default=>'starting value',
-size=>50,
-maxlength=>80);
-or-
print filefield('uploaded_file','starting value',50,80);
filefield() will return a file upload field for Netscape 2.0 browsers.
In order to take full advantage of this you must use the new multipart
encoding scheme for the form. You can do this either by calling
ssttaarrtt_ffoorrmm(()) with an encoding type of &CGI::MULTIPART, or by calling
the new method ssttaarrtt_mmuullttiippaarrtt_ffoorrmm(()) instead of vanilla ssttaarrtt_ffoorrmm(()).
Parameters
1. The first parameter is the required name for the field (-name).
2. The optional second parameter is the starting value for the field
contents to be used as the default file name (-default).
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 "sticky" behavior and forgets its previous con-
tents. The starting value field is called for in the HTML specifi-
cation, however, and possibly some browser will eventually provide
support for it.
3. The optional third parameter is the size of the field in characters
(-size).
4. The optional fourth parameter is the maximum number of characters
the field will accept (-maxlength).
When the form is processed, you can retrieve the entered filename by
calling param():
$filename = param('uploaded_file');
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. Regard-
less, the name returned is always the name of the file on the user's
machine, and is unrelated to the name of the temporary file that CGI.pm
creates during upload spooling (see below).
The filename returned is also a file handle. You can read the contents
of the file using standard Perl file reading calls:
# Read a text file and print it out
while (<$filename>) {
print;
}
# Copy a binary file to somewhere safe
open (OUTFILE,">>/usr/local/web/users/feedback");
while ($bytesread=read($filename,$buffer,1024)) {
print OUTFILE $buffer;
}
However, there are problems with the dual nature of the upload fields.
If you "use strict", 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 "no strict" pragma. More seri-
ously, it is possible for the remote user to type garbage into the
upload field, in which case what you get from param() is not a filehan-
dle at all, but a string.
To be safe, use the upload() function (new in version 2.47). When
called with the name of an upload field, upload() returns a filehandle,
or undef if the parameter is not a valid filehandle.
$fh = upload('uploaded_file');
while (<$fh>) {
print;
}
In an list context, upload() will return an array of filehandles. This
makes it possible to create forms that use the same name for multiple
upload fields.
This is the recommended idiom.
When a file is uploaded the browser usually sends along some informa-
tion along with it in the format of headers. The information usually
includes the MIME content type. Future browsers may send other infor-
mation as well (such as modification date and size). To retrieve this
information, call uploadInfo(). It returns a reference to an associa-
tive array containing all the document headers.
$filename = param('uploaded_file');
$type = uploadInfo($filename)->{'Content-Type'};
unless ($type eq 'text/html') {
die "HTML FILES ONLY!";
}
If you are using a machine that recognizes "text" and "binary" 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.
There are occasionally problems involving parsing the uploaded file.
This usually happens when the user presses "Stop" before the upload is
finished. In this case, CGI.pm will return undef for the name of the
uploaded file and set cgi_error() to the string "400 Bad request (mal-
formed multipart POST)". This error message is designed so that you
can incorporate it into a status code to be sent to the browser. Exam-
ple:
$file = upload('uploaded_file');
if (!$file && cgi_error) {
print header(-status=>cgi_error);
exit 0;
}
You are free to create a custom HTML page to complain about the error,
if you wish.
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
UPLOAD_HOOK 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.
$q = CGI->new(\&hook,$data);
sub hook
{
my ($filename, $buffer, $bytes_read, $data) = @_;
print "Read $bytes_read bytes of $filename\n";
}
If using the function-oriented interface, call the CGI::upload_hook()
method before calling param() or any other CGI functions:
CGI::upload_hook(\&hook,$data);
This method is not exported by default. You will have to import it
explicitly if you wish to use it without the CGI:: prefix.
If you are using CGI.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 binmode() on any handle that you create to
write the uploaded file to disk.
JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver,
-onMouseOut and -onSelect parameters are recognized. See textfield()
for details.
CREATING A POPUP MENU
print popup_menu('menu_name',
['eenie','meenie','minie'],
'meenie');
-or-
%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',\%labels,\%attributes);
-or (named parameter style)-
print popup_menu(-name=>'menu_name',
-values=>['eenie','meenie','minie'],
-default=>'meenie',
-labels=>\%labels,
-attributes=>\%attributes);
popup_menu() creates a menu.
1. The required first argument is the menu's name (-name).
2. The required second argument (-values) is an array reference con-
taining 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 "\@foo".
3. 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.
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).
5. The optional fifth parameter (-attributes) is provided to assign
any of the common HTML 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.
When the form is processed, the selected value of the popup menu can be
retrieved using:
$popup_menu_value = param('menu_name');
CREATING AN OPTION GROUP
Named parameter style
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');
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'});
optgroup() creates an option group within a popup menu.
1. The required first argument (-name) is the label attribute of the
optgroup and is not inserted in the parameter list of the query.
2. The required second argument (-values) is an array reference con-
taining 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 \@foo. If you pass a HASH reference, the
keys will be used for the menu values, and the values will be used
for the menu labels (see -labels below).
3. The optional third parameter (-labels) allows you to pass a refer-
ence 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 ("eenie", "meenie" and "minie" in this example). This
is equivalent to using a hash reference for the -values parameter.
4. An optional fourth parameter (-labeled) 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.
5. 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.
See the discussion on optgroup at W3C
(http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
for details.
6. An optional sixth parameter (-attributes) is provided to assign any
of the common HTML 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.
CREATING A SCROLLING LIST
print scrolling_list('list_name',
['eenie','meenie','minie','moe'],
['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
-or-
print scrolling_list('list_name',
['eenie','meenie','minie','moe'],
['eenie','moe'],5,'true',
\%labels,%attributes);
-or-
print scrolling_list(-name=>'list_name',
-values=>['eenie','meenie','minie','moe'],
-default=>['eenie','moe'],
-size=>5,
-multiple=>'true',
-labels=>\%labels,
-attributes=>\%attributes);
scrolling_list() creates a scrolling list.
Parameters:
1. 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.
2. 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 "-defaults" for this
parameter.
3. The optional fourth argument is the size of the list (-size).
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.
5. 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.
6. The optional sixth parameter (-attributes) is provided to assign
any of the common HTML 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.
When this form is processed, all selected list items will be
returned as a list under the parameter name 'list_name'. The val-
ues of the selected items can be retrieved with:
@selected = param('list_name');
CREATING A GROUP OF RELATED CHECKBOXES
print checkbox_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-default=>['eenie','moe'],
-linebreak=>'true',
-labels=>\%labels,
-attributes=>\%attributes);
print checkbox_group('group_name',
['eenie','meenie','minie','moe'],
['eenie','moe'],'true',\%labels,
{'moe'=>{'class'=>'red'}});
HTML3-COMPATIBLE BROWSERS ONLY:
print checkbox_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-rows=2,-columns=>2);
checkbox_group() creates a list of checkboxes that are related by the
same name.
Parameters:
1. 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.
2. 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.
3. 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 hori-
zontal line.
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.
Modern browsers can take advantage of the optional parameters -rows,
and -columns. These parameters cause checkbox_group() to return an
HTML3 compatible table containing the checkbox group formatted with the
specified number of rows and columns. You can provide just the -col-
umns parameter if you wish; checkbox_group will calculate the correct
number of rows for you.
The optional -attributes argument is provided to assign any of the com-
mon HTML 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.
The optional -tabindex 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:
-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
When the form is processed, all checked boxes will be returned as a
list under the parameter name 'group_name'. The values of the "on"
checkboxes can be retrieved with:
@turned_on = param('group_name');
The value returned by checkbox_group() is actually an array of button
elements. You can capture them and use them within tables, lists, or
in other creative ways:
@h = checkbox_group(-name=>'group_name',-values=>\@values);
&use_in_creative_way(@h);
CREATING A STANDALONE CHECKBOX
print checkbox(-name=>'checkbox_name',
-checked=>1,
-value=>'ON',
-label=>'CLICK ME');
-or-
print checkbox('checkbox_name','checked','ON','CLICK ME');
checkbox() is used to create an isolated checkbox that isn't logically
related to any others.
Parameters:
1. 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.
2. The optional second parameter (-checked) specifies that the check-
box is turned on by default. Synonyms are -selected and -on.
3. The optional third parameter (-value) specifies the value of the
checkbox when it is checked. If not provided, the word "on" is
assumed.
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.
The value of the checkbox can be retrieved using:
$turned_on = param('checkbox_name');
CREATING A RADIO BUTTON GROUP
print radio_group(-name=>'group_name',
-values=>['eenie','meenie','minie'],
-default=>'meenie',
-linebreak=>'true',
-labels=>\%labels,
-attributes=>\%attributes);
-or-
print radio_group('group_name',['eenie','meenie','minie'],
'meenie','true',\%labels,\%attributes);
HTML3-COMPATIBLE BROWSERS ONLY:
print radio_group(-name=>'group_name',
-values=>['eenie','meenie','minie','moe'],
-rows=2,-columns=>2);
radio_group() creates a set of logically-related radio buttons (turning
one member of the group on turns the others off)
Parameters:
1. The first argument is the name of the group and is required
(-name).
2. 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 reference in the second argument, either
using an anonymous array, as shown, or by referencing a named array
as in "\@foo".
3. 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 "-" to
start up with no buttons selected.
4. The optional fourth parameter (-linebreak) can be set to 'true' to
put line breaks between the buttons, creating a vertical list.
5. The optional fifth parameter (-labels) is a pointer to an associa-
tive array relating the radio button values to user-visible labels
to be used in the display. If not provided, the values themselves
are displayed.
All modern browsers can take advantage of the optional parameters
-rows, and -columns. These parameters cause radio_group() to return an
HTML3 compatible table containing the radio group formatted with the
specified number of rows and columns. You can provide just the -col-
umns parameter if you wish; radio_group will calculate the correct num-
ber of rows for you.
To include row and column headings in the returned table, you can use
the -rowheader and -colheader parameters. Both of these accept a
pointer to an array of headings to use. The headings are just decora-
tive. They don't reorganize the interpretation of the radio buttons --
they're still a single named unit.
The optional -tabindex 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:
-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
The optional -attributes argument is provided to assign any of the com-
mon HTML 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.
When the form is processed, the selected radio button can be retrieved
using:
$which_radio_button = param('group_name');
The value returned by radio_group() is actually an array of button ele-
ments. You can capture them and use them within tables, lists, or in
other creative ways:
@h = radio_group(-name=>'group_name',-values=>\@values);
&use_in_creative_way(@h);
CREATING A SUBMIT BUTTON
print submit(-name=>'button_name',
-value=>'value');
-or-
print submit('button_name','value');
submit() will create the query submission button. Every form should
have one of these.
Parameters:
1. 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.
2. The second argument (-value) is also optional. This gives the but-
ton a value that will be passed to your script in the query string.
The name will also be used as the user-visible label.
3. 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.
You can figure out which button was pressed by using different values
for each one:
$which_one = param('button_name');
CREATING A RESET BUTTON
print reset
reset() creates the "reset" button. Note that it restores the form to
its value from the last time the script was called, NOT necessarily to
the defaults.
Note that this conflicts with the Perl reset() built-in. Use
CORE::reset() to get the original reset function.
CREATING A DEFAULT BUTTON
print defaults('button_label')
defaults() 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.
CREATING A HIDDEN FIELD
print hidden(-name=>'hidden_name',
-default=>['value1','value2'...]);
-or-
print hidden('hidden_name','value1','value2'...);
hidden() 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.
Parameters:
1. The first argument is required and specifies the name of this field
(-name).
2. The second argument is also required and specifies its value
(-default). In the named parameter style of calling, you can pro-
vide a single value here or a reference to a whole list
Fetch the value of a hidden field this way:
$hidden_value = param('hidden_name');
Note, that just like all the other form elements, the value of a hidden
field is "sticky". 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:
param('hidden_name','new','values','here');
CREATING A CLICKABLE IMAGE BUTTON
print image_button(-name=>'button_name',
-src=>'/source/URL',
-align=>'MIDDLE');
-or-
print image_button('button_name','/source/URL','MIDDLE');
image_button() produces a clickable image. When it's clicked on the
position of the click is returned to your script as "button_name.x" and
"button_name.y", where "button_name" is the name you've assigned to it.
Parameters:
1. The first argument (-name) is required and specifies the name of
this field.
2. The second argument (-src) is also required and specifies the URL
3. The third option (-align, optional) is an alignment type, and may be
TOP, BOTTOM or MIDDLE
Fetch the value of the button this way:
$x = param('button_name.x');
$y = param('button_name.y');
CREATING A JAVASCRIPT ACTION BUTTON
print button(-name=>'button_name',
-value=>'user visible label',
-onClick=>"do_something()");
-or-
print button('button_name',"do_something()");
button() 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 -onClick parameter will be executed. On non-Netscape
browsers this form element will probably not even display.
HTTP COOKIES
Netscape browsers versions 1.1 and higher, and all versions of Internet
Explorer, support a so-called "cookie" designed to help maintain state
within a browser session. CGI.pm has several methods that support
cookies.
A cookie is a name=value pair much like the named parameters in a CGI
query string. CGI scripts create one or more cookies and send them to
the browser in the HTTP header. The browser maintains a list of cook-
ies that belong to a particular Web server, and returns them to the CGI
script during subsequent interactions.
In addition to the required name=value pair, each cookie has several
optional attributes:
1. an expiration time
This is a time/date string (in a special GMT 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 speci-
fied, the cookie will remain active until the user quits the
browser.
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 ".capricorn.com", then the browser will return the cookie to Web
servers running on any of the machines "www.capricorn.com",
"www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
must contain at least two periods to prevent attempts to match on
top level domains like ".edu". If no domain is specified, then the
browser will only return the cookie to servers on the host the
cookie originated from.
3. a path
If you provide a cookie path attribute, the browser will check it
against your script's URL before returning the cookie. For exam-
ple, if you specify the path "/cgi-bin", then the cookie will be
returned to each of the scripts "/cgi-bin/tally.pl",
"/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
but not to the script "/cgi-private/site_admin.pl". By default,
path is set to "/", which causes the cookie to be sent to any CGI
script on your site.
4. a "secure" flag
If the "secure" attribute is set, the cookie will only be sent to
your script if the CGI request is occurring on a secure channel,
such as SSL.
The interface to HTTP cookies is the ccooookkiiee(()) method:
$cookie = cookie(-name=>'sessionID',
-value=>'xyzzy',
-expires=>'+1h',
-path=>'/cgi-bin/database',
-domain=>'.capricorn.org',
-secure=>1);
print header(-cookie=>$cookie);
ccooookkiiee(()) creates a new cookie. Its parameters include:
-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, CGI.pm removes this restriction by escap-
ing and unescaping cookies behind the scenes.
-value
The value of the cookie. This can be any scalar value, array ref-
erence, or even associative array reference. For example, you can
store an entire associative array into a cookie this way:
$cookie=cookie(-name=>'family information',
-value=>\%childrens_ages);
-path
The optional partial path for which this cookie will be valid, as
described above.
-domain
The optional partial domain for which this cookie will be valid, as
described above.
-expires
The optional expiration date for this cookie. The format is as
described in the section on the hheeaaddeerr(()) method:
"+1h" one hour from now
-secure
If set to true, this cookie will only be used within a secure SSL
session.
The cookie created by cookie() must be incorporated into the HTTP
header within the string returned by the header() method:
print header(-cookie=>$my_cookie);
To create multiple cookies, give header() an array reference:
$cookie1 = cookie(-name=>'riddle_name',
-value=>"The Sphynx's Question");
$cookie2 = cookie(-name=>'answers',
-value=>\%answers);
print header(-cookie=>[$cookie1,$cookie2]);
To retrieve a cookie, request it by name by calling cookie() method
without the -value parameter:
use CGI;
$query = new CGI;
$riddle = cookie('riddle_name');
%answers = cookie('answers');
Cookies created with a single scalar value, such as the "riddle_name"
cookie, will be returned in that form. Cookies with array and hash
values can also be retrieved.
The cookie and CGI namespaces are separate. If you have a parameter
named 'answers' and a cookie named 'answers', the values retrieved by
param() and cookie() are independent of each other. However, it's sim-
ple to turn a CGI parameter into a cookie, and vice-versa:
# turn a CGI parameter into a cookie
$c=cookie(-name=>'answers',-value=>[param('answers')]);
# vice-versa
param(-name=>'answers',-value=>[cookie('answers')]);
See the cookie.cgi example script for some ideas on how to use cookies
effectively.
WORKING WITH FRAMES
It's possible for CGI.pm scripts to write into several browser panels
and windows using the HTML 4 frame mechanism. There are three tech-
niques for defining new frames programmatically:
1. Create a <Frameset> document
After writing out the HTTP header, instead of creating a standard
HTML document using the start_html() call, create a <frameset> doc-
ument that defines the frames on the page. Specify your script(s)
(with appropriate parameters) as the SRC for each of the frames.
There is no specific support for creating <frameset> sections in
CGI.pm, but the HTML is very simple to write. See the frame docu-
mentation in Netscape's home pages for details
http://home.netscape.com/assist/net_sites/frames.html
2. Specify the destination for the document in the HTTP header
You may provide a -target parameter to the header() method:
print header(-target=>'ResultsWindow');
This will tell the browser to load the output of your script into
the frame named "ResultsWindow". 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.
3. Specify the destination for the document in the <form> tag
You can specify the frame to load in the FORM tag itself. With
CGI.pm it looks like this:
print start_form(-target=>'ResultsWindow');
When your script is reinvoked by the form, its output will be
loaded into the frame named "ResultsWindow". If one doesn't
already exist a new window will be created.
The script "frameset.cgi" 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.
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 CGI scripting, JavaScript is
quite useful for validating fill-out forms prior to submitting them.
You'll need to know JavaScript in order to use it. There are many good
sources in bookstores and on the web.
The usual way to use JavaScript is to define a set of functions in a
<SCRIPT> block inside the HTML header and then to register event han-
dlers 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 han-
dler, its associated JavaScript code gets called.
The elements that can register event handlers include the <BODY> of an
HTML 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 par-
tial list:
onLoad
The browser is loading the current document. Valid in:
+ The HTML <BODY> section only.
onUnload
The browser is closing the current page or frame. Valid for:
+ The HTML <BODY> section only.
onSubmit
The user has pressed the submit button of a form. This event hap-
pens just before the form is submitted, and your function can
return a value of false in order to abort the submission. Valid
for:
+ Forms only.
onClick
The mouse has clicked on an item in a fill-out form. Valid for:
+ Buttons (including submit, reset, and image buttons)
+ Checkboxes
+ Radio buttons
onChange
The user has changed the contents of a field. Valid for:
+ Text fields
+ Text areas
+ Password fields
+ File fields
+ Popup Menus
+ Scrolling lists
onFocus
The user has selected a field to work with. Valid for:
+ Text fields
+ Text areas
+ Password fields
+ File fields
+ Popup Menus
+ Scrolling lists
onBlur
The user has deselected a field (gone to work somewhere else).
Valid for:
+ Text fields
+ Text areas
+ Password fields
+ File fields
+ Popup Menus
+ Scrolling lists
onSelect
The user has changed the part of a text field that is selected.
Valid for:
+ Text fields
+ Text areas
+ Password fields
+ File fields
onMouseOver
The mouse has moved over an element.
+ Text fields
+ Text areas
+ Password fields
+ File fields
+ Popup Menus
+ Scrolling lists
onMouseOut
The mouse has moved off an element.
+ Text fields
+ Text areas
+ Password fields
+ File fields
+ Popup Menus
+ Scrolling lists
In order to register a JavaScript event handler with an HTML element,
just use the event name as a parameter when you call the corresponding
CGI method. For example, to have your validateAge() JavaScript code
executed every time the textfield named "age" changes, generate the
field like this:
print textfield(-name=>'age',-onChange=>"validateAge(this)");
This example assumes that you've already declared the validateAge()
function by incorporating it into a <SCRIPT> block. The CGI.pm
start_html() method provides a convenient way to create this section.
Similarly, you can create a form that checks itself over for consis-
tency and alerts the user if some essential value is missing by creat-
ing it this way:
print startform(-onSubmit=>"validateMe(this)");
See the javascript.cgi script for a demonstration of how this all
works.
LIMITED SUPPORT FOR CASCADING STYLE SHEETS
CGI.pm has limited support for HTML3's cascading style sheets (css).
To incorporate a stylesheet into your document, pass the start_html()
method a -style parameter. The value of this parameter may be a
scalar, in which case it is treated as the source URL for the
stylesheet, or it may be a hash reference. In the latter case you
should provide the hash with one or more of -src or -code. -src points
to a URL where an externally-defined stylesheet can be found. -code
points to a scalar value to be incorporated into a <style> section.
Style definitions in -code override similarly-named ones in -src, hence
the name "cascading."
You may also specify the type of the stylesheet by adding the optional
-type parameter to the hash pointed to by -style. If not specified,
the style defaults to 'text/css'.
To refer to a style within the body of your document, add the -class
parameter to any HTML element:
print h1({-class=>'Fancy'},'Welcome to the Party');
Or define styles on the fly with the -style parameter:
print h1({-style=>'Color: red;'},'Welcome to Hell');
You may also use the new ssppaann(()) element to apply a style to a section
of text:
print span({-style=>'Color: red;'},
h1('Welcome to Hell'),
"Where did that handbasket get to?"
);
Note that you must import the ":html3" definitions to have the ssppaann(())
method available. Here's a quick and dirty example of using CSS's.
See the CSS specification at http://www.w3.org/pub/WWW/TR/Wd-css-1.html
for more information.
use CGI qw/:standard :html3/;
#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;
Pass an array reference to -code or -src in order to incorporate multi-
ple stylesheets into your document.
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:
print start_html (-STYLE => {-verbatim => '@import url("/server-com-
mon/css/'.$cssFile.'");',
-src => '/server-common/css/core.css'});
</blockquote></pre>
This will generate an HTML header that contains this:
<link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
<style type="text/css">
@import url("/server-common/css/main.css");
</style>
Any additional arguments passed in the -style value will be incorpo-
rated into the <link> tag. For example:
start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
-media => 'all'});
This will give:
<link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
<link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
<p>
To make more complicated <link> tags, use the Link() function and pass
it to start_html() in the -head argument, as in:
@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=>\@h})
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 vari-
ables). You can pass keywords like this:
your_script.pl keyword1 keyword2 keyword3
or this:
your_script.pl keyword1+keyword2+keyword3
or this:
your_script.pl name1=value1 name2=value2
or this:
your_script.pl name1=value1&name2=value2
To turn off this feature, use the -no_debug pragma.
To test the POST 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.
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:
your_script.pl "name1='I am a long value'" "name2=two\ words"
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
(?):
your_script.pl /your/path/here?name1=value1&name2=value2
DUMPING OUT ALL THE NAME/VALUE PAIRS
The Dump() 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:
print Dump
Produces something that looks like:
<ul>
<li>name1
<ul>
<li>value1
<li>value2
</ul>
<li>name2
<ul>
<li>value1
</ul>
</ul>
As a shortcut, you can interpolate the entire CGI object into a string
and it will be replaced with the a nice HTML dump shown above:
$query=new CGI;
print "<h2>Current Values</h2> $query\n";
FETCHING ENVIRONMENT VARIABLES
Some of the more useful environment variables can be fetched through
this interface. The methods are as follows:
AAcccceepptt(())
Return a list of MIME types that the remote browser accepts. If you
give this method a single argument corresponding to a MIME type, as
in Accept('text/html'), it will return a floating point value cor-
responding 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.
Note that the capitalization changed between version 2.43 and 2.44
in order to avoid conflict with Perl's accept() function.
rraaww_ccooookkiiee(())
Returns the HTTP_COOKIE variable, an HTTP 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 cookie() for
ways of setting and retrieving cooked cookies.
Called with no parameters, raw_cookie() returns the packed cookie
structure. You can separate it into individual cookies by split-
ting on the character sequence "; ". Called with the name of a
cookie, retrieves the unescaped form of the cookie. You can use
the regular cookie() method to get the names, or use the
raw_fetch() method from the CGI::Cookie module.
uusseerr_aaggeenntt(())
Returns the HTTP_USER_AGENT 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);
ppaatthh_iinnffoo(())
Returns additional path information from the script URL. E.G.
fetching /cgi-bin/your_script/additional/stuff will result in
path_info() returning "/additional/stuff".
NOTE: The Microsoft Internet Information Server is broken with
respect to additional path information. If you use the Perl DLL
library, the IIS server will attempt to execute the additional path
information as a Perl script. If you use the ordinary file associ-
ations mapping, the path information will be present in the envi-
ronment, but incorrect. The best thing to do is to avoid using
additional path information in CGI scripts destined for use with
IIS.
ppaatthh_ttrraannssllaatteedd(())
As per path_info() but returns the additional path information
translated into a physical path, e.g.
"/usr/local/etc/httpd/htdocs/additional/stuff".
The Microsoft IIS is broken with respect to the translated path as
well.
rreemmoottee_hhoosstt(())
Returns either the remote host name or IP address. if the former
is unavailable.
ssccrriipptt_nnaammee(()) Return the script name as a partial URL, for self-refer-
ing scripts.
rreeffeerreerr(())
Return the URL of the page the browser was viewing prior to fetch-
ing your script. Not available for all browsers.
auth_type ()
Return the authorization/verification method in use for this
script, if any.
server_name ()
Returns the name of the server, usually the machine's host name.
virtual_host ()
When using virtual hosts, returns the name of the host that the
browser attempted to contact
server_port ()
Return the port that the server is listening on.
virtual_port ()
Like server_port() except that it takes virtual hosts into account.
Use this when running with virtual hosts.
server_software ()
Returns the server software and version number.
remote_user ()
Return the authorization/verification name used for user verifica-
tion, if this script is protected.
user_name ()
Attempt to obtain the remote user's name, using a variety of dif-
ferent techniques. This only works with older browsers such as
Mosaic. Newer browsers do not report the user name for privacy
reasons!
rreeqquueesstt_mmeetthhoodd(())
Returns the method used to access your script, usually one of
'POST', 'GET' or 'HEAD'.
ccoonntteenntt_ttyyppee(())
Returns the content_type of data submitted in a POST, generally
multipart/form-data or application/x-www-form-urlencoded
hhttttpp(())
Called with no arguments returns the list of HTTP environment vari-
ables, including such things as HTTP_USER_AGENT, HTTP_ACCEPT_LAN-
GUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the like-named
HTTP header fields in the request. Called with the name of an HTTP
header field, returns its value. Capitalization and the use of
hyphens versus underscores are not significant.
For example, all three of these examples are equivalent:
$requested_language = http('Accept-language');
$requested_language = http('Accept_language');
$requested_language = http('HTTP_ACCEPT_LANGUAGE');
hhttttppss(())
The same as http(), but operates on the HTTPS environment variables
present when the SSL protocol is in effect. Can be used to deter-
mine whether SSL is turned on.
USING NPH SCRIPTS
NPH, or "no-parsed-header", scripts bypass the server completely by
sending the complete HTTP header directly to the browser. This has
slight performance benefits, but is of most use for taking advantage of
HTTP extensions that are not directly supported by your server, such as
server push and PICS headers.
Servers use a variety of conventions for designating CGI scripts as
NPH. Many Unix servers look at the beginning of the script's name for
the prefix "nph-". The Macintosh WebSTAR server and Microsoft's Inter-
net Information Server, in contrast, try to decide whether a program is
an NPH script by examining the first line of script output.
CGI.pm supports NPH scripts with a special NPH mode. When in this
mode, CGI.pm will output the necessary extra header information when
the header() and redirect() methods are called.
The Microsoft Internet Information Server requires NPH mode. As of
version 2.30, CGI.pm will automatically detect when the script is run-
ning under IIS 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 NPH scripts, including the ability to redirect while setting a
cookie, b<do not work at all> on IIS without a special patch from
Microsoft. See http://support.microsoft.com/support/kb/arti-
cles/Q280/3/41.ASP: Non-Parsed Headers Stripped From CGI Applications
That Have nph- Prefix in Name.
In the use statement
Simply add the "-nph" pragmato the list of symbols to be imported
into your script:
use CGI qw(:standard -nph)
By calling the nnpphh(()) method:
Call nnpphh(()) with a non-zero parameter at any point after using
CGI.pm in your program.
CGI->nph(1)
By using -nph parameters
in the hheeaaddeerr(()) and rreeddiirreecctt(()) statements:
print header(-nph=>1);
Server Push
CGI.pm provides four simple functions for producing multipart documents
of the type needed to implement server push. These functions were gra-
ciously provided by Ed Jordan <ed@fidalgo.net>. To import these into
your namespace, you must import the ":push" set. You are also advised
to put the script into NPH mode and to set $| to 1 to avoid buffering
problems.
Here is a simple script that demonstrates server push:
#!/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),"\n";
if ($_ < 4) {
print multipart_end;
} else {
print multipart_final;
}
sleep 1;
}
This script initializes server push by calling mmuullttiippaarrtt_iinniitt(()). It
then enters a loop in which it begins a new multipart section by call-
ing mmuullttiippaarrtt_ssttaarrtt(()), prints the current local time, and ends a multi-
part section with mmuullttiippaarrtt_eenndd(()). It then sleeps a second, and begins
again. On the final iteration, it ends the multipart section with mmuull--
ttiippaarrtt_ffiinnaall(()) rather than with mmuullttiippaarrtt_eenndd(()).
multipart_init()
multipart_init(-boundary=>$boundary);
Initialize the multipart system. The -boundary argument specifies
what MIME boundary string to use to separate parts of the document.
If not provided, CGI.pm chooses a reasonable boundary for you.
multipart_start()
multipart_start(-type=>$type)
Start a new part of the multipart document using the specified MIME
type. If not specified, text/html is assumed.
multipart_end()
multipart_end()
End a part. You must remember to call multipart_end() once for
each multipart_start(), except at the end of the last part of the
multipart document when multipart_final() should be called instead
of multipart_end().
multipart_final()
multipart_final()
End all parts. You should call multipart_final() rather than mul-
tipart_end() at the end of the last part of the multipart document.
Users interested in server push applications should also have a look at
the CGI::Push module.
Only Netscape Navigator supports server push. Internet Explorer
browsers do not.
Avoiding Denial of Service Attacks
A potential problem with CGI.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 CGI script a huge POST of many
megabytes. CGI.pm will attempt to read the entire POST into a vari-
able, growing hugely in size until it runs out of memory. While the
script attempts to allocate the memory the system may slow down dramat-
ically. This is a form of denial of service attack.
Another possible attack is for the remote user to force CGI.pm to
accept a huge file upload. CGI.pm will accept the upload and store it
in a temporary directory even if your script doesn't expect to receive
an uploaded file. CGI.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.
The best way to avoid denial of service attacks is to limit the amount
of memory, CPU time and disk space that CGI scripts can use. Some Web
servers come with built-in facilities to accomplish this. In other
cases, you can use the shell limit or ulimit commands to put ceilings
on CGI resource usage.
CGI.pm also has some simple built-in protections against denial of ser-
vice attacks, but you must activate them before you can use them.
These take the form of two global variables in the CGI name space:
$CGI::POST_MAX
If set to a non-negative integer, this variable puts a ceiling on
the size of POSTings, in bytes. If CGI.pm detects a POST 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.
$CGI::DISABLE_UPLOADS
If set to a non-zero value, this will disable file uploads com-
pletely. Other fill-out form values will work as usual.
You can use these variables in either of two ways.
1. On a script-by-script basis
Set the variable at the top of the script, right after the "use"
statement:
use CGI qw/:standard/;
use CGI::Carp 'fatalsToBrowser';
$CGI::POST_MAX=1024 * 100; # max 100K posts
$CGI::DISABLE_UPLOADS = 1; # no uploads
2. Globally for all scripts
Open up CGI.pm, find the definitions for $POST_MAX and $DIS-
ABLE_UPLOADS, and set them to the desired values. You'll find them
towards the top of the file in a subroutine named initialize_glob-
als().
An attempt to send a POST larger than $POST_MAX bytes will cause
param() to return an empty CGI parameter list. You can test for this
event by checking cgi_error(), either after you create the CGI object
or, if you are using the function-oriented interface, call <param()>
for the first time. If the POST was intercepted, then cgi_error() will
return the message "413 POST too large".
This error message is actually defined by the HTTP protocol, and is
designed to be returned to the browser as the CGI script's status
code. For example:
$uploaded_file = param('upload');
if (!$uploaded_file && cgi_error()) {
print header(-status=>cgi_error());
exit 0;
}
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 HTML page that
warns the user of the problem.
COMPATIBILITY WITH CGI-LIB.PL
To make it easier to port existing programs that use cgi-lib.pl the
compatibility routine "ReadParse" is provided. Porting is simple:
OLD VERSION
require "cgi-lib.pl";
&ReadParse;
print "The value of the antique is $in{antique}.\n";
NEW VERSION
use CGI;
CGI::ReadParse();
print "The value of the antique is $in{antique}.\n";
CGI.pm's ReadParse() routine creates a tied variable named %in, which
can be accessed to obtain the query variables. Like ReadParse, you can
also provide your own variable. Infrequently used features of Read-
Parse, such as the creation of @in and $in variables, are not sup-
ported.
Once you use ReadParse, you can retrieve the query object itself this
way:
$q = $in{CGI};
print textfield(-name=>'wow',
-value=>'does this really work?');
This allows you to start using the more interesting features of CGI.pm
without rewriting your old scripts from scratch.
AUTHOR INFORMATION
Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
Address bug reports and comments to: lstein@cshl.org. When sending bug
reports, please provide the version of CGI.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 brow-
ers as well.
CREDITS
Thanks very much to:
Matt Heffron (heffron@falstaff.css.beckman.com)
James Taylor (james.taylor@srs.gov)
Scott Anguish <sanguish@digifix.com>
Mike Jewell (mlj3u@virginia.edu)
Timothy Shimmin (tes@kbs.citri.edu.au)
Joergen Haegg (jh@axis.se)
Laurent Delfosse (delfosse@delfosse.com)
Richard Resnick (applepi1@aol.com)
Craig Bishop (csb@barwonwater.vic.gov.au)
Tony Curtis (tc@vcpc.univie.ac.at)
Tim Bunce (Tim.Bunce@ig.co.uk)
Tom Christiansen (tchrist@convex.com)
Andreas Koenig (k@franz.ww.TU-Berlin.DE)
Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
Stephen Dahmen (joyfire@inxpress.net)
Ed Jordan (ed@fidalgo.net)
David Alan Pisoni (david@cnation.com)
Doug MacEachern (dougm@opengroup.org)
Robin Houston (robin@oneworld.org)
...and many many more...
for suggestions and bug fixes.
A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
#!/usr/local/bin/perl
use CGI ':standard';
print header;
print start_html("Example CGI.pm Form");
print "<h1> Example CGI.pm Form</h1>\n";
print_prompt();
do_work();
print_tail();
print end_html;
sub print_prompt {
print start_form;
print "<em>What's your name?</em><br>";
print textfield('name');
print checkbox('Not my real name');
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]);
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');
print "<p><em>What's your favorite color?</em> ";
print popup_menu(-name=>'Color',
-values=>['black','brown','red','yellow'],
-default=>'red');
print hidden('Reference','Monty Python and the Holy Grail');
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');
print "<p><em>Any parting comments?</em><br>";
print textarea(-name=>'Comments',
-rows=>10,
-columns=>50);
print "<p>",reset;
print submit('Action','Shout');
print submit('Action','Scream');
print endform;
print "<hr>\n";
}
sub do_work {
my(@values,$key);
print "<h2>Here are the current settings in this form</h2>";
foreach $key (param) {
print "<strong>$key</strong> -> ";
@values = param($key);
print join(", ",@values),"<br>\n";
}
}
sub print_tail {
print <<END;
<hr>
<address>Lincoln D. Stein</address><br>
<a href="/">Home Page</a>
END
}
BUGS
Please report them.
SEE ALSO
CGI::Carp, CGI::Fast, CGI::Pretty
perl v5.8.8 2006-06-14 CGI(3)
See also Apache::ASP::CGI::Table(3)
See also CGI::Apache(3)
See also CGI::Carp(3)
See also CGI::Cookie(3)
See also CGI::Fast(3)
See also CGI::Pretty(3)
See also CGI::Push(3)
See also CGI::Switch(3)
See also CGI::Util(3)
See also SOAP::Transport::HTTP::CGI(3)
Man(1) output converted with
man2html