1CGI(3pm)               Perl Programmers Reference Guide               CGI(3pm)
2
3
4

NAME

6       CGI - Handle Common Gateway Interface requests and responses
7

SYNOPSIS

9           use CGI;
10
11           my $q = CGI->new;
12
13           # Process an HTTP request
14            @values  = $q->param('form_field');
15
16            $fh      = $q->upload('file_field');
17
18            $riddle  = $query->cookie('riddle_name');
19            %answers = $query->cookie('answers');
20
21           # Prepare various HTTP responses
22           print $q->header();
23           print $q->header('application/json');
24
25               $cookie1 = $q->cookie(-name=>'riddle_name', -value=>"The Sphynx's Question");
26               $cookie2 = $q->cookie(-name=>'answers', -value=>\%answers);
27           print $q->header(
28               -type    => 'image/gif',
29               -expires => '+3d',
30               -cookie  => [$cookie1,$cookie2]
31               );
32
33          print  $q->redirect('http://somewhere.else/in/movie/land');
34

DESCRIPTION

36       CGI.pm is a stable, complete and mature solution for processing and
37       preparing HTTP requests and responses.  Major features including
38       processing form submissions, file uploads, reading and writing cookies,
39       query string generation and manipulation, and processing and preparing
40       HTTP headers. Some HTML generation utilities are included as well.
41
42       CGI.pm performs very well in in a vanilla CGI.pm environment and also
43       comes with built-in support for mod_perl and mod_perl2 as well as
44       FastCGI.
45
46       It has the benefit of having developed and refined over 10 years with
47       input from dozens of contributors and being deployed on thousands of
48       websites.  CGI.pm has been included in the Perl distribution since Perl
49       5.4, and has become a de-facto standard.
50
51   PROGRAMMING STYLE
52       There are two styles of programming with CGI.pm, an object-oriented
53       style and a function-oriented style.  In the object-oriented style you
54       create one or more CGI objects and then use object methods to create
55       the various elements of the page.  Each CGI object starts out with the
56       list of named parameters that were passed to your CGI script by the
57       server.  You can modify the objects, save them to a file or database
58       and recreate them.  Because each object corresponds to the "state" of
59       the CGI script, and because each object's parameter list is independent
60       of the others, this allows you to save the state of the script and
61       restore it later.
62
63       For example, using the object oriented style, here is how you create a
64       simple "Hello World" HTML page:
65
66          #!/usr/local/bin/perl -w
67          use CGI;                             # load CGI routines
68          $q = CGI->new;                        # create new CGI object
69          print $q->header,                    # create the HTTP header
70                $q->start_html('hello world'), # start the HTML
71                $q->h1('hello world'),         # level 1 header
72                $q->end_html;                  # end the HTML
73
74       In the function-oriented style, there is one default CGI object that
75       you rarely deal with directly.  Instead you just call functions to
76       retrieve CGI parameters, create HTML tags, manage cookies, and so on.
77       This provides you with a cleaner programming interface, but limits you
78       to using one CGI object at a time.  The following example prints the
79       same page, but uses the function-oriented interface.  The main
80       differences are that we now need to import a set of functions into our
81       name space (usually the "standard" functions), and we don't need to
82       create the CGI object.
83
84          #!/usr/local/bin/perl
85          use CGI qw/:standard/;           # load standard CGI routines
86          print header,                    # create the HTTP header
87                start_html('hello world'), # start the HTML
88                h1('hello world'),         # level 1 header
89                end_html;                  # end the HTML
90
91       The examples in this document mainly use the object-oriented style.
92       See HOW TO IMPORT FUNCTIONS for important information on function-
93       oriented programming in CGI.pm
94
95   CALLING CGI.PM ROUTINES
96       Most CGI.pm routines accept several arguments, sometimes as many as 20
97       optional ones!  To simplify this interface, all routines use a named
98       argument calling style that looks like this:
99
100          print $q->header(-type=>'image/gif',-expires=>'+3d');
101
102       Each argument name is preceded by a dash.  Neither case nor order
103       matters in the argument list.  -type, -Type, and -TYPE are all
104       acceptable.  In fact, only the first argument needs to begin with a
105       dash.  If a dash is present in the first argument, CGI.pm assumes
106       dashes for the subsequent ones.
107
108       Several routines are commonly called with just one argument.  In the
109       case of these routines you can provide the single argument without an
110       argument name.  header() happens to be one of these routines.  In this
111       case, the single argument is the document type.
112
113          print $q->header('text/html');
114
115       Other such routines are documented below.
116
117       Sometimes named arguments expect a scalar, sometimes a reference to an
118       array, and sometimes a reference to a hash.  Often, you can pass any
119       type of argument and the routine will do whatever is most appropriate.
120       For example, the param() routine is used to set a CGI parameter to a
121       single or a multi-valued value.  The two cases are shown below:
122
123          $q->param(-name=>'veggie',-value=>'tomato');
124          $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
125
126       A large number of routines in CGI.pm actually aren't specifically
127       defined in the module, but are generated automatically as needed.
128       These are the "HTML shortcuts," routines that generate HTML tags for
129       use in dynamically-generated pages.  HTML tags have both attributes
130       (the attribute="value" pairs within the tag itself) and contents (the
131       part between the opening and closing pairs.)  To distinguish between
132       attributes and contents, CGI.pm uses the convention of passing HTML
133       attributes as a hash reference as the first argument, and the contents,
134       if any, as any subsequent arguments.  It works out like this:
135
136          Code                           Generated HTML
137          ----                           --------------
138          h1()                           <h1>
139          h1('some','contents');         <h1>some contents</h1>
140          h1({-align=>left});            <h1 align="LEFT">
141          h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
142
143       HTML tags are described in more detail later.
144
145       Many newcomers to CGI.pm are puzzled by the difference between the
146       calling conventions for the HTML shortcuts, which require curly braces
147       around the HTML tag attributes, and the calling conventions for other
148       routines, which manage to generate attributes without the curly
149       brackets.  Don't be confused.  As a convenience the curly braces are
150       optional in all but the HTML shortcuts.  If you like, you can use curly
151       braces when calling any routine that takes named arguments.  For
152       example:
153
154          print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
155
156       If you use the -w switch, you will be warned that some CGI.pm argument
157       names conflict with built-in Perl functions.  The most frequent of
158       these is the -values argument, used to create multi-valued menus, radio
159       button clusters and the like.  To get around this warning, you have
160       several choices:
161
162       1.  Use another name for the argument, if one is available.  For
163           example, -value is an alias for -values.
164
165       2.  Change the capitalization, e.g. -Values
166
167       3.  Put quotes around the argument name, e.g. '-values'
168
169       Many routines will do something useful with a named argument that it
170       doesn't recognize.  For example, you can produce non-standard HTTP
171       header fields by providing them as named arguments:
172
173         print $q->header(-type  =>  'text/html',
174                          -cost  =>  'Three smackers',
175                          -annoyance_level => 'high',
176                          -complaints_to   => 'bit bucket');
177
178       This will produce the following nonstandard HTTP header:
179
180          HTTP/1.0 200 OK
181          Cost: Three smackers
182          Annoyance-level: high
183          Complaints-to: bit bucket
184          Content-type: text/html
185
186       Notice the way that underscores are translated automatically into
187       hyphens.  HTML-generating routines perform a different type of
188       translation.
189
190       This feature allows you to keep up with the rapidly changing HTTP and
191       HTML "standards".
192
193   CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
194            $query = CGI->new;
195
196       This will parse the input (from both POST and GET methods) and store it
197       into a perl5 object called $query.
198
199       Any filehandles from file uploads will have their position reset to the
200       beginning of the file.
201
202   CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
203            $query = CGI->new(INPUTFILE);
204
205       If you provide a file handle to the new() method, it will read
206       parameters from the file (or STDIN, or whatever).  The file can be in
207       any of the forms describing below under debugging (i.e. a series of
208       newline delimited TAG=VALUE pairs will work).  Conveniently, this type
209       of file is created by the save() method (see below).  Multiple records
210       can be saved and restored.
211
212       Perl purists will be pleased to know that this syntax accepts
213       references to file handles, or even references to filehandle globs,
214       which is the "official" way to pass a filehandle:
215
216           $query = CGI->new(\*STDIN);
217
218       You can also initialize the CGI object with a FileHandle or IO::File
219       object.
220
221       If you are using the function-oriented interface and want to initialize
222       CGI state from a file handle, the way to do this is with
223       restore_parameters().  This will (re)initialize the default CGI object
224       from the indicated file handle.
225
226           open (IN,"test.in") || die;
227           restore_parameters(IN);
228           close IN;
229
230       You can also initialize the query object from a hash reference:
231
232           $query = CGI->new( {'dinosaur'=>'barney',
233                              'song'=>'I love you',
234                              'friends'=>[qw/Jessica George Nancy/]}
235                           );
236
237       or from a properly formatted, URL-escaped query string:
238
239           $query = CGI->new('dinosaur=barney&color=purple');
240
241       or from a previously existing CGI object (currently this clones the
242       parameter list, but none of the other object-specific fields, such as
243       autoescaping):
244
245           $old_query = CGI->new;
246           $new_query = CGI->new($old_query);
247
248       To create an empty query, initialize it from an empty string or hash:
249
250          $empty_query = CGI->new("");
251
252              -or-
253
254          $empty_query = CGI->new({});
255
256   FETCHING A LIST OF KEYWORDS FROM THE QUERY:
257            @keywords = $query->keywords
258
259       If the script was invoked as the result of an <ISINDEX> search, the
260       parsed keywords can be obtained as an array using the keywords()
261       method.
262
263   FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
264            @names = $query->param
265
266       If the script was invoked with a parameter list (e.g.
267       "name1=value1&name2=value2&name3=value3"), the param() method will
268       return the parameter names as a list.  If the script was invoked as an
269       <ISINDEX> script and contains a string without ampersands (e.g.
270       "value1+value2+value3") , there will be a single parameter named
271       "keywords" containing the "+"-delimited keywords.
272
273       NOTE: As of version 1.5, the array of parameter names returned will be
274       in the same order as they were submitted by the browser.  Usually this
275       order is the same as the order in which the parameters are defined in
276       the form (however, this isn't part of the spec, and so isn't
277       guaranteed).
278
279   FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
280           @values = $query->param('foo');
281
282                     -or-
283
284           $value = $query->param('foo');
285
286       Pass the param() method a single argument to fetch the value of the
287       named parameter. If the parameter is multivalued (e.g. from multiple
288       selections in a scrolling list), you can ask to receive an array.
289       Otherwise the method will return a single value.
290
291       If a value is not given in the query string, as in the queries
292       "name1=&name2=", it will be returned as an empty string.
293
294       If the parameter does not exist at all, then param() will return undef
295       in a scalar context, and the empty list in a list context.
296
297   SETTING THE VALUE(S) OF A NAMED PARAMETER:
298           $query->param('foo','an','array','of','values');
299
300       This sets the value for the named parameter 'foo' to an array of
301       values.  This is one way to change the value of a field AFTER the
302       script has been invoked once before.  (Another way is with the
303       -override parameter accepted by all methods that generate form
304       elements.)
305
306       param() also recognizes a named parameter style of calling described in
307       more detail later:
308
309           $query->param(-name=>'foo',-values=>['an','array','of','values']);
310
311                                     -or-
312
313           $query->param(-name=>'foo',-value=>'the value');
314
315   APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
316          $query->append(-name=>'foo',-values=>['yet','more','values']);
317
318       This adds a value or list of values to the named parameter.  The values
319       are appended to the end of the parameter if it already exists.
320       Otherwise the parameter is created.  Note that this method only
321       recognizes the named argument calling syntax.
322
323   IMPORTING ALL PARAMETERS INTO A NAMESPACE:
324          $query->import_names('R');
325
326       This creates a series of variables in the 'R' namespace.  For example,
327       $R::foo, @R:foo.  For keyword lists, a variable @R::keywords will
328       appear.  If no namespace is given, this method will assume 'Q'.
329       WARNING:  don't import anything into 'main'; this is a major security
330       risk!!!!
331
332       NOTE 1: Variable names are transformed as necessary into legal Perl
333       variable names.  All non-legal characters are transformed into
334       underscores.  If you need to keep the original names, you should use
335       the param() method instead to access CGI variables by name.
336
337       NOTE 2: In older versions, this method was called import().  As of
338       version 2.20, this name has been removed completely to avoid conflict
339       with the built-in Perl module import operator.
340
341   DELETING A PARAMETER COMPLETELY:
342           $query->delete('foo','bar','baz');
343
344       This completely clears a list of parameters.  It sometimes useful for
345       resetting parameters that you don't want passed down between script
346       invocations.
347
348       If you are using the function call interface, use "Delete()" instead to
349       avoid conflicts with Perl's built-in delete operator.
350
351   DELETING ALL PARAMETERS:
352          $query->delete_all();
353
354       This clears the CGI object completely.  It might be useful to ensure
355       that all the defaults are taken when you create a fill-out form.
356
357       Use Delete_all() instead if you are using the function call interface.
358
359   HANDLING NON-URLENCODED ARGUMENTS
360       If POSTed data is not of type application/x-www-form-urlencoded or
361       multipart/form-data, then the POSTed data will not be processed, but
362       instead be returned as-is in a parameter named POSTDATA.  To retrieve
363       it, use code like this:
364
365          my $data = $query->param('POSTDATA');
366
367       Likewise if PUTed data can be retrieved with code like this:
368
369          my $data = $query->param('PUTDATA');
370
371       (If you don't know what the preceding means, don't worry about it.  It
372       only affects people trying to use CGI for XML processing and other
373       specialized tasks.)
374
375   DIRECT ACCESS TO THE PARAMETER LIST:
376          $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
377          unshift @{$q->param_fetch(-name=>'address')},'George Munster';
378
379       If you need access to the parameter list in a way that isn't covered by
380       the methods given in the previous sections, you can obtain a direct
381       reference to it by calling the param_fetch() method with the name of
382       the parameter.  This will return an array reference to the named
383       parameter, which you then can manipulate in any way you like.
384
385       You can also use a named argument style using the -name argument.
386
387   FETCHING THE PARAMETER LIST AS A HASH:
388           $params = $q->Vars;
389           print $params->{'address'};
390           @foo = split("\0",$params->{'foo'});
391           %params = $q->Vars;
392
393           use CGI ':cgi-lib';
394           $params = Vars;
395
396       Many people want to fetch the entire parameter list as a hash in which
397       the keys are the names of the CGI parameters, and the values are the
398       parameters' values.  The Vars() method does this.  Called in a scalar
399       context, it returns the parameter list as a tied hash reference.
400       Changing a key changes the value of the parameter in the underlying CGI
401       parameter list.  Called in a list context, it returns the parameter
402       list as an ordinary hash.  This allows you to read the contents of the
403       parameter list, but not to change it.
404
405       When using this, the thing you must watch out for are multivalued CGI
406       parameters.  Because a hash cannot distinguish between scalar and list
407       context, multivalued parameters will be returned as a packed string,
408       separated by the "\0" (null) character.  You must split this packed
409       string in order to get at the individual values.  This is the
410       convention introduced long ago by Steve Brenner in his cgi-lib.pl
411       module for Perl version 4.
412
413       If you wish to use Vars() as a function, import the :cgi-lib set of
414       function calls (also see the section on CGI-LIB compatibility).
415
416   SAVING THE STATE OF THE SCRIPT TO A FILE:
417           $query->save(\*FILEHANDLE)
418
419       This will write the current state of the form to the provided
420       filehandle.  You can read it back in by providing a filehandle to the
421       new() method.  Note that the filehandle can be a file, a pipe, or
422       whatever!
423
424       The format of the saved file is:
425
426               NAME1=VALUE1
427               NAME1=VALUE1'
428               NAME2=VALUE2
429               NAME3=VALUE3
430               =
431
432       Both name and value are URL escaped.  Multi-valued CGI parameters are
433       represented as repeated names.  A session record is delimited by a
434       single = symbol.  You can write out multiple records and read them back
435       in with several calls to new.  You can do this across several sessions
436       by opening the file in append mode, allowing you to create primitive
437       guest books, or to keep a history of users' queries.  Here's a short
438       example of creating multiple session records:
439
440          use CGI;
441
442          open (OUT,'>>','test.out') || die;
443          $records = 5;
444          for (0..$records) {
445              my $q = CGI->new;
446              $q->param(-name=>'counter',-value=>$_);
447              $q->save(\*OUT);
448          }
449          close OUT;
450
451          # reopen for reading
452          open (IN,'<','test.out') || die;
453          while (!eof(IN)) {
454              my $q = CGI->new(\*IN);
455              print $q->param('counter'),"\n";
456          }
457
458       The file format used for save/restore is identical to that used by the
459       Whitehead Genome Center's data exchange format "Boulderio", and can be
460       manipulated and even databased using Boulderio utilities.  See
461
462         http://stein.cshl.org/boulder/
463
464       for further details.
465
466       If you wish to use this method from the function-oriented (non-OO)
467       interface, the exported name for this method is save_parameters().
468
469   RETRIEVING CGI ERRORS
470       Errors can occur while processing user input, particularly when
471       processing uploaded files.  When these errors occur, CGI will stop
472       processing and return an empty parameter list.  You can test for the
473       existence and nature of errors using the cgi_error() function.  The
474       error messages are formatted as HTTP status codes. You can either
475       incorporate the error text into an HTML page, or use it as the value of
476       the HTTP status:
477
478           my $error = $q->cgi_error;
479           if ($error) {
480               print $q->header(-status=>$error),
481                     $q->start_html('Problems'),
482                     $q->h2('Request not processed'),
483                     $q->strong($error);
484               exit 0;
485           }
486
487       When using the function-oriented interface (see the next section),
488       errors may only occur the first time you call param(). Be ready for
489       this!
490
491   USING THE FUNCTION-ORIENTED INTERFACE
492       To use the function-oriented interface, you must specify which CGI.pm
493       routines or sets of routines to import into your script's namespace.
494       There is a small overhead associated with this importation, but it
495       isn't much.
496
497          use CGI <list of methods>;
498
499       The listed methods will be imported into the current package; you can
500       call them directly without creating a CGI object first.  This example
501       shows how to import the param() and header() methods, and then use them
502       directly:
503
504          use CGI 'param','header';
505          print header('text/plain');
506          $zipcode = param('zipcode');
507
508       More frequently, you'll import common sets of functions by referring to
509       the groups by name.  All function sets are preceded with a ":"
510       character as in ":html3" (for tags defined in the HTML 3 standard).
511
512       Here is a list of the function sets you can import:
513
514       :cgi
515           Import all CGI-handling methods, such as param(), path_info() and
516           the like.
517
518       :form
519           Import all fill-out form generating methods, such as textfield().
520
521       :html2
522           Import all methods that generate HTML 2.0 standard elements.
523
524       :html3
525           Import all methods that generate HTML 3.0 elements (such as
526           <table>, <super> and <sub>).
527
528       :html4
529           Import all methods that generate HTML 4 elements (such as <abbrev>,
530           <acronym> and <thead>).
531
532       :netscape
533           Import the <blink>, <fontsize> and <center> tags.
534
535       :html
536           Import all HTML-generating shortcuts (i.e. 'html2', 'html3',
537           'html4' and 'netscape')
538
539       :standard
540           Import "standard" features, 'html2', 'html3', 'html4', 'form' and
541           'cgi'.
542
543       :all
544           Import all the available methods.  For the full list, see the
545           CGI.pm code, where the variable %EXPORT_TAGS is defined.
546
547       If you import a function name that is not part of CGI.pm, the module
548       will treat it as a new HTML tag and generate the appropriate
549       subroutine.  You can then use it like any other HTML tag.  This is to
550       provide for the rapidly-evolving HTML "standard."  For example, say
551       Microsoft comes out with a new tag called <gradient> (which causes the
552       user's desktop to be flooded with a rotating gradient fill until his
553       machine reboots).  You don't need to wait for a new version of CGI.pm
554       to start using it immediately:
555
556          use CGI qw/:standard :html3 gradient/;
557          print gradient({-start=>'red',-end=>'blue'});
558
559       Note that in the interests of execution speed CGI.pm does not use the
560       standard Exporter syntax for specifying load symbols.  This may change
561       in the future.
562
563       If you import any of the state-maintaining CGI or form-generating
564       methods, a default CGI object will be created and initialized
565       automatically the first time you use any of the methods that require
566       one to be present.  This includes param(), textfield(), submit() and
567       the like.  (If you need direct access to the CGI object, you can find
568       it in the global variable $CGI::Q).  By importing CGI.pm methods, you
569       can create visually elegant scripts:
570
571          use CGI qw/:standard/;
572          print
573              header,
574              start_html('Simple Script'),
575              h1('Simple Script'),
576              start_form,
577              "What's your name? ",textfield('name'),p,
578              "What's the combination?",
579              checkbox_group(-name=>'words',
580                             -values=>['eenie','meenie','minie','moe'],
581                             -defaults=>['eenie','moe']),p,
582              "What's your favorite color?",
583              popup_menu(-name=>'color',
584                         -values=>['red','green','blue','chartreuse']),p,
585              submit,
586              end_form,
587              hr,"\n";
588
589           if (param) {
590              print
591                  "Your name is ",em(param('name')),p,
592                  "The keywords are: ",em(join(", ",param('words'))),p,
593                  "Your favorite color is ",em(param('color')),".\n";
594           }
595           print end_html;
596
597   PRAGMAS
598       In addition to the function sets, there are a number of pragmas that
599       you can import.  Pragmas, which are always preceded by a hyphen, change
600       the way that CGI.pm functions in various ways.  Pragmas, function sets,
601       and individual functions can all be imported in the same use() line.
602       For example, the following use statement imports the standard set of
603       functions and enables debugging mode (pragma -debug):
604
605          use CGI qw/:standard -debug/;
606
607       The current list of pragmas is as follows:
608
609       -any
610           When you use CGI -any, then any method that the query object
611           doesn't recognize will be interpreted as a new HTML tag.  This
612           allows you to support the next ad hoc HTML extension.  This lets
613           you go wild with new and unsupported tags:
614
615              use CGI qw(-any);
616              $q=CGI->new;
617              print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
618
619           Since using <cite>any</cite> causes any mistyped method name to be
620           interpreted as an HTML tag, use it with care or not at all.
621
622       -compile
623           This causes the indicated autoloaded methods to be compiled up
624           front, rather than deferred to later.  This is useful for scripts
625           that run for an extended period of time under FastCGI or mod_perl,
626           and for those destined to be crunched by Malcolm Beattie's Perl
627           compiler.  Use it in conjunction with the methods or method
628           families you plan to use.
629
630              use CGI qw(-compile :standard :html3);
631
632           or even
633
634              use CGI qw(-compile :all);
635
636           Note that using the -compile pragma in this way will always have
637           the effect of importing the compiled functions into the current
638           namespace.  If you want to compile without importing use the
639           compile() method instead:
640
641              use CGI();
642              CGI->compile();
643
644           This is particularly useful in a mod_perl environment, in which you
645           might want to precompile all CGI routines in a startup script, and
646           then import the functions individually in each mod_perl script.
647
648       -nosticky
649           By default the CGI module implements a state-preserving behavior
650           called "sticky" fields.  The way this works is that if you are
651           regenerating a form, the methods that generate the form field
652           values will interrogate param() to see if similarly-named
653           parameters are present in the query string. If they find a like-
654           named parameter, they will use it to set their default values.
655
656           Sometimes this isn't what you want.  The -nosticky pragma prevents
657           this behavior.  You can also selectively change the sticky behavior
658           in each element that you generate.
659
660       -tabindex
661           Automatically add tab index attributes to each form field. With
662           this option turned off, you can still add tab indexes manually by
663           passing a -tabindex option to each field-generating method.
664
665       -no_undef_params
666           This keeps CGI.pm from including undef params in the parameter
667           list.
668
669       -no_xhtml
670           By default, CGI.pm versions 2.69 and higher emit XHTML
671           (http://www.w3.org/TR/xhtml1/).  The -no_xhtml pragma disables this
672           feature.  Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for
673           this feature.
674
675           If start_html()'s -dtd parameter specifies an HTML 2.0, 3.2, 4.0 or
676           4.01 DTD, XHTML will automatically be disabled without needing to
677           use this pragma.
678
679       -utf8
680           This makes CGI.pm treat all parameters as UTF-8 strings. Use this
681           with care, as it will interfere with the processing of binary
682           uploads. It is better to manually select which fields are expected
683           to return utf-8 strings and convert them using code like this:
684
685            use Encode;
686            my $arg = decode utf8=>param('foo');
687
688       -nph
689           This makes CGI.pm produce a header appropriate for an NPH (no
690           parsed header) script.  You may need to do other things as well to
691           tell the server that the script is NPH.  See the discussion of NPH
692           scripts below.
693
694       -newstyle_urls
695           Separate the name=value pairs in CGI parameter query strings with
696           semicolons rather than ampersands.  For example:
697
698              ?name=fred;age=24;favorite_color=3
699
700           Semicolon-delimited query strings are always accepted, and will be
701           emitted by self_url() and query_string(). newstyle_urls became the
702           default in version 2.64.
703
704       -oldstyle_urls
705           Separate the name=value pairs in CGI parameter query strings with
706           ampersands rather than semicolons.  This is no longer the default.
707
708       -autoload
709           This overrides the autoloader so that any function in your program
710           that is not recognized is referred to CGI.pm for possible
711           evaluation.  This allows you to use all the CGI.pm functions
712           without adding them to your symbol table, which is of concern for
713           mod_perl users who are worried about memory consumption.  Warning:
714           when -autoload is in effect, you cannot use "poetry mode"
715           (functions without the parenthesis).  Use hr() rather than hr, or
716           add something like use subs qw/hr p header/ to the top of your
717           script.
718
719       -no_debug
720           This turns off the command-line processing features.  If you want
721           to run a CGI.pm script from the command line to produce HTML, and
722           you don't want it to read CGI parameters from the command line or
723           STDIN, then use this pragma:
724
725              use CGI qw(-no_debug :standard);
726
727       -debug
728           This turns on full debugging.  In addition to reading CGI arguments
729           from the command-line processing, CGI.pm will pause and try to read
730           arguments from STDIN, producing the message "(offline mode: enter
731           name=value pairs on standard input)" features.
732
733           See the section on debugging for more details.
734
735       -private_tempfiles
736           CGI.pm can process uploaded file. Ordinarily it spools the uploaded
737           file to a temporary directory, then deletes the file when done.
738           However, this opens the risk of eavesdropping as described in the
739           file upload section.  Another CGI script author could peek at this
740           data during the upload, even if it is confidential information. On
741           Unix systems, the -private_tempfiles pragma will cause the
742           temporary file to be unlinked as soon as it is opened and before
743           any data is written into it, reducing, but not eliminating the risk
744           of eavesdropping (there is still a potential race condition).  To
745           make life harder for the attacker, the program chooses tempfile
746           names by calculating a 32 bit checksum of the incoming HTTP
747           headers.
748
749           To ensure that the temporary file cannot be read by other CGI
750           scripts, use suEXEC or a CGI wrapper program to run your script.
751           The temporary file is created with mode 0600 (neither world nor
752           group readable).
753
754           The temporary directory is selected using the following algorithm:
755
756               1. if $CGITempFile::TMPDIRECTORY is already set, use that
757
758               2. if the environment variable TMPDIR exists, use the location
759               indicated.
760
761               3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
762               /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
763
764           Each of these locations is checked that it is a directory and is
765           writable.  If not, the algorithm tries the next choice.
766
767   SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
768       Many of the methods generate HTML tags.  As described below, tag
769       functions automatically generate both the opening and closing tags.
770       For example:
771
772         print h1('Level 1 Header');
773
774       produces
775
776         <h1>Level 1 Header</h1>
777
778       There will be some times when you want to produce the start and end
779       tags yourself.  In this case, you can use the form start_tag_name and
780       end_tag_name, as in:
781
782         print start_h1,'Level 1 Header',end_h1;
783
784       With a few exceptions (described below), start_tag_name and
785       end_tag_name functions are not generated automatically when you use
786       CGI.  However, you can specify the tags you want to generate start/end
787       functions for by putting an asterisk in front of their name, or,
788       alternatively, requesting either "start_tag_name" or "end_tag_name" in
789       the import list.
790
791       Example:
792
793         use CGI qw/:standard *table start_ul/;
794
795       In this example, the following functions are generated in addition to
796       the standard ones:
797
798       1. start_table() (generates a <table> tag)
799       2. end_table() (generates a </table> tag)
800       3. start_ul() (generates a <ul> tag)
801       4. end_ul() (generates a </ul> tag)
802

GENERATING DYNAMIC DOCUMENTS

804       Most of CGI.pm's functions deal with creating documents on the fly.
805       Generally you will produce the HTTP header first, followed by the
806       document itself.  CGI.pm provides functions for generating HTTP headers
807       of various types as well as for generating HTML.  For creating GIF
808       images, see the GD.pm module.
809
810       Each of these functions produces a fragment of HTML or HTTP which you
811       can print out directly so that it displays in the browser window,
812       append to a string, or save to a file for later use.
813
814   CREATING A STANDARD HTTP HEADER:
815       Normally the first thing you will do in any CGI script is print out an
816       HTTP header.  This tells the browser what type of document to expect,
817       and gives other optional information, such as the language, expiration
818       date, and whether to cache the document.  The header can also be
819       manipulated for special purposes, such as server push and pay per view
820       pages.
821
822               print header;
823
824                    -or-
825
826               print header('image/gif');
827
828                    -or-
829
830               print header('text/html','204 No response');
831
832                    -or-
833
834               print header(-type=>'image/gif',
835                                    -nph=>1,
836                                    -status=>'402 Payment required',
837                                    -expires=>'+3d',
838                                    -cookie=>$cookie,
839                                    -charset=>'utf-7',
840                                    -attachment=>'foo.gif',
841                                    -Cost=>'$2.00');
842
843       header() returns the Content-type: header.  You can provide your own
844       MIME type if you choose, otherwise it defaults to text/html.  An
845       optional second parameter specifies the status code and a human-
846       readable message.  For example, you can specify 204, "No response" to
847       create a script that tells the browser to do nothing at all.
848
849       The last example shows the named argument style for passing arguments
850       to the CGI methods using named parameters.  Recognized parameters are
851       -type, -status, -expires, and -cookie.  Any other named parameters will
852       be stripped of their initial hyphens and turned into header fields,
853       allowing you to specify any HTTP header you desire.  Internal
854       underscores will be turned into hyphens:
855
856           print header(-Content_length=>3002);
857
858       Most browsers will not cache the output from CGI scripts.  Every time
859       the browser reloads the page, the script is invoked anew.  You can
860       change this behavior with the -expires parameter.  When you specify an
861       absolute or relative expiration interval with this parameter, some
862       browsers and proxy servers will cache the script's output until the
863       indicated expiration date.  The following forms are all valid for the
864       -expires field:
865
866               +30s                              30 seconds from now
867               +10m                              ten minutes from now
868               +1h                               one hour from now
869               -1d                               yesterday (i.e. "ASAP!")
870               now                               immediately
871               +3M                               in three months
872               +10y                              in ten years time
873               Thursday, 25-Apr-1999 00:40:33 GMT  at the indicated time & date
874
875       The -cookie parameter generates a header that tells the browser to
876       provide a "magic cookie" during all subsequent transactions with your
877       script.  Some cookies have a special format that includes interesting
878       attributes such as expiration time.  Use the cookie() method to create
879       and retrieve session cookies.
880
881       The -nph parameter, if set to a true value, will issue the correct
882       headers to work with a NPH (no-parse-header) script.  This is important
883       to use with certain servers that expect all their scripts to be NPH.
884
885       The -charset parameter can be used to control the character set sent to
886       the browser.  If not provided, defaults to ISO-8859-1.  As a side
887       effect, this sets the charset() method as well.
888
889       The -attachment parameter can be used to turn the page into an
890       attachment.  Instead of displaying the page, some browsers will prompt
891       the user to save it to disk.  The value of the argument is the
892       suggested name for the saved file.  In order for this to work, you may
893       have to set the -type to "application/octet-stream".
894
895       The -p3p parameter will add a P3P tag to the outgoing header.  The
896       parameter can be an arrayref or a space-delimited string of P3P tags.
897       For example:
898
899          print header(-p3p=>[qw(CAO DSP LAW CURa)]);
900          print header(-p3p=>'CAO DSP LAW CURa');
901
902       In either case, the outgoing header will be formatted as:
903
904         P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
905
906       Note that if a header value contains a carriage return, a leading space
907       will be added to each new line that doesn't already have one as
908       specified by RFC2616 section 4.2.  For example:
909
910           print header( -ingredients => "ham\neggs\nbacon" );
911
912       will generate
913
914           Ingredients: ham
915            eggs
916            bacon
917
918   GENERATING A REDIRECTION HEADER
919          print $q->redirect('http://somewhere.else/in/movie/land');
920
921       Sometimes you don't want to produce a document yourself, but simply
922       redirect the browser elsewhere, perhaps choosing a URL based on the
923       time of day or the identity of the user.
924
925       The redirect() method redirects the browser to a different URL.  If you
926       use redirection like this, you should not print out a header as well.
927
928       You should always use full URLs (including the http: or ftp: part) in
929       redirection requests.  Relative URLs will not work correctly.
930
931       You can also use named arguments:
932
933           print $q->redirect(
934               -uri=>'http://somewhere.else/in/movie/land',
935                   -nph=>1,
936                -status=>301);
937
938       All names arguments recognized by header() are also recognized by
939       redirect(). However, most HTTP headers, including those generated by
940       -cookie and -target, are ignored by the browser.
941
942       The -nph parameter, if set to a true value, will issue the correct
943       headers to work with a NPH (no-parse-header) script.  This is important
944       to use with certain servers, such as Microsoft IIS, which expect all
945       their scripts to be NPH.
946
947       The -status parameter will set the status of the redirect.  HTTP
948       defines three different possible redirection status codes:
949
950            301 Moved Permanently
951            302 Found
952            303 See Other
953
954       The default if not specified is 302, which means "moved temporarily."
955       You may change the status to another status code if you wish.  Be
956       advised that changing the status to anything other than 301, 302 or 303
957       will probably break redirection.
958
959   CREATING THE HTML DOCUMENT HEADER
960          print start_html(-title=>'Secrets of the Pyramids',
961                                   -author=>'fred@capricorn.org',
962                                   -base=>'true',
963                                   -target=>'_blank',
964                                   -meta=>{'keywords'=>'pharaoh secret mummy',
965                                           'copyright'=>'copyright 1996 King Tut'},
966                                   -style=>{'src'=>'/styles/style1.css'},
967                                   -BGCOLOR=>'blue');
968
969       The start_html() routine creates the top of the page, along with a lot
970       of optional information that controls the page's appearance and
971       behavior.
972
973       This method returns a canned HTML header and the opening <body> tag.
974       All parameters are optional.  In the named parameter form, recognized
975       parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
976       (see below for the explanation).  Any additional parameters you
977       provide, such as the unofficial BGCOLOR attribute, are added to the
978       <body> tag.  Additional parameters must be proceeded by a hyphen.
979
980       The argument -xbase allows you to provide an HREF for the <base> tag
981       different from the current location, as in
982
983           -xbase=>"http://home.mcom.com/"
984
985       All relative links will be interpreted relative to this tag.
986
987       The argument -target allows you to provide a default target frame for
988       all the links and fill-out forms on the page.  This is a non-standard
989       HTTP feature which only works with some browsers!
990
991           -target=>"answer_window"
992
993       All relative links will be interpreted relative to this tag.  You add
994       arbitrary meta information to the header with the -meta argument.  This
995       argument expects a reference to a hash containing name/value pairs of
996       meta information.  These will be turned into a series of header <meta>
997       tags that look something like this:
998
999           <meta name="keywords" content="pharaoh secret mummy">
1000           <meta name="description" content="copyright 1996 King Tut">
1001
1002       To create an HTTP-EQUIV type of <meta> tag, use -head, described below.
1003
1004       The -style argument is used to incorporate cascading stylesheets into
1005       your code.  See the section on CASCADING STYLESHEETS for more
1006       information.
1007
1008       The -lang argument is used to incorporate a language attribute into the
1009       <html> tag.  For example:
1010
1011           print $q->start_html(-lang=>'fr-CA');
1012
1013       The default if not specified is "en-US" for US English, unless the -dtd
1014       parameter specifies an HTML 2.0 or 3.2 DTD, in which case the lang
1015       attribute is left off.  You can force the lang attribute to left off in
1016       other cases by passing an empty string (-lang=>'').
1017
1018       The -encoding argument can be used to specify the character set for
1019       XHTML.  It defaults to iso-8859-1 if not specified.
1020
1021       The -dtd argument can be used to specify a public DTD identifier
1022       string. For example:
1023
1024           -dtd => '-//W3C//DTD HTML 4.01 Transitional//EN')
1025
1026       Alternatively, it can take public and system DTD identifiers as an
1027       array:
1028
1029           dtd => [ '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd' ]
1030
1031       For the public DTD identifier to be considered, it must be valid.
1032       Otherwise it will be replaced by the default DTD. If the public DTD
1033       contains 'XHTML', CGI.pm will emit XML.
1034
1035       The -declare_xml argument, when used in conjunction with XHTML, will
1036       put a <?xml> declaration at the top of the HTML header. The sole
1037       purpose of this declaration is to declare the character set encoding.
1038       In the absence of -declare_xml, the output HTML will contain a <meta>
1039       tag that specifies the encoding, allowing the HTML to pass most
1040       validators.  The default for -declare_xml is false.
1041
1042       You can place other arbitrary HTML elements to the <head> section with
1043       the -head tag.  For example, to place a <link> element in the head
1044       section, use this:
1045
1046           print start_html(-head=>Link({-rel=>'shortcut icon',
1047                                         -href=>'favicon.ico'}));
1048
1049       To incorporate multiple HTML elements into the <head> section, just
1050       pass an array reference:
1051
1052           print start_html(-head=>[
1053                                    Link({-rel=>'next',
1054                                          -href=>'http://www.capricorn.com/s2.html'}),
1055                                    Link({-rel=>'previous',
1056                                          -href=>'http://www.capricorn.com/s1.html'})
1057                                    ]
1058                            );
1059
1060       And here's how to create an HTTP-EQUIV <meta> tag:
1061
1062             print start_html(-head=>meta({-http_equiv => 'Content-Type',
1063                                           -content    => 'text/html'}))
1064
1065       JAVASCRIPTING: The -script, -noScript, -onLoad, -onMouseOver,
1066       -onMouseOut and -onUnload parameters are used to add JavaScript calls
1067       to your pages.  -script should point to a block of text containing
1068       JavaScript function definitions.  This block will be placed within a
1069       <script> block inside the HTML (not HTTP) header.  The block is placed
1070       in the header in order to give your page a fighting chance of having
1071       all its JavaScript functions in place even if the user presses the stop
1072       button before the page has loaded completely.  CGI.pm attempts to
1073       format the script in such a way that JavaScript-naive browsers will not
1074       choke on the code: unfortunately there are some browsers, such as
1075       Chimera for Unix, that get confused by it nevertheless.
1076
1077       The -onLoad and -onUnload parameters point to fragments of JavaScript
1078       code to execute when the page is respectively opened and closed by the
1079       browser.  Usually these parameters are calls to functions defined in
1080       the -script field:
1081
1082             $query = CGI->new;
1083             print header;
1084             $JSCRIPT=<<END;
1085             // Ask a silly question
1086             function riddle_me_this() {
1087                var r = prompt("What walks on four legs in the morning, " +
1088                              "two legs in the afternoon, " +
1089                              "and three legs in the evening?");
1090                response(r);
1091             }
1092             // Get a silly answer
1093             function response(answer) {
1094                if (answer == "man")
1095                   alert("Right you are!");
1096                else
1097                   alert("Wrong!  Guess again.");
1098             }
1099             END
1100             print start_html(-title=>'The Riddle of the Sphinx',
1101                                      -script=>$JSCRIPT);
1102
1103       Use the -noScript parameter to pass some HTML text that will be
1104       displayed on browsers that do not have JavaScript (or browsers where
1105       JavaScript is turned off).
1106
1107       The <script> tag, has several attributes including "type", "charset"
1108       and "src".  "src" allows you to keep JavaScript code in an external
1109       file. To use these attributes pass a HASH reference in the -script
1110       parameter containing one or more of -type, -src, or -code:
1111
1112           print $q->start_html(-title=>'The Riddle of the Sphinx',
1113                                -script=>{-type=>'JAVASCRIPT',
1114                                          -src=>'/javascript/sphinx.js'}
1115                                );
1116
1117           print $q->(-title=>'The Riddle of the Sphinx',
1118                      -script=>{-type=>'PERLSCRIPT',
1119                                -code=>'print "hello world!\n;"'}
1120                      );
1121
1122       A final feature allows you to incorporate multiple <script> sections
1123       into the header.  Just pass the list of script sections as an array
1124       reference.  this allows you to specify different source files for
1125       different dialects of JavaScript.  Example:
1126
1127            print $q->start_html(-title=>'The Riddle of the Sphinx',
1128                                 -script=>[
1129                                           { -type => 'text/javascript',
1130                                             -src      => '/javascript/utilities10.js'
1131                                           },
1132                                           { -type => 'text/javascript',
1133                                             -src      => '/javascript/utilities11.js'
1134                                           },
1135                                           { -type => 'text/jscript',
1136                                             -src      => '/javascript/utilities12.js'
1137                                           },
1138                                           { -type => 'text/ecmascript',
1139                                             -src      => '/javascript/utilities219.js'
1140                                           }
1141                                        ]
1142                                    );
1143
1144       The option "-language" is a synonym for -type, and is supported for
1145       backwards compatibility.
1146
1147       The old-style positional parameters are as follows:
1148
1149       Parameters:
1150       1.  The title
1151
1152       2.  The author's e-mail address (will create a <link rev="MADE"> tag if
1153           present
1154
1155       3.  A 'true' flag if you want to include a <base> tag in the header.
1156           This helps resolve relative addresses to absolute ones when the
1157           document is moved, but makes the document hierarchy non-portable.
1158           Use with care!
1159
1160       4, 5, 6...
1161           Any other parameters you want to include in the <body> tag.  This
1162           is a good place to put HTML extensions, such as colors and
1163           wallpaper patterns.
1164
1165   ENDING THE HTML DOCUMENT:
1166               print end_html
1167
1168       This ends an HTML document by printing the </body></html> tags.
1169
1170   CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
1171           $myself = self_url;
1172           print q(<a href="$myself">I'm talking to myself.</a>);
1173
1174       self_url() will return a URL, that, when selected, will reinvoke this
1175       script with all its state information intact.  This is most useful when
1176       you want to jump around within the document using internal anchors but
1177       you don't want to disrupt the current contents of the form(s).
1178       Something like this will do the trick.
1179
1180            $myself = self_url;
1181            print "<a href=\"$myself#table1\">See table 1</a>";
1182            print "<a href=\"$myself#table2\">See table 2</a>";
1183            print "<a href=\"$myself#yourself\">See for yourself</a>";
1184
1185       If you want more control over what's returned, using the url() method
1186       instead.
1187
1188       You can also retrieve the unprocessed query string with query_string():
1189
1190           $the_string = query_string;
1191
1192   OBTAINING THE SCRIPT'S URL
1193           $full_url      = url();
1194           $full_url      = url(-full=>1);  #alternative syntax
1195           $relative_url  = url(-relative=>1);
1196           $absolute_url  = url(-absolute=>1);
1197           $url_with_path = url(-path_info=>1);
1198           $url_with_path_and_query = url(-path_info=>1,-query=>1);
1199           $netloc        = url(-base => 1);
1200
1201       url() returns the script's URL in a variety of formats.  Called without
1202       any arguments, it returns the full form of the URL, including host name
1203       and port number
1204
1205           http://your.host.com/path/to/script.cgi
1206
1207       You can modify this format with the following named arguments:
1208
1209       -absolute
1210           If true, produce an absolute URL, e.g.
1211
1212               /path/to/script.cgi
1213
1214       -relative
1215           Produce a relative URL.  This is useful if you want to reinvoke
1216           your script with different parameters. For example:
1217
1218               script.cgi
1219
1220       -full
1221           Produce the full URL, exactly as if called without any arguments.
1222           This overrides the -relative and -absolute arguments.
1223
1224       -path (-path_info)
1225           Append the additional path information to the URL.  This can be
1226           combined with -full, -absolute or -relative.  -path_info is
1227           provided as a synonym.
1228
1229       -query (-query_string)
1230           Append the query string to the URL.  This can be combined with
1231           -full, -absolute or -relative.  -query_string is provided as a
1232           synonym.
1233
1234       -base
1235           Generate just the protocol and net location, as in
1236           http://www.foo.com:8000
1237
1238       -rewrite
1239           If Apache's mod_rewrite is turned on, then the script name and path
1240           info probably won't match the request that the user sent. Set
1241           -rewrite=>1 (default) to return URLs that match what the user sent
1242           (the original request URI). Set -rewrite=>0 to return URLs that
1243           match the URL after mod_rewrite's rules have run. Because the
1244           additional path information only makes sense in the context of the
1245           rewritten URL, -rewrite is set to false when you request path info
1246           in the URL.
1247
1248   MIXING POST AND URL PARAMETERS
1249          $color = url_param('color');
1250
1251       It is possible for a script to receive CGI parameters in the URL as
1252       well as in the fill-out form by creating a form that POSTs to a URL
1253       containing a query string (a "?" mark followed by arguments).  The
1254       param() method will always return the contents of the POSTed fill-out
1255       form, ignoring the URL's query string.  To retrieve URL parameters,
1256       call the url_param() method.  Use it in the same way as param().  The
1257       main difference is that it allows you to read the parameters, but not
1258       set them.
1259
1260       Under no circumstances will the contents of the URL query string
1261       interfere with similarly-named CGI parameters in POSTed forms.  If you
1262       try to mix a URL query string with a form submitted with the GET
1263       method, the results will not be what you expect.
1264

CREATING STANDARD HTML ELEMENTS:

1266       CGI.pm defines general HTML shortcut methods for many HTML tags.  HTML
1267       shortcuts are named after a single HTML element and return a fragment
1268       of HTML text. Example:
1269
1270          print $q->blockquote(
1271                            "Many years ago on the island of",
1272                            $q->a({href=>"http://crete.org/"},"Crete"),
1273                            "there lived a Minotaur named",
1274                            $q->strong("Fred."),
1275                           ),
1276              $q->hr;
1277
1278       This results in the following HTML code (extra newlines have been added
1279       for readability):
1280
1281          <blockquote>
1282          Many years ago on the island of
1283          <a href="http://crete.org/">Crete</a> there lived
1284          a minotaur named <strong>Fred.</strong>
1285          </blockquote>
1286          <hr>
1287
1288       If you find the syntax for calling the HTML shortcuts awkward, you can
1289       import them into your namespace and dispense with the object syntax
1290       completely (see the next section for more details):
1291
1292          use CGI ':standard';
1293          print blockquote(
1294             "Many years ago on the island of",
1295             a({href=>"http://crete.org/"},"Crete"),
1296             "there lived a minotaur named",
1297             strong("Fred."),
1298             ),
1299             hr;
1300
1301   PROVIDING ARGUMENTS TO HTML SHORTCUTS
1302       The HTML methods will accept zero, one or multiple arguments.  If you
1303       provide no arguments, you get a single tag:
1304
1305          print hr;    #  <hr>
1306
1307       If you provide one or more string arguments, they are concatenated
1308       together with spaces and placed between opening and closing tags:
1309
1310          print h1("Chapter","1"); # <h1>Chapter 1</h1>"
1311
1312       If the first argument is a hash reference, then the keys and values of
1313       the hash become the HTML tag's attributes:
1314
1315          print a({-href=>'fred.html',-target=>'_new'},
1316             "Open a new frame");
1317
1318                   <a href="fred.html",target="_new">Open a new frame</a>
1319
1320       You may dispense with the dashes in front of the attribute names if you
1321       prefer:
1322
1323          print img {src=>'fred.gif',align=>'LEFT'};
1324
1325                  <img align="LEFT" src="fred.gif">
1326
1327       Sometimes an HTML tag attribute has no argument.  For example, ordered
1328       lists can be marked as COMPACT.  The syntax for this is an argument
1329       that that points to an undef string:
1330
1331          print ol({compact=>undef},li('one'),li('two'),li('three'));
1332
1333       Prior to CGI.pm version 2.41, providing an empty ('') string as an
1334       attribute argument was the same as providing undef.  However, this has
1335       changed in order to accommodate those who want to create tags of the
1336       form <img alt="">.  The difference is shown in these two pieces of
1337       code:
1338
1339          CODE                   RESULT
1340          img({alt=>undef})      <img alt>
1341          img({alt=>''})         <img alt="">
1342
1343   THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
1344       One of the cool features of the HTML shortcuts is that they are
1345       distributive.  If you give them an argument consisting of a reference
1346       to a list, the tag will be distributed across each element of the list.
1347       For example, here's one way to make an ordered list:
1348
1349          print ul(
1350                    li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
1351                  );
1352
1353       This example will result in HTML output that looks like this:
1354
1355          <ul>
1356            <li type="disc">Sneezy</li>
1357            <li type="disc">Doc</li>
1358            <li type="disc">Sleepy</li>
1359            <li type="disc">Happy</li>
1360          </ul>
1361
1362       This is extremely useful for creating tables.  For example:
1363
1364          print table({-border=>undef},
1365                  caption('When Should You Eat Your Vegetables?'),
1366                  Tr({-align=>'CENTER',-valign=>'TOP'},
1367                  [
1368                     th(['Vegetable', 'Breakfast','Lunch','Dinner']),
1369                     td(['Tomatoes' , 'no', 'yes', 'yes']),
1370                     td(['Broccoli' , 'no', 'no',  'yes']),
1371                     td(['Onions'   , 'yes','yes', 'yes'])
1372                  ]
1373                  )
1374               );
1375
1376   HTML SHORTCUTS AND LIST INTERPOLATION
1377       Consider this bit of code:
1378
1379          print blockquote(em('Hi'),'mom!'));
1380
1381       It will ordinarily return the string that you probably expect, namely:
1382
1383          <blockquote><em>Hi</em> mom!</blockquote>
1384
1385       Note the space between the element "Hi" and the element "mom!".  CGI.pm
1386       puts the extra space there using array interpolation, which is
1387       controlled by the magic $" variable.  Sometimes this extra space is not
1388       what you want, for example, when you are trying to align a series of
1389       images.  In this case, you can simply change the value of $" to an
1390       empty string.
1391
1392          {
1393             local($") = '';
1394             print blockquote(em('Hi'),'mom!'));
1395           }
1396
1397       I suggest you put the code in a block as shown here.  Otherwise the
1398       change to $" will affect all subsequent code until you explicitly reset
1399       it.
1400
1401   NON-STANDARD HTML SHORTCUTS
1402       A few HTML tags don't follow the standard pattern for various reasons.
1403
1404       comment() generates an HTML comment (<!-- comment -->).  Call it like
1405
1406           print comment('here is my comment');
1407
1408       Because of conflicts with built-in Perl functions, the following
1409       functions begin with initial caps:
1410
1411           Select
1412           Tr
1413           Link
1414           Delete
1415           Accept
1416           Sub
1417
1418       In addition, start_html(), end_html(), start_form(), end_form(),
1419       start_multipart_form() and all the fill-out form tags are special.  See
1420       their respective sections.
1421
1422   AUTOESCAPING HTML
1423       By default, all HTML that is emitted by the form-generating functions
1424       is passed through a function called escapeHTML():
1425
1426       $escaped_string = escapeHTML("unescaped string");
1427           Escape HTML formatting characters in a string.
1428
1429       Provided that you have specified a character set of ISO-8859-1 (the
1430       default), the standard HTML escaping rules will be used.  The "<"
1431       character becomes "&lt;", ">" becomes "&gt;", "&" becomes "&amp;", and
1432       the quote character becomes "&quot;".  In addition, the hexadecimal
1433       0x8b and 0x9b characters, which some browsers incorrectly interpret as
1434       the left and right angle-bracket characters, are replaced by their
1435       numeric character entities ("&#8249" and "&#8250;").  If you manually
1436       change the charset, either by calling the charset() method explicitly
1437       or by passing a -charset argument to header(), then all characters will
1438       be replaced by their numeric entities, since CGI.pm has no lookup table
1439       for all the possible encodings.
1440
1441       "escapeHTML()" expects the supplied string to be a character string.
1442       This means you should Encode::decode data received from "outside" and
1443       Encode::encode your strings before sending them back outside. If your
1444       source code UTF-8 encoded and you want to upgrade string literals in
1445       your source to character strings, you can use "use utf8". See
1446       perlunitut, perlunifaq and perlunicode for more information on how Perl
1447       handles the difference between bytes and characters.
1448
1449       The automatic escaping does not apply to other shortcuts, such as h1().
1450       You should call escapeHTML() yourself on untrusted data in order to
1451       protect your pages against nasty tricks that people may enter into
1452       guestbooks, etc..  To change the character set, use charset().  To turn
1453       autoescaping off completely, use autoEscape(0):
1454
1455       $charset = charset([$charset]);
1456           Get or set the current character set.
1457
1458       $flag = autoEscape([$flag]);
1459           Get or set the value of the autoescape flag.
1460
1461   PRETTY-PRINTING HTML
1462       By default, all the HTML produced by these functions comes out as one
1463       long line without carriage returns or indentation. This is yuck, but it
1464       does reduce the size of the documents by 10-20%.  To get pretty-printed
1465       output, please use CGI::Pretty, a subclass contributed by Brian
1466       Paulsen.
1467

CREATING FILL-OUT FORMS:

1469       General note  The various form-creating methods all return strings to
1470       the caller, containing the tag or tags that will create the requested
1471       form element.  You are responsible for actually printing out these
1472       strings.  It's set up this way so that you can place formatting tags
1473       around the form elements.
1474
1475       Another note The default values that you specify for the forms are only
1476       used the first time the script is invoked (when there is no query
1477       string).  On subsequent invocations of the script (when there is a
1478       query string), the former values are used even if they are blank.
1479
1480       If you want to change the value of a field from its previous value, you
1481       have two choices:
1482
1483       (1) call the param() method to set it.
1484
1485       (2) use the -override (alias -force) parameter (a new feature in
1486       version 2.15).  This forces the default value to be used, regardless of
1487       the previous value:
1488
1489          print textfield(-name=>'field_name',
1490                                  -default=>'starting value',
1491                                  -override=>1,
1492                                  -size=>50,
1493                                  -maxlength=>80);
1494
1495       Yet another note By default, the text and labels of form elements are
1496       escaped according to HTML rules.  This means that you can safely use
1497       "<CLICK ME>" as the label for a button.  However, it also interferes
1498       with your ability to incorporate special HTML character sequences, such
1499       as &Aacute;, into your fields.  If you wish to turn off automatic
1500       escaping, call the autoEscape() method with a false value immediately
1501       after creating the CGI object:
1502
1503          $query = CGI->new;
1504          $query->autoEscape(0);
1505
1506       Note that autoEscape() is exclusively used to effect the behavior of
1507       how some CGI.pm HTML generation functions handle escaping. Calling
1508       escapeHTML() explicitly will always escape the HTML.
1509
1510       A Lurking Trap! Some of the form-element generating methods return
1511       multiple tags.  In a scalar context, the tags will be concatenated
1512       together with spaces, or whatever is the current value of the $"
1513       global.  In a list context, the methods will return a list of elements,
1514       allowing you to modify them if you wish.  Usually you will not notice
1515       this behavior, but beware of this:
1516
1517           printf("%s\n",end_form())
1518
1519       end_form() produces several tags, and only the first of them will be
1520       printed because the format only expects one value.
1521
1522       <p>
1523
1524   CREATING AN ISINDEX TAG
1525          print isindex(-action=>$action);
1526
1527                -or-
1528
1529          print isindex($action);
1530
1531       Prints out an <isindex> tag.  Not very exciting.  The parameter -action
1532       specifies the URL of the script to process the query.  The default is
1533       to process the query with the current script.
1534
1535   STARTING AND ENDING A FORM
1536           print start_form(-method=>$method,
1537                           -action=>$action,
1538                           -enctype=>$encoding);
1539             <... various form stuff ...>
1540           print end_form;
1541
1542               -or-
1543
1544           print start_form($method,$action,$encoding);
1545             <... various form stuff ...>
1546           print end_form;
1547
1548       start_form() will return a <form> tag with the optional method, action
1549       and form encoding that you specify.  The defaults are:
1550
1551           method: POST
1552           action: this script
1553           enctype: application/x-www-form-urlencoded for non-XHTML
1554                    multipart/form-data for XHTML, see multipart/form-data below.
1555
1556       end_form() returns the closing </form> tag.
1557
1558       Start_form()'s enctype argument tells the browser how to package the
1559       various fields of the form before sending the form to the server.  Two
1560       values are possible:
1561
1562       Note: These methods were previously named startform() and endform().
1563       These methods are now DEPRECATED.  Please use start_form() and
1564       end_form() instead.
1565
1566       application/x-www-form-urlencoded
1567           This is the older type of encoding.  It is compatible with many CGI
1568           scripts and is suitable for short fields containing text data.  For
1569           your convenience, CGI.pm stores the name of this encoding type in
1570           &CGI::URL_ENCODED.
1571
1572       multipart/form-data
1573           This is the newer type of encoding.  It is suitable for forms that
1574           contain very large fields or that are intended for transferring
1575           binary data.  Most importantly, it enables the "file upload"
1576           feature.  For your convenience, CGI.pm stores the name of this
1577           encoding type in &CGI::MULTIPART
1578
1579           Forms that use this type of encoding are not easily interpreted by
1580           CGI scripts unless they use CGI.pm or another library designed to
1581           handle them.
1582
1583           If XHTML is activated (the default), then forms will be
1584           automatically created using this type of encoding.
1585
1586       The start_form() method uses the older form of encoding by default
1587       unless XHTML is requested.  If you want to use the newer form of
1588       encoding by default, you can call start_multipart_form() instead of
1589       start_form().  The method end_multipart_form() is an alias to
1590       end_form().
1591
1592       JAVASCRIPTING: The -name and -onSubmit parameters are provided for use
1593       with JavaScript.  The -name parameter gives the form a name so that it
1594       can be identified and manipulated by JavaScript functions.  -onSubmit
1595       should point to a JavaScript function that will be executed just before
1596       the form is submitted to your server.  You can use this opportunity to
1597       check the contents of the form for consistency and completeness.  If
1598       you find something wrong, you can put up an alert box or maybe fix
1599       things up yourself.  You can abort the submission by returning false
1600       from this function.
1601
1602       Usually the bulk of JavaScript functions are defined in a <script>
1603       block in the HTML header and -onSubmit points to one of these function
1604       call.  See start_html() for details.
1605
1606   FORM ELEMENTS
1607       After starting a form, you will typically create one or more
1608       textfields, popup menus, radio groups and other form elements.  Each of
1609       these elements takes a standard set of named arguments.  Some elements
1610       also have optional arguments.  The standard arguments are as follows:
1611
1612       -name
1613           The name of the field. After submission this name can be used to
1614           retrieve the field's value using the param() method.
1615
1616       -value, -values
1617           The initial value of the field which will be returned to the script
1618           after form submission.  Some form elements, such as text fields,
1619           take a single scalar -value argument. Others, such as popup menus,
1620           take a reference to an array of values. The two arguments are
1621           synonyms.
1622
1623       -tabindex
1624           A numeric value that sets the order in which the form element
1625           receives focus when the user presses the tab key. Elements with
1626           lower values receive focus first.
1627
1628       -id A string identifier that can be used to identify this element to
1629           JavaScript and DHTML.
1630
1631       -override
1632           A boolean, which, if true, forces the element to take on the value
1633           specified by -value, overriding the sticky behavior described
1634           earlier for the -nosticky pragma.
1635
1636       -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect
1637           These are used to assign JavaScript event handlers. See the
1638           JavaScripting section for more details.
1639
1640       Other common arguments are described in the next section. In addition
1641       to these, all attributes described in the HTML specifications are
1642       supported.
1643
1644   CREATING A TEXT FIELD
1645           print textfield(-name=>'field_name',
1646                           -value=>'starting value',
1647                           -size=>50,
1648                           -maxlength=>80);
1649               -or-
1650
1651           print textfield('field_name','starting value',50,80);
1652
1653       textfield() will return a text input field.
1654
1655       Parameters
1656       1.  The first parameter is the required name for the field (-name).
1657
1658       2.  The optional second parameter is the default starting value for the
1659           field contents (-value, formerly known as -default).
1660
1661       3.  The optional third parameter is the size of the field in
1662                 characters (-size).
1663
1664       4.  The optional fourth parameter is the maximum number of characters
1665           the
1666                 field will accept (-maxlength).
1667
1668       As with all these methods, the field will be initialized with its
1669       previous contents from earlier invocations of the script.  When the
1670       form is processed, the value of the text field can be retrieved with:
1671
1672              $value = param('foo');
1673
1674       If you want to reset it from its initial value after the script has
1675       been called once, you can do so like this:
1676
1677              param('foo',"I'm taking over this value!");
1678
1679   CREATING A BIG TEXT FIELD
1680          print textarea(-name=>'foo',
1681                                 -default=>'starting value',
1682                                 -rows=>10,
1683                                 -columns=>50);
1684
1685               -or
1686
1687          print textarea('foo','starting value',10,50);
1688
1689       textarea() is just like textfield, but it allows you to specify rows
1690       and columns for a multiline text entry box.  You can provide a starting
1691       value for the field, which can be long and contain multiple lines.
1692
1693   CREATING A PASSWORD FIELD
1694          print password_field(-name=>'secret',
1695                                       -value=>'starting value',
1696                                       -size=>50,
1697                                       -maxlength=>80);
1698               -or-
1699
1700          print password_field('secret','starting value',50,80);
1701
1702       password_field() is identical to textfield(), except that its contents
1703       will be starred out on the web page.
1704
1705   CREATING A FILE UPLOAD FIELD
1706           print filefield(-name=>'uploaded_file',
1707                                   -default=>'starting value',
1708                                   -size=>50,
1709                                   -maxlength=>80);
1710               -or-
1711
1712           print filefield('uploaded_file','starting value',50,80);
1713
1714       filefield() will return a file upload field.  In order to take full
1715       advantage of this you must use the new multipart encoding scheme for
1716       the form.  You can do this either by calling start_form() with an
1717       encoding type of &CGI::MULTIPART, or by calling the new method
1718       start_multipart_form() instead of vanilla start_form().
1719
1720       Parameters
1721       1.  The first parameter is the required name for the field (-name).
1722
1723       2.  The optional second parameter is the starting value for the field
1724           contents to be used as the default file name (-default).
1725
1726           For security reasons, browsers don't pay any attention to this
1727           field, and so the starting value will always be blank.  Worse, the
1728           field loses its "sticky" behavior and forgets its previous
1729           contents.  The starting value field is called for in the HTML
1730           specification, however, and possibly some browser will eventually
1731           provide support for it.
1732
1733       3.  The optional third parameter is the size of the field in characters
1734           (-size).
1735
1736       4.  The optional fourth parameter is the maximum number of characters
1737           the field will accept (-maxlength).
1738
1739       JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver,
1740       -onMouseOut and -onSelect parameters are recognized.  See textfield()
1741       for details.
1742
1743   PROCESSING A FILE UPLOAD FIELD
1744       Basics
1745
1746       When the form is processed, you can retrieve an IO::Handle compatible
1747       handle for a file upload field like this:
1748
1749         $lightweight_fh  = $q->upload('field_name');
1750
1751         # undef may be returned if it's not a valid file handle
1752         if (defined $lightweight_fh) {
1753           # Upgrade the handle to one compatible with IO::Handle:
1754           my $io_handle = $lightweight_fh->handle;
1755
1756           open (OUTFILE,'>>','/usr/local/web/users/feedback');
1757           while ($bytesread = $io_handle->read($buffer,1024)) {
1758             print OUTFILE $buffer;
1759           }
1760         }
1761
1762       In a list context, upload() will return an array of filehandles.  This
1763       makes it possible to process forms that use the same name for multiple
1764       upload fields.
1765
1766       If you want the entered file name for the file, you can just call
1767       param():
1768
1769         $filename = $q->param('field_name');
1770
1771       Different browsers will return slightly different things for the name.
1772       Some browsers return the filename only.  Others return the full path to
1773       the file, using the path conventions of the user's machine.
1774       Regardless, the name returned is always the name of the file on the
1775       user's machine, and is unrelated to the name of the temporary file that
1776       CGI.pm creates during upload spooling (see below).
1777
1778       When a file is uploaded the browser usually sends along some
1779       information along with it in the format of headers.  The information
1780       usually includes the MIME content type. To retrieve this information,
1781       call uploadInfo().  It returns a reference to a hash containing all the
1782       document headers.
1783
1784              $filename = $q->param('uploaded_file');
1785              $type = $q->uploadInfo($filename)->{'Content-Type'};
1786              unless ($type eq 'text/html') {
1787               die "HTML FILES ONLY!";
1788              }
1789
1790       If you are using a machine that recognizes "text" and "binary" data
1791       modes, be sure to understand when and how to use them (see the Camel
1792       book).  Otherwise you may find that binary files are corrupted during
1793       file uploads.
1794
1795       Accessing the temp files directly
1796
1797       When processing an uploaded file, CGI.pm creates a temporary file on
1798       your hard disk and passes you a file handle to that file. After you are
1799       finished with the file handle, CGI.pm unlinks (deletes) the temporary
1800       file. If you need to you can access the temporary file directly. You
1801       can access the temp file for a file upload by passing the file name to
1802       the tmpFileName() method:
1803
1804              $filename = $query->param('uploaded_file');
1805              $tmpfilename = $query->tmpFileName($filename);
1806
1807       The temporary file will be deleted automatically when your program
1808       exits unless you manually rename it. On some operating systems (such as
1809       Windows NT), you will need to close the temporary file's filehandle
1810       before your program exits.  Otherwise the attempt to delete the
1811       temporary file will fail.
1812
1813       Handling interrupted file uploads
1814
1815       There are occasionally problems involving parsing the uploaded file.
1816       This usually happens when the user presses "Stop" before the upload is
1817       finished.  In this case, CGI.pm will return undef for the name of the
1818       uploaded file and set cgi_error() to the string "400 Bad request
1819       (malformed multipart POST)".  This error message is designed so that
1820       you can incorporate it into a status code to be sent to the browser.
1821       Example:
1822
1823          $file = $q->upload('uploaded_file');
1824          if (!$file && $q->cgi_error) {
1825             print $q->header(-status=>$q->cgi_error);
1826             exit 0;
1827          }
1828
1829       You are free to create a custom HTML page to complain about the error,
1830       if you wish.
1831
1832       Progress bars for file uploads and avoiding temp files
1833
1834       CGI.pm gives you low-level access to file upload management through a
1835       file upload hook. You can use this feature to completely turn off the
1836       temp file storage of file uploads, or potentially write your own file
1837       upload progress meter.
1838
1839       This is much like the UPLOAD_HOOK facility available in
1840       Apache::Request, with the exception that the first argument to the
1841       callback is an Apache::Upload object, here it's the remote filename.
1842
1843        $q = CGI->new(\&hook [,$data [,$use_tempfile]]);
1844
1845        sub hook {
1846               my ($filename, $buffer, $bytes_read, $data) = @_;
1847               print  "Read $bytes_read bytes of $filename\n";
1848        }
1849
1850       The $data field is optional; it lets you pass configuration information
1851       (e.g. a database handle) to your hook callback.
1852
1853       The $use_tempfile field is a flag that lets you turn on and off
1854       CGI.pm's use of a temporary disk-based file during file upload. If you
1855       set this to a FALSE value (default true) then
1856       $q->param('uploaded_file') will no longer work, and the only way to get
1857       at the uploaded data is via the hook you provide.
1858
1859       If using the function-oriented interface, call the CGI::upload_hook()
1860       method before calling param() or any other CGI functions:
1861
1862         CGI::upload_hook(\&hook [,$data [,$use_tempfile]]);
1863
1864       This method is not exported by default.  You will have to import it
1865       explicitly if you wish to use it without the CGI:: prefix.
1866
1867       Troubleshooting file uploads on Windows
1868
1869       If you are using CGI.pm on a Windows platform and find that binary
1870       files get slightly larger when uploaded but that text files remain the
1871       same, then you have forgotten to activate binary mode on the output
1872       filehandle.  Be sure to call binmode() on any handle that you create to
1873       write the uploaded file to disk.
1874
1875       Older ways to process file uploads
1876
1877       ( This section is here for completeness. if you are building a new
1878       application with CGI.pm, you can skip it. )
1879
1880       The original way to process file uploads with CGI.pm was to use
1881       param(). The value it returns has a dual nature as both a file name and
1882       a lightweight filehandle. This dual nature is problematic if you
1883       following the recommended practice of having "use strict" in your code.
1884       Perl will complain when you try to use a string as a filehandle.  More
1885       seriously, it is possible for the remote user to type garbage into the
1886       upload field, in which case what you get from param() is not a
1887       filehandle at all, but a string.
1888
1889       To solve this problem the upload() method was added, which always
1890       returns a lightweight filehandle. This generally works well, but will
1891       have trouble interoperating with some other modules because the file
1892       handle is not derived from IO::Handle. So that brings us to current
1893       recommendation given above, which is to call the handle() method on the
1894       file handle returned by upload().  That upgrades the handle to an
1895       IO::Handle. It's a big win for compatibility for a small penalty of
1896       loading IO::Handle the first time you call it.
1897
1898   CREATING A POPUP MENU
1899          print popup_menu('menu_name',
1900                                   ['eenie','meenie','minie'],
1901                                   'meenie');
1902
1903             -or-
1904
1905          %labels = ('eenie'=>'your first choice',
1906                     'meenie'=>'your second choice',
1907                     'minie'=>'your third choice');
1908          %attributes = ('eenie'=>{'class'=>'class of first choice'});
1909          print popup_menu('menu_name',
1910                                   ['eenie','meenie','minie'],
1911                 'meenie',\%labels,\%attributes);
1912
1913               -or (named parameter style)-
1914
1915          print popup_menu(-name=>'menu_name',
1916                                   -values=>['eenie','meenie','minie'],
1917                                   -default=>['meenie','minie'],
1918                 -labels=>\%labels,
1919                 -attributes=>\%attributes);
1920
1921       popup_menu() creates a menu.
1922
1923       1.  The required first argument is the menu's name (-name).
1924
1925       2.  The required second argument (-values) is an array reference
1926           containing the list of menu items in the menu.  You can pass the
1927           method an anonymous array, as shown in the example, or a reference
1928           to a named array, such as "\@foo".
1929
1930       3.  The optional third parameter (-default) is the name of the default
1931           menu choice.  If not specified, the first item will be the default.
1932           The values of the previous choice will be maintained across
1933           queries. Pass an array reference to select multiple defaults.
1934
1935       4.  The optional fourth parameter (-labels) is provided for people who
1936           want to use different values for the user-visible label inside the
1937           popup menu and the value returned to your script.  It's a pointer
1938           to an hash relating menu values to user-visible labels.  If you
1939           leave this parameter blank, the menu values will be displayed by
1940           default.  (You can also leave a label undefined if you want to).
1941
1942       5.  The optional fifth parameter (-attributes) is provided to assign
1943           any of the common HTML attributes to an individual menu item. It's
1944           a pointer to a hash relating menu values to another hash with the
1945           attribute's name as the key and the attribute's value as the value.
1946
1947       When the form is processed, the selected value of the popup menu can be
1948       retrieved using:
1949
1950             $popup_menu_value = param('menu_name');
1951
1952   CREATING AN OPTION GROUP
1953       Named parameter style
1954
1955         print popup_menu(-name=>'menu_name',
1956                         -values=>[qw/eenie meenie minie/,
1957                                   optgroup(-name=>'optgroup_name',
1958                                                    -values => ['moe','catch'],
1959                                                    -attributes=>{'catch'=>{'class'=>'red'}})],
1960                         -labels=>{'eenie'=>'one',
1961                                   'meenie'=>'two',
1962                                   'minie'=>'three'},
1963                         -default=>'meenie');
1964
1965         Old style
1966         print popup_menu('menu_name',
1967                         ['eenie','meenie','minie',
1968                          optgroup('optgroup_name', ['moe', 'catch'],
1969                                          {'catch'=>{'class'=>'red'}})],'meenie',
1970                         {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
1971
1972       optgroup() creates an option group within a popup menu.
1973
1974       1.  The required first argument (-name) is the label attribute of the
1975           optgroup and is not inserted in the parameter list of the query.
1976
1977       2.  The required second argument (-values)  is an array reference
1978           containing the list of menu items in the menu.  You can pass the
1979           method an anonymous array, as shown in the example, or a reference
1980           to a named array, such as \@foo.  If you pass a HASH reference, the
1981           keys will be used for the menu values, and the values will be used
1982           for the menu labels (see -labels below).
1983
1984       3.  The optional third parameter (-labels) allows you to pass a
1985           reference to a hash containing user-visible labels for one or more
1986           of the menu items.  You can use this when you want the user to see
1987           one menu string, but have the browser return your program a
1988           different one.  If you don't specify this, the value string will be
1989           used instead ("eenie", "meenie" and "minie" in this example).  This
1990           is equivalent to using a hash reference for the -values parameter.
1991
1992       4.  An optional fourth parameter (-labeled) can be set to a true value
1993           and indicates that the values should be used as the label attribute
1994           for each option element within the optgroup.
1995
1996       5.  An optional fifth parameter (-novals) can be set to a true value
1997           and indicates to suppress the val attribute in each option element
1998           within the optgroup.
1999
2000           See the discussion on optgroup at W3C
2001           (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
2002           for details.
2003
2004       6.  An optional sixth parameter (-attributes) is provided to assign any
2005           of the common HTML attributes to an individual menu item. It's a
2006           pointer to a hash relating menu values to another hash with the
2007           attribute's name as the key and the attribute's value as the value.
2008
2009   CREATING A SCROLLING LIST
2010          print scrolling_list('list_name',
2011                                       ['eenie','meenie','minie','moe'],
2012               ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
2013             -or-
2014
2015          print scrolling_list('list_name',
2016                                       ['eenie','meenie','minie','moe'],
2017                                       ['eenie','moe'],5,'true',
2018               \%labels,%attributes);
2019
2020               -or-
2021
2022          print scrolling_list(-name=>'list_name',
2023                                       -values=>['eenie','meenie','minie','moe'],
2024                                       -default=>['eenie','moe'],
2025                                       -size=>5,
2026                                       -multiple=>'true',
2027               -labels=>\%labels,
2028               -attributes=>\%attributes);
2029
2030       scrolling_list() creates a scrolling list.
2031
2032       Parameters:
2033       1.  The first and second arguments are the list name (-name) and values
2034           (-values).  As in the popup menu, the second argument should be an
2035           array reference.
2036
2037       2.  The optional third argument (-default) can be either a reference to
2038           a list containing the values to be selected by default, or can be a
2039           single value to select.  If this argument is missing or undefined,
2040           then nothing is selected when the list first appears.  In the named
2041           parameter version, you can use the synonym "-defaults" for this
2042           parameter.
2043
2044       3.  The optional fourth argument is the size of the list (-size).
2045
2046       4.  The optional fifth argument can be set to true to allow multiple
2047           simultaneous selections (-multiple).  Otherwise only one selection
2048           will be allowed at a time.
2049
2050       5.  The optional sixth argument is a pointer to a hash containing long
2051           user-visible labels for the list items (-labels).  If not provided,
2052           the values will be displayed.
2053
2054       6.  The optional sixth parameter (-attributes) is provided to assign
2055           any of the common HTML attributes to an individual menu item. It's
2056           a pointer to a hash relating menu values to another hash with the
2057           attribute's name as the key and the attribute's value as the value.
2058
2059           When this form is processed, all selected list items will be
2060           returned as a list under the parameter name 'list_name'.  The
2061           values of the selected items can be retrieved with:
2062
2063                 @selected = param('list_name');
2064
2065   CREATING A GROUP OF RELATED CHECKBOXES
2066          print checkbox_group(-name=>'group_name',
2067                                       -values=>['eenie','meenie','minie','moe'],
2068                                       -default=>['eenie','moe'],
2069                                       -linebreak=>'true',
2070                                       -disabled => ['moe'],
2071               -labels=>\%labels,
2072               -attributes=>\%attributes);
2073
2074          print checkbox_group('group_name',
2075                                       ['eenie','meenie','minie','moe'],
2076               ['eenie','moe'],'true',\%labels,
2077               {'moe'=>{'class'=>'red'}});
2078
2079          HTML3-COMPATIBLE BROWSERS ONLY:
2080
2081          print checkbox_group(-name=>'group_name',
2082                                       -values=>['eenie','meenie','minie','moe'],
2083                                       -rows=2,-columns=>2);
2084
2085       checkbox_group() creates a list of checkboxes that are related by the
2086       same name.
2087
2088       Parameters:
2089       1.  The first and second arguments are the checkbox name and values,
2090           respectively (-name and -values).  As in the popup menu, the second
2091           argument should be an array reference.  These values are used for
2092           the user-readable labels printed next to the checkboxes as well as
2093           for the values passed to your script in the query string.
2094
2095       2.  The optional third argument (-default) can be either a reference to
2096           a list containing the values to be checked by default, or can be a
2097           single value to checked.  If this argument is missing or undefined,
2098           then nothing is selected when the list first appears.
2099
2100       3.  The optional fourth argument (-linebreak) can be set to true to
2101           place line breaks between the checkboxes so that they appear as a
2102           vertical list.  Otherwise, they will be strung together on a
2103           horizontal line.
2104
2105       The optional -labels argument is a pointer to a hash relating the
2106       checkbox values to the user-visible labels that will be printed next to
2107       them.  If not provided, the values will be used as the default.
2108
2109       The optional parameters -rows, and -columns cause checkbox_group() to
2110       return an HTML3 compatible table containing the checkbox group
2111       formatted with the specified number of rows and columns.  You can
2112       provide just the -columns parameter if you wish; checkbox_group will
2113       calculate the correct number of rows for you.
2114
2115       The option -disabled takes an array of checkbox values and disables
2116       them by greying them out (this may not be supported by all browsers).
2117
2118       The optional -attributes argument is provided to assign any of the
2119       common HTML attributes to an individual menu item. It's a pointer to a
2120       hash relating menu values to another hash with the attribute's name as
2121       the key and the attribute's value as the value.
2122
2123       The optional -tabindex argument can be used to control the order in
2124       which radio buttons receive focus when the user presses the tab button.
2125       If passed a scalar numeric value, the first element in the group will
2126       receive this tab index and subsequent elements will be incremented by
2127       one.  If given a reference to an array of radio button values, then the
2128       indexes will be jiggered so that the order specified in the array will
2129       correspond to the tab order.  You can also pass a reference to a hash
2130       in which the hash keys are the radio button values and the values are
2131       the tab indexes of each button.  Examples:
2132
2133         -tabindex => 100    #  this group starts at index 100 and counts up
2134         -tabindex => ['moe','minie','eenie','meenie']  # tab in this order
2135         -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2136
2137       The optional -labelattributes argument will contain attributes attached
2138       to the <label> element that surrounds each button.
2139
2140       When the form is processed, all checked boxes will be returned as a
2141       list under the parameter name 'group_name'.  The values of the "on"
2142       checkboxes can be retrieved with:
2143
2144             @turned_on = param('group_name');
2145
2146       The value returned by checkbox_group() is actually an array of button
2147       elements.  You can capture them and use them within tables, lists, or
2148       in other creative ways:
2149
2150           @h = checkbox_group(-name=>'group_name',-values=>\@values);
2151           &use_in_creative_way(@h);
2152
2153   CREATING A STANDALONE CHECKBOX
2154           print checkbox(-name=>'checkbox_name',
2155                                  -checked=>1,
2156                                  -value=>'ON',
2157                                  -label=>'CLICK ME');
2158
2159               -or-
2160
2161           print checkbox('checkbox_name','checked','ON','CLICK ME');
2162
2163       checkbox() is used to create an isolated checkbox that isn't logically
2164       related to any others.
2165
2166       Parameters:
2167       1.  The first parameter is the required name for the checkbox (-name).
2168           It will also be used for the user-readable label printed next to
2169           the checkbox.
2170
2171       2.  The optional second parameter (-checked) specifies that the
2172           checkbox is turned on by default.  Synonyms are -selected and -on.
2173
2174       3.  The optional third parameter (-value) specifies the value of the
2175           checkbox when it is checked.  If not provided, the word "on" is
2176           assumed.
2177
2178       4.  The optional fourth parameter (-label) is the user-readable label
2179           to be attached to the checkbox.  If not provided, the checkbox name
2180           is used.
2181
2182       The value of the checkbox can be retrieved using:
2183
2184           $turned_on = param('checkbox_name');
2185
2186   CREATING A RADIO BUTTON GROUP
2187          print radio_group(-name=>'group_name',
2188                                    -values=>['eenie','meenie','minie'],
2189                                    -default=>'meenie',
2190                                    -linebreak=>'true',
2191                  -labels=>\%labels,
2192                  -attributes=>\%attributes);
2193
2194               -or-
2195
2196          print radio_group('group_name',['eenie','meenie','minie'],
2197                   'meenie','true',\%labels,\%attributes);
2198
2199
2200          HTML3-COMPATIBLE BROWSERS ONLY:
2201
2202          print radio_group(-name=>'group_name',
2203                                    -values=>['eenie','meenie','minie','moe'],
2204                                    -rows=2,-columns=>2);
2205
2206       radio_group() creates a set of logically-related radio buttons (turning
2207       one member of the group on turns the others off)
2208
2209       Parameters:
2210       1.  The first argument is the name of the group and is required
2211           (-name).
2212
2213       2.  The second argument (-values) is the list of values for the radio
2214           buttons.  The values and the labels that appear on the page are
2215           identical.  Pass an array reference in the second argument, either
2216           using an anonymous array, as shown, or by referencing a named array
2217           as in "\@foo".
2218
2219       3.  The optional third parameter (-default) is the name of the default
2220           button to turn on. If not specified, the first item will be the
2221           default.  You can provide a nonexistent button name, such as "-" to
2222           start up with no buttons selected.
2223
2224       4.  The optional fourth parameter (-linebreak) can be set to 'true' to
2225           put line breaks between the buttons, creating a vertical list.
2226
2227       5.  The optional fifth parameter (-labels) is a pointer to an
2228           associative array relating the radio button values to user-visible
2229           labels to be used in the display.  If not provided, the values
2230           themselves are displayed.
2231
2232       All modern browsers can take advantage of the optional parameters
2233       -rows, and -columns.  These parameters cause radio_group() to return an
2234       HTML3 compatible table containing the radio group formatted with the
2235       specified number of rows and columns.  You can provide just the
2236       -columns parameter if you wish; radio_group will calculate the correct
2237       number of rows for you.
2238
2239       To include row and column headings in the returned table, you can use
2240       the -rowheaders and -colheaders parameters.  Both of these accept a
2241       pointer to an array of headings to use.  The headings are just
2242       decorative.  They don't reorganize the interpretation of the radio
2243       buttons -- they're still a single named unit.
2244
2245       The optional -tabindex argument can be used to control the order in
2246       which radio buttons receive focus when the user presses the tab button.
2247       If passed a scalar numeric value, the first element in the group will
2248       receive this tab index and subsequent elements will be incremented by
2249       one.  If given a reference to an array of radio button values, then the
2250       indexes will be jiggered so that the order specified in the array will
2251       correspond to the tab order.  You can also pass a reference to a hash
2252       in which the hash keys are the radio button values and the values are
2253       the tab indexes of each button.  Examples:
2254
2255         -tabindex => 100    #  this group starts at index 100 and counts up
2256         -tabindex => ['moe','minie','eenie','meenie']  # tab in this order
2257         -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2258
2259       The optional -attributes argument is provided to assign any of the
2260       common HTML attributes to an individual menu item. It's a pointer to a
2261       hash relating menu values to another hash with the attribute's name as
2262       the key and the attribute's value as the value.
2263
2264       The optional -labelattributes argument will contain attributes attached
2265       to the <label> element that surrounds each button.
2266
2267       When the form is processed, the selected radio button can be retrieved
2268       using:
2269
2270             $which_radio_button = param('group_name');
2271
2272       The value returned by radio_group() is actually an array of button
2273       elements.  You can capture them and use them within tables, lists, or
2274       in other creative ways:
2275
2276           @h = radio_group(-name=>'group_name',-values=>\@values);
2277           &use_in_creative_way(@h);
2278
2279   CREATING A SUBMIT BUTTON
2280          print submit(-name=>'button_name',
2281                               -value=>'value');
2282
2283               -or-
2284
2285          print submit('button_name','value');
2286
2287       submit() will create the query submission button.  Every form should
2288       have one of these.
2289
2290       Parameters:
2291       1.  The first argument (-name) is optional.  You can give the button a
2292           name if you have several submission buttons in your form and you
2293           want to distinguish between them.
2294
2295       2.  The second argument (-value) is also optional.  This gives the
2296           button a value that will be passed to your script in the query
2297           string. The name will also be used as the user-visible label.
2298
2299       3.  You can use -label as an alias for -value.  I always get confused
2300           about which of -name and -value changes the user-visible label on
2301           the button.
2302
2303       You can figure out which button was pressed by using different values
2304       for each one:
2305
2306            $which_one = param('button_name');
2307
2308   CREATING A RESET BUTTON
2309          print reset
2310
2311       reset() creates the "reset" button.  Note that it restores the form to
2312       its value from the last time the script was called, NOT necessarily to
2313       the defaults.
2314
2315       Note that this conflicts with the Perl reset() built-in.  Use
2316       CORE::reset() to get the original reset function.
2317
2318   CREATING A DEFAULT BUTTON
2319          print defaults('button_label')
2320
2321       defaults() creates a button that, when invoked, will cause the form to
2322       be completely reset to its defaults, wiping out all the changes the
2323       user ever made.
2324
2325   CREATING A HIDDEN FIELD
2326               print hidden(-name=>'hidden_name',
2327                                    -default=>['value1','value2'...]);
2328
2329                       -or-
2330
2331               print hidden('hidden_name','value1','value2'...);
2332
2333       hidden() produces a text field that can't be seen by the user.  It is
2334       useful for passing state variable information from one invocation of
2335       the script to the next.
2336
2337       Parameters:
2338       1.  The first argument is required and specifies the name of this field
2339           (-name).
2340
2341       2.  The second argument is also required and specifies its value
2342           (-default).  In the named parameter style of calling, you can
2343           provide a single value here or a reference to a whole list
2344
2345       Fetch the value of a hidden field this way:
2346
2347            $hidden_value = param('hidden_name');
2348
2349       Note, that just like all the other form elements, the value of a hidden
2350       field is "sticky".  If you want to replace a hidden field with some
2351       other values after the script has been called once you'll have to do it
2352       manually:
2353
2354            param('hidden_name','new','values','here');
2355
2356   CREATING A CLICKABLE IMAGE BUTTON
2357            print image_button(-name=>'button_name',
2358                                       -src=>'/source/URL',
2359                                       -align=>'MIDDLE');
2360
2361               -or-
2362
2363            print image_button('button_name','/source/URL','MIDDLE');
2364
2365       image_button() produces a clickable image.  When it's clicked on the
2366       position of the click is returned to your script as "button_name.x" and
2367       "button_name.y", where "button_name" is the name you've assigned to it.
2368
2369       Parameters:
2370       1.  The first argument (-name) is required and specifies the name of
2371           this field.
2372
2373       2.  The second argument (-src) is also required and specifies the URL
2374
2375       3. The third option (-align, optional) is an alignment type, and may be
2376       TOP, BOTTOM or MIDDLE
2377
2378       Fetch the value of the button this way:
2379            $x = param('button_name.x');
2380            $y = param('button_name.y');
2381
2382   CREATING A JAVASCRIPT ACTION BUTTON
2383            print button(-name=>'button_name',
2384                                 -value=>'user visible label',
2385                                 -onClick=>"do_something()");
2386
2387               -or-
2388
2389            print button('button_name',"user visible value","do_something()");
2390
2391       button() produces an "<input>" tag with "type="button"".  When it's
2392       pressed the fragment of JavaScript code pointed to by the -onClick
2393       parameter will be executed.
2394

HTTP COOKIES

2396       Browsers support a so-called "cookie" designed to help maintain state
2397       within a browser session.  CGI.pm has several methods that support
2398       cookies.
2399
2400       A cookie is a name=value pair much like the named parameters in a CGI
2401       query string.  CGI scripts create one or more cookies and send them to
2402       the browser in the HTTP header.  The browser maintains a list of
2403       cookies that belong to a particular Web server, and returns them to the
2404       CGI script during subsequent interactions.
2405
2406       In addition to the required name=value pair, each cookie has several
2407       optional attributes:
2408
2409       1. an expiration time
2410           This is a time/date string (in a special GMT format) that indicates
2411           when a cookie expires.  The cookie will be saved and returned to
2412           your script until this expiration date is reached if the user exits
2413           the browser and restarts it.  If an expiration date isn't
2414           specified, the cookie will remain active until the user quits the
2415           browser.
2416
2417       2. a domain
2418           This is a partial or complete domain name for which the cookie is
2419           valid.  The browser will return the cookie to any host that matches
2420           the partial domain name.  For example, if you specify a domain name
2421           of ".capricorn.com", then the browser will return the cookie to Web
2422           servers running on any of the machines "www.capricorn.com",
2423           "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
2424           must contain at least two periods to prevent attempts to match on
2425           top level domains like ".edu".  If no domain is specified, then the
2426           browser will only return the cookie to servers on the host the
2427           cookie originated from.
2428
2429       3. a path
2430           If you provide a cookie path attribute, the browser will check it
2431           against your script's URL before returning the cookie.  For
2432           example, if you specify the path "/cgi-bin", then the cookie will
2433           be returned to each of the scripts "/cgi-bin/tally.pl",
2434           "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
2435           but not to the script "/cgi-private/site_admin.pl".  By default,
2436           path is set to "/", which causes the cookie to be sent to any CGI
2437           script on your site.
2438
2439       4. a "secure" flag
2440           If the "secure" attribute is set, the cookie will only be sent to
2441           your script if the CGI request is occurring on a secure channel,
2442           such as SSL.
2443
2444       The interface to HTTP cookies is the cookie() method:
2445
2446           $cookie = cookie(-name=>'sessionID',
2447                                    -value=>'xyzzy',
2448                                    -expires=>'+1h',
2449                                    -path=>'/cgi-bin/database',
2450                                    -domain=>'.capricorn.org',
2451                                    -secure=>1);
2452           print header(-cookie=>$cookie);
2453
2454       cookie() creates a new cookie.  Its parameters include:
2455
2456       -name
2457           The name of the cookie (required).  This can be any string at all.
2458           Although browsers limit their cookie names to non-whitespace
2459           alphanumeric characters, CGI.pm removes this restriction by
2460           escaping and unescaping cookies behind the scenes.
2461
2462       -value
2463           The value of the cookie.  This can be any scalar value, array
2464           reference, or even hash reference.  For example, you can store an
2465           entire hash into a cookie this way:
2466
2467                   $cookie=cookie(-name=>'family information',
2468                                          -value=>\%childrens_ages);
2469
2470       -path
2471           The optional partial path for which this cookie will be valid, as
2472           described above.
2473
2474       -domain
2475           The optional partial domain for which this cookie will be valid, as
2476           described above.
2477
2478       -expires
2479           The optional expiration date for this cookie.  The format is as
2480           described in the section on the header() method:
2481
2482                   "+1h"  one hour from now
2483
2484       -secure
2485           If set to true, this cookie will only be used within a secure SSL
2486           session.
2487
2488       The cookie created by cookie() must be incorporated into the HTTP
2489       header within the string returned by the header() method:
2490
2491               use CGI ':standard';
2492               print header(-cookie=>$my_cookie);
2493
2494       To create multiple cookies, give header() an array reference:
2495
2496               $cookie1 = cookie(-name=>'riddle_name',
2497                                         -value=>"The Sphynx's Question");
2498               $cookie2 = cookie(-name=>'answers',
2499                                         -value=>\%answers);
2500               print header(-cookie=>[$cookie1,$cookie2]);
2501
2502       To retrieve a cookie, request it by name by calling cookie() method
2503       without the -value parameter. This example uses the object-oriented
2504       form:
2505
2506               use CGI;
2507               $query = CGI->new;
2508               $riddle = $query->cookie('riddle_name');
2509               %answers = $query->cookie('answers');
2510
2511       Cookies created with a single scalar value, such as the "riddle_name"
2512       cookie, will be returned in that form.  Cookies with array and hash
2513       values can also be retrieved.
2514
2515       The cookie and CGI namespaces are separate.  If you have a parameter
2516       named 'answers' and a cookie named 'answers', the values retrieved by
2517       param() and cookie() are independent of each other.  However, it's
2518       simple to turn a CGI parameter into a cookie, and vice-versa:
2519
2520          # turn a CGI parameter into a cookie
2521          $c=cookie(-name=>'answers',-value=>[param('answers')]);
2522          # vice-versa
2523          param(-name=>'answers',-value=>[cookie('answers')]);
2524
2525       If you call cookie() without any parameters, it will return a list of
2526       the names of all cookies passed to your script:
2527
2528         @cookies = cookie();
2529
2530       See the cookie.cgi example script for some ideas on how to use cookies
2531       effectively.
2532

WORKING WITH FRAMES

2534       It's possible for CGI.pm scripts to write into several browser panels
2535       and windows using the HTML 4 frame mechanism.  There are three
2536       techniques for defining new frames programmatically:
2537
2538       1. Create a <Frameset> document
2539           After writing out the HTTP header, instead of creating a standard
2540           HTML document using the start_html() call, create a <frameset>
2541           document that defines the frames on the page.  Specify your
2542           script(s) (with appropriate parameters) as the SRC for each of the
2543           frames.
2544
2545           There is no specific support for creating <frameset> sections in
2546           CGI.pm, but the HTML is very simple to write.
2547
2548       2. Specify the destination for the document in the HTTP header
2549           You may provide a -target parameter to the header() method:
2550
2551               print header(-target=>'ResultsWindow');
2552
2553           This will tell the browser to load the output of your script into
2554           the frame named "ResultsWindow".  If a frame of that name doesn't
2555           already exist, the browser will pop up a new window and load your
2556           script's document into that.  There are a number of magic names
2557           that you can use for targets.  See the HTML "<frame>" documentation
2558           for details.
2559
2560       3. Specify the destination for the document in the <form> tag
2561           You can specify the frame to load in the FORM tag itself.  With
2562           CGI.pm it looks like this:
2563
2564               print start_form(-target=>'ResultsWindow');
2565
2566           When your script is reinvoked by the form, its output will be
2567           loaded into the frame named "ResultsWindow".  If one doesn't
2568           already exist a new window will be created.
2569
2570       The script "frameset.cgi" in the examples directory shows one way to
2571       create pages in which the fill-out form and the response live in side-
2572       by-side frames.
2573

SUPPORT FOR JAVASCRIPT

2575       The usual way to use JavaScript is to define a set of functions in a
2576       <SCRIPT> block inside the HTML header and then to register event
2577       handlers in the various elements of the page. Events include such
2578       things as the mouse passing over a form element, a button being
2579       clicked, the contents of a text field changing, or a form being
2580       submitted. When an event occurs that involves an element that has
2581       registered an event handler, its associated JavaScript code gets
2582       called.
2583
2584       The elements that can register event handlers include the <BODY> of an
2585       HTML document, hypertext links, all the various elements of a fill-out
2586       form, and the form itself. There are a large number of events, and each
2587       applies only to the elements for which it is relevant. Here is a
2588       partial list:
2589
2590       onLoad
2591           The browser is loading the current document. Valid in:
2592
2593                + The HTML <BODY> section only.
2594
2595       onUnload
2596           The browser is closing the current page or frame. Valid for:
2597
2598                + The HTML <BODY> section only.
2599
2600       onSubmit
2601           The user has pressed the submit button of a form. This event
2602           happens just before the form is submitted, and your function can
2603           return a value of false in order to abort the submission.  Valid
2604           for:
2605
2606                + Forms only.
2607
2608       onClick
2609           The mouse has clicked on an item in a fill-out form. Valid for:
2610
2611                + Buttons (including submit, reset, and image buttons)
2612                + Checkboxes
2613                + Radio buttons
2614
2615       onChange
2616           The user has changed the contents of a field. Valid for:
2617
2618                + Text fields
2619                + Text areas
2620                + Password fields
2621                + File fields
2622                + Popup Menus
2623                + Scrolling lists
2624
2625       onFocus
2626           The user has selected a field to work with. Valid for:
2627
2628                + Text fields
2629                + Text areas
2630                + Password fields
2631                + File fields
2632                + Popup Menus
2633                + Scrolling lists
2634
2635       onBlur
2636           The user has deselected a field (gone to work somewhere else).
2637           Valid for:
2638
2639                + Text fields
2640                + Text areas
2641                + Password fields
2642                + File fields
2643                + Popup Menus
2644                + Scrolling lists
2645
2646       onSelect
2647           The user has changed the part of a text field that is selected.
2648           Valid for:
2649
2650                + Text fields
2651                + Text areas
2652                + Password fields
2653                + File fields
2654
2655       onMouseOver
2656           The mouse has moved over an element.
2657
2658                + Text fields
2659                + Text areas
2660                + Password fields
2661                + File fields
2662                + Popup Menus
2663                + Scrolling lists
2664
2665       onMouseOut
2666           The mouse has moved off an element.
2667
2668                + Text fields
2669                + Text areas
2670                + Password fields
2671                + File fields
2672                + Popup Menus
2673                + Scrolling lists
2674
2675       In order to register a JavaScript event handler with an HTML element,
2676       just use the event name as a parameter when you call the corresponding
2677       CGI method. For example, to have your validateAge() JavaScript code
2678       executed every time the textfield named "age" changes, generate the
2679       field like this:
2680
2681        print textfield(-name=>'age',-onChange=>"validateAge(this)");
2682
2683       This example assumes that you've already declared the validateAge()
2684       function by incorporating it into a <SCRIPT> block. The CGI.pm
2685       start_html() method provides a convenient way to create this section.
2686
2687       Similarly, you can create a form that checks itself over for
2688       consistency and alerts the user if some essential value is missing by
2689       creating it this way:
2690         print start_form(-onSubmit=>"validateMe(this)");
2691
2692       See the javascript.cgi script for a demonstration of how this all
2693       works.
2694

LIMITED SUPPORT FOR CASCADING STYLE SHEETS

2696       CGI.pm has limited support for HTML3's cascading style sheets (css).
2697       To incorporate a stylesheet into your document, pass the start_html()
2698       method a -style parameter.  The value of this parameter may be a
2699       scalar, in which case it is treated as the source URL for the
2700       stylesheet, or it may be a hash reference.  In the latter case you
2701       should provide the hash with one or more of -src or -code.  -src points
2702       to a URL where an externally-defined stylesheet can be found.  -code
2703       points to a scalar value to be incorporated into a <style> section.
2704       Style definitions in -code override similarly-named ones in -src, hence
2705       the name "cascading."
2706
2707       You may also specify the type of the stylesheet by adding the optional
2708       -type parameter to the hash pointed to by -style.  If not specified,
2709       the style defaults to 'text/css'.
2710
2711       To refer to a style within the body of your document, add the -class
2712       parameter to any HTML element:
2713
2714           print h1({-class=>'Fancy'},'Welcome to the Party');
2715
2716       Or define styles on the fly with the -style parameter:
2717
2718           print h1({-style=>'Color: red;'},'Welcome to Hell');
2719
2720       You may also use the new span() element to apply a style to a section
2721       of text:
2722
2723           print span({-style=>'Color: red;'},
2724                      h1('Welcome to Hell'),
2725                      "Where did that handbasket get to?"
2726                      );
2727
2728       Note that you must import the ":html3" definitions to have the span()
2729       method available.  Here's a quick and dirty example of using CSS's.
2730       See the CSS specification at http://www.w3.org/Style/CSS/ for more
2731       information.
2732
2733           use CGI qw/:standard :html3/;
2734
2735           #here's a stylesheet incorporated directly into the page
2736           $newStyle=<<END;
2737           <!--
2738           P.Tip {
2739               margin-right: 50pt;
2740               margin-left: 50pt;
2741               color: red;
2742           }
2743           P.Alert {
2744               font-size: 30pt;
2745               font-family: sans-serif;
2746             color: red;
2747           }
2748           -->
2749           END
2750           print header();
2751           print start_html( -title=>'CGI with Style',
2752                             -style=>{-src=>'http://www.capricorn.com/style/st1.css',
2753                                      -code=>$newStyle}
2754                            );
2755           print h1('CGI with Style'),
2756                 p({-class=>'Tip'},
2757                   "Better read the cascading style sheet spec before playing with this!"),
2758                 span({-style=>'color: magenta'},
2759                      "Look Mom, no hands!",
2760                      p(),
2761                      "Whooo wee!"
2762                      );
2763           print end_html;
2764
2765       Pass an array reference to -code or -src in order to incorporate
2766       multiple stylesheets into your document.
2767
2768       Should you wish to incorporate a verbatim stylesheet that includes
2769       arbitrary formatting in the header, you may pass a -verbatim tag to the
2770       -style hash, as follows:
2771
2772       print start_html (-style  =>  {-verbatim => '@import
2773       url("/server-common/css/'.$cssFile.'");',
2774                         -src    =>  '/server-common/css/core.css'});
2775
2776       This will generate an HTML header that contains this:
2777
2778        <link rel="stylesheet" type="text/css"  href="/server-common/css/core.css">
2779          <style type="text/css">
2780          @import url("/server-common/css/main.css");
2781          </style>
2782
2783       Any additional arguments passed in the -style value will be
2784       incorporated into the <link> tag.  For example:
2785
2786        start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
2787                                 -media => 'all'});
2788
2789       This will give:
2790
2791        <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
2792        <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
2793
2794       <p>
2795
2796       To make more complicated <link> tags, use the Link() function and pass
2797       it to start_html() in the -head argument, as in:
2798
2799         @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
2800               Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
2801         print start_html({-head=>\@h})
2802
2803       To create primary and  "alternate" stylesheet, use the -alternate
2804       option:
2805
2806        start_html(-style=>{-src=>[
2807                                  {-src=>'/styles/print.css'},
2808                                  {-src=>'/styles/alt.css',-alternate=>1}
2809                                  ]
2810                           });
2811

DEBUGGING

2813       If you are running the script from the command line or in the perl
2814       debugger, you can pass the script a list of keywords or parameter=value
2815       pairs on the command line or from standard input (you don't have to
2816       worry about tricking your script into reading from environment
2817       variables).  You can pass keywords like this:
2818
2819           your_script.pl keyword1 keyword2 keyword3
2820
2821       or this:
2822
2823          your_script.pl keyword1+keyword2+keyword3
2824
2825       or this:
2826
2827           your_script.pl name1=value1 name2=value2
2828
2829       or this:
2830
2831           your_script.pl name1=value1&name2=value2
2832
2833       To turn off this feature, use the -no_debug pragma.
2834
2835       To test the POST method, you may enable full debugging with the -debug
2836       pragma.  This will allow you to feed newline-delimited name=value pairs
2837       to the script on standard input.
2838
2839       When debugging, you can use quotes and backslashes to escape characters
2840       in the familiar shell manner, letting you place spaces and other funny
2841       characters in your parameter=value pairs:
2842
2843          your_script.pl "name1='I am a long value'" "name2=two\ words"
2844
2845       Finally, you can set the path info for the script by prefixing the
2846       first name/value parameter with the path followed by a question mark
2847       (?):
2848
2849           your_script.pl /your/path/here?name1=value1&name2=value2
2850
2851   DUMPING OUT ALL THE NAME/VALUE PAIRS
2852       The Dump() method produces a string consisting of all the query's
2853       name/value pairs formatted nicely as a nested list.  This is useful for
2854       debugging purposes:
2855
2856           print Dump
2857
2858       Produces something that looks like:
2859
2860           <ul>
2861           <li>name1
2862               <ul>
2863               <li>value1
2864               <li>value2
2865               </ul>
2866           <li>name2
2867               <ul>
2868               <li>value1
2869               </ul>
2870           </ul>
2871
2872       As a shortcut, you can interpolate the entire CGI object into a string
2873       and it will be replaced with the a nice HTML dump shown above:
2874
2875           $query=CGI->new;
2876           print "<h2>Current Values</h2> $query\n";
2877

FETCHING ENVIRONMENT VARIABLES

2879       Some of the more useful environment variables can be fetched through
2880       this interface.  The methods are as follows:
2881
2882       Accept()
2883           Return a list of MIME types that the remote browser accepts. If you
2884           give this method a single argument corresponding to a MIME type, as
2885           in Accept('text/html'), it will return a floating point value
2886           corresponding to the browser's preference for this type from 0.0
2887           (don't want) to 1.0.  Glob types (e.g. text/*) in the browser's
2888           accept list are handled correctly.
2889
2890           Note that the capitalization changed between version 2.43 and 2.44
2891           in order to avoid conflict with Perl's accept() function.
2892
2893       raw_cookie()
2894           Returns the HTTP_COOKIE variable.  Cookies have a special format,
2895           and this method call just returns the raw form (?cookie dough).
2896           See cookie() for ways of setting and retrieving cooked cookies.
2897
2898           Called with no parameters, raw_cookie() returns the packed cookie
2899           structure.  You can separate it into individual cookies by
2900           splitting on the character sequence "; ".  Called with the name of
2901           a cookie, retrieves the unescaped form of the cookie.  You can use
2902           the regular cookie() method to get the names, or use the
2903           raw_fetch() method from the CGI::Cookie module.
2904
2905       user_agent()
2906           Returns the HTTP_USER_AGENT variable.  If you give this method a
2907           single argument, it will attempt to pattern match on it, allowing
2908           you to do something like user_agent(Mozilla);
2909
2910       path_info()
2911           Returns additional path information from the script URL.  E.G.
2912           fetching /cgi-bin/your_script/additional/stuff will result in
2913           path_info() returning "/additional/stuff".
2914
2915           NOTE: The Microsoft Internet Information Server is broken with
2916           respect to additional path information.  If you use the Perl DLL
2917           library, the IIS server will attempt to execute the additional path
2918           information as a Perl script.  If you use the ordinary file
2919           associations mapping, the path information will be present in the
2920           environment, but incorrect.  The best thing to do is to avoid using
2921           additional path information in CGI scripts destined for use with
2922           IIS.
2923
2924       path_translated()
2925           As per path_info() but returns the additional path information
2926           translated into a physical path, e.g.
2927           "/usr/local/etc/httpd/htdocs/additional/stuff".
2928
2929           The Microsoft IIS is broken with respect to the translated path as
2930           well.
2931
2932       remote_host()
2933           Returns either the remote host name or IP address.  if the former
2934           is unavailable.
2935
2936       remote_addr()
2937           Returns the remote host IP address, or 127.0.0.1 if the address is
2938           unavailable.
2939
2940       script_name() Return the script name as a partial URL, for self-
2941       referring scripts.
2942       referer()
2943           Return the URL of the page the browser was viewing prior to
2944           fetching your script.  Not available for all browsers.
2945
2946       auth_type ()
2947           Return the authorization/verification method in use for this
2948           script, if any.
2949
2950       server_name ()
2951           Returns the name of the server, usually the machine's host name.
2952
2953       virtual_host ()
2954           When using virtual hosts, returns the name of the host that the
2955           browser attempted to contact
2956
2957       server_port ()
2958           Return the port that the server is listening on.
2959
2960       virtual_port ()
2961           Like server_port() except that it takes virtual hosts into account.
2962           Use this when running with virtual hosts.
2963
2964       server_software ()
2965           Returns the server software and version number.
2966
2967       remote_user ()
2968           Return the authorization/verification name used for user
2969           verification, if this script is protected.
2970
2971       user_name ()
2972           Attempt to obtain the remote user's name, using a variety of
2973           different techniques.  This only works with older browsers such as
2974           Mosaic.  Newer browsers do not report the user name for privacy
2975           reasons!
2976
2977       request_method()
2978           Returns the method used to access your script, usually one of
2979           'POST', 'GET' or 'HEAD'.
2980
2981       content_type()
2982           Returns the content_type of data submitted in a POST, generally
2983           multipart/form-data or application/x-www-form-urlencoded
2984
2985       http()
2986           Called with no arguments returns the list of HTTP environment
2987           variables, including such things as HTTP_USER_AGENT,
2988           HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
2989           like-named HTTP header fields in the request.  Called with the name
2990           of an HTTP header field, returns its value.  Capitalization and the
2991           use of hyphens versus underscores are not significant.
2992
2993           For example, all three of these examples are equivalent:
2994
2995              $requested_language = http('Accept-language');
2996              $requested_language = http('Accept_language');
2997              $requested_language = http('HTTP_ACCEPT_LANGUAGE');
2998
2999       https()
3000           The same as http(), but operates on the HTTPS environment variables
3001           present when the SSL protocol is in effect.  Can be used to
3002           determine whether SSL is turned on.
3003

USING NPH SCRIPTS

3005       NPH, or "no-parsed-header", scripts bypass the server completely by
3006       sending the complete HTTP header directly to the browser.  This has
3007       slight performance benefits, but is of most use for taking advantage of
3008       HTTP extensions that are not directly supported by your server, such as
3009       server push and PICS headers.
3010
3011       Servers use a variety of conventions for designating CGI scripts as
3012       NPH.  Many Unix servers look at the beginning of the script's name for
3013       the prefix "nph-".  The Macintosh WebSTAR server and Microsoft's
3014       Internet Information Server, in contrast, try to decide whether a
3015       program is an NPH script by examining the first line of script output.
3016
3017       CGI.pm supports NPH scripts with a special NPH mode.  When in this
3018       mode, CGI.pm will output the necessary extra header information when
3019       the header() and redirect() methods are called.
3020
3021       The Microsoft Internet Information Server requires NPH mode.  As of
3022       version 2.30, CGI.pm will automatically detect when the script is
3023       running under IIS and put itself into this mode.  You do not need to do
3024       this manually, although it won't hurt anything if you do.  However,
3025       note that if you have applied Service Pack 6, much of the functionality
3026       of NPH scripts, including the ability to redirect while setting a
3027       cookie, do not work at all on IIS without a special patch from
3028       Microsoft.  See
3029       http://web.archive.org/web/20010812012030/http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP
3030       Non-Parsed Headers Stripped From CGI Applications That Have nph- Prefix
3031       in Name.
3032
3033       In the use statement
3034           Simply add the "-nph" pragma to the list of symbols to be imported
3035           into your script:
3036
3037                 use CGI qw(:standard -nph)
3038
3039       By calling the nph() method:
3040           Call nph() with a non-zero parameter at any point after using
3041           CGI.pm in your program.
3042
3043                 CGI->nph(1)
3044
3045       By using -nph parameters
3046           in the header() and redirect()  statements:
3047
3048                 print header(-nph=>1);
3049

Server Push

3051       CGI.pm provides four simple functions for producing multipart documents
3052       of the type needed to implement server push.  These functions were
3053       graciously provided by Ed Jordan <ed@fidalgo.net>.  To import these
3054       into your namespace, you must import the ":push" set.  You are also
3055       advised to put the script into NPH mode and to set $| to 1 to avoid
3056       buffering problems.
3057
3058       Here is a simple script that demonstrates server push:
3059
3060         #!/usr/local/bin/perl
3061         use CGI qw/:push -nph/;
3062         $| = 1;
3063         print multipart_init(-boundary=>'----here we go!');
3064         for (0 .. 4) {
3065             print multipart_start(-type=>'text/plain'),
3066                   "The current time is ",scalar(localtime),"\n";
3067             if ($_ < 4) {
3068                     print multipart_end;
3069             } else {
3070                     print multipart_final;
3071             }
3072             sleep 1;
3073         }
3074
3075       This script initializes server push by calling multipart_init().  It
3076       then enters a loop in which it begins a new multipart section by
3077       calling multipart_start(), prints the current local time, and ends a
3078       multipart section with multipart_end().  It then sleeps a second, and
3079       begins again. On the final iteration, it ends the multipart section
3080       with multipart_final() rather than with multipart_end().
3081
3082       multipart_init()
3083             multipart_init(-boundary=>$boundary);
3084
3085           Initialize the multipart system.  The -boundary argument specifies
3086           what MIME boundary string to use to separate parts of the document.
3087           If not provided, CGI.pm chooses a reasonable boundary for you.
3088
3089       multipart_start()
3090             multipart_start(-type=>$type)
3091
3092           Start a new part of the multipart document using the specified MIME
3093           type.  If not specified, text/html is assumed.
3094
3095       multipart_end()
3096             multipart_end()
3097
3098           End a part.  You must remember to call multipart_end() once for
3099           each multipart_start(), except at the end of the last part of the
3100           multipart document when multipart_final() should be called instead
3101           of multipart_end().
3102
3103       multipart_final()
3104             multipart_final()
3105
3106           End all parts.  You should call multipart_final() rather than
3107           multipart_end() at the end of the last part of the multipart
3108           document.
3109
3110       Users interested in server push applications should also have a look at
3111       the CGI::Push module.
3112

Avoiding Denial of Service Attacks

3114       A potential problem with CGI.pm is that, by default, it attempts to
3115       process form POSTings no matter how large they are.  A wily hacker
3116       could attack your site by sending a CGI script a huge POST of many
3117       megabytes.  CGI.pm will attempt to read the entire POST into a
3118       variable, growing hugely in size until it runs out of memory.  While
3119       the script attempts to allocate the memory the system may slow down
3120       dramatically.  This is a form of denial of service attack.
3121
3122       Another possible attack is for the remote user to force CGI.pm to
3123       accept a huge file upload.  CGI.pm will accept the upload and store it
3124       in a temporary directory even if your script doesn't expect to receive
3125       an uploaded file.  CGI.pm will delete the file automatically when it
3126       terminates, but in the meantime the remote user may have filled up the
3127       server's disk space, causing problems for other programs.
3128
3129       The best way to avoid denial of service attacks is to limit the amount
3130       of memory, CPU time and disk space that CGI scripts can use.  Some Web
3131       servers come with built-in facilities to accomplish this. In other
3132       cases, you can use the shell limit or ulimit commands to put ceilings
3133       on CGI resource usage.
3134
3135       CGI.pm also has some simple built-in protections against denial of
3136       service attacks, but you must activate them before you can use them.
3137       These take the form of two global variables in the CGI name space:
3138
3139       $CGI::POST_MAX
3140           If set to a non-negative integer, this variable puts a ceiling on
3141           the size of POSTings, in bytes.  If CGI.pm detects a POST that is
3142           greater than the ceiling, it will immediately exit with an error
3143           message.  This value will affect both ordinary POSTs and multipart
3144           POSTs, meaning that it limits the maximum size of file uploads as
3145           well.  You should set this to a reasonably high value, such as 1
3146           megabyte.
3147
3148       $CGI::DISABLE_UPLOADS
3149           If set to a non-zero value, this will disable file uploads
3150           completely.  Other fill-out form values will work as usual.
3151
3152       You can use these variables in either of two ways.
3153
3154       1. On a script-by-script basis
3155           Set the variable at the top of the script, right after the "use"
3156           statement:
3157
3158               use CGI qw/:standard/;
3159               use CGI::Carp 'fatalsToBrowser';
3160               $CGI::POST_MAX=1024 * 100;  # max 100K posts
3161               $CGI::DISABLE_UPLOADS = 1;  # no uploads
3162
3163       2. Globally for all scripts
3164           Open up CGI.pm, find the definitions for $POST_MAX and
3165           $DISABLE_UPLOADS, and set them to the desired values.  You'll find
3166           them towards the top of the file in a subroutine named
3167           initialize_globals().
3168
3169       An attempt to send a POST larger than $POST_MAX bytes will cause
3170       param() to return an empty CGI parameter list.  You can test for this
3171       event by checking cgi_error(), either after you create the CGI object
3172       or, if you are using the function-oriented interface, call <param()>
3173       for the first time.  If the POST was intercepted, then cgi_error() will
3174       return the message "413 POST too large".
3175
3176       This error message is actually defined by the HTTP protocol, and is
3177       designed to be returned to the browser as the CGI script's status
3178        code.  For example:
3179
3180          $uploaded_file = param('upload');
3181          if (!$uploaded_file && cgi_error()) {
3182             print header(-status=>cgi_error());
3183             exit 0;
3184          }
3185
3186       However it isn't clear that any browser currently knows what to do with
3187       this status code.  It might be better just to create an HTML page that
3188       warns the user of the problem.
3189

COMPATIBILITY WITH CGI-LIB.PL

3191       To make it easier to port existing programs that use cgi-lib.pl the
3192       compatibility routine "ReadParse" is provided.  Porting is simple:
3193
3194       OLD VERSION
3195
3196           require "cgi-lib.pl";
3197           &ReadParse;
3198           print "The value of the antique is $in{antique}.\n";
3199
3200       NEW VERSION
3201
3202           use CGI;
3203           CGI::ReadParse();
3204           print "The value of the antique is $in{antique}.\n";
3205
3206       CGI.pm's ReadParse() routine creates a tied variable named %in, which
3207       can be accessed to obtain the query variables.  Like ReadParse, you can
3208       also provide your own variable.  Infrequently used features of
3209       ReadParse, such as the creation of @in and $in variables, are not
3210       supported.
3211
3212       Once you use ReadParse, you can retrieve the query object itself this
3213       way:
3214
3215           $q = $in{CGI};
3216           print $q->textfield(-name=>'wow',
3217                   -value=>'does this really work?');
3218
3219       This allows you to start using the more interesting features of CGI.pm
3220       without rewriting your old scripts from scratch.
3221
3222       An even simpler way to mix cgi-lib calls with CGI.pm calls is to import
3223       both the ":cgi-lib" and ":standard" method:
3224
3225        use CGI qw(:cgi-lib :standard);
3226        &ReadParse;
3227        print "The price of your purchase is $in{price}.\n";
3228        print textfield(-name=>'price', -default=>'$1.99');
3229
3230   Cgi-lib functions that are available in CGI.pm
3231       In compatability mode, the following cgi-lib.pl functions are available
3232       for your use:
3233
3234        ReadParse()
3235        PrintHeader()
3236        HtmlTop()
3237        HtmlBot()
3238        SplitParam()
3239        MethGet()
3240        MethPost()
3241
3242   Cgi-lib functions that are not available in CGI.pm
3243         * Extended form of ReadParse()
3244           The extended form of ReadParse() that provides for file upload
3245           spooling, is not available.
3246
3247         * MyBaseURL()
3248           This function is not available.  Use CGI.pm's url() method instead.
3249
3250         * MyFullURL()
3251           This function is not available.  Use CGI.pm's self_url() method
3252           instead.
3253
3254         * CgiError(), CgiDie()
3255           These functions are not supported.  Look at CGI::Carp for the way I
3256           prefer to handle error messages.
3257
3258         * PrintVariables()
3259           This function is not available.  To achieve the same effect,
3260              just print out the CGI object:
3261
3262              use CGI qw(:standard);
3263              $q = CGI->new;
3264              print h1("The Variables Are"),$q;
3265
3266         * PrintEnv()
3267           This function is not available. You'll have to roll your own if you really need it.
3268

AUTHOR INFORMATION

3270       The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein.  It
3271       is distributed under GPL and the Artistic License 2.0.
3272
3273       Address bug reports and comments to: lstein@cshl.org.  When sending bug
3274       reports, please provide the version of CGI.pm, the version of Perl, the
3275       name and version of your Web server, and the name and version of the
3276       operating system you are using.  If the problem is even remotely
3277       browser dependent, please provide information about the affected
3278       browsers as well.
3279

CREDITS

3281       Thanks very much to:
3282
3283       Matt Heffron (heffron@falstaff.css.beckman.com)
3284       James Taylor (james.taylor@srs.gov)
3285       Scott Anguish <sanguish@digifix.com>
3286       Mike Jewell (mlj3u@virginia.edu)
3287       Timothy Shimmin (tes@kbs.citri.edu.au)
3288       Joergen Haegg (jh@axis.se)
3289       Laurent Delfosse (delfosse@delfosse.com)
3290       Richard Resnick (applepi1@aol.com)
3291       Craig Bishop (csb@barwonwater.vic.gov.au)
3292       Tony Curtis (tc@vcpc.univie.ac.at)
3293       Tim Bunce (Tim.Bunce@ig.co.uk)
3294       Tom Christiansen (tchrist@convex.com)
3295       Andreas Koenig (k@franz.ww.TU-Berlin.DE)
3296       Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
3297       Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
3298       Stephen Dahmen (joyfire@inxpress.net)
3299       Ed Jordan (ed@fidalgo.net)
3300       David Alan Pisoni (david@cnation.com)
3301       Doug MacEachern (dougm@opengroup.org)
3302       Robin Houston (robin@oneworld.org)
3303       ...and many many more...
3304           for suggestions and bug fixes.
3305

A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT

3307               #!/usr/local/bin/perl
3308
3309               use CGI ':standard';
3310
3311               print header;
3312               print start_html("Example CGI.pm Form");
3313               print "<h1> Example CGI.pm Form</h1>\n";
3314               print_prompt();
3315               do_work();
3316               print_tail();
3317               print end_html;
3318
3319               sub print_prompt {
3320                  print start_form;
3321                  print "<em>What's your name?</em><br>";
3322                  print textfield('name');
3323                  print checkbox('Not my real name');
3324
3325                  print "<p><em>Where can you find English Sparrows?</em><br>";
3326                  print checkbox_group(
3327                                        -name=>'Sparrow locations',
3328                                        -values=>[England,France,Spain,Asia,Hoboken],
3329                                        -linebreak=>'yes',
3330                                        -defaults=>[England,Asia]);
3331
3332                  print "<p><em>How far can they fly?</em><br>",
3333                       radio_group(
3334                               -name=>'how far',
3335                               -values=>['10 ft','1 mile','10 miles','real far'],
3336                               -default=>'1 mile');
3337
3338                  print "<p><em>What's your favorite color?</em>  ";
3339                  print popup_menu(-name=>'Color',
3340                                           -values=>['black','brown','red','yellow'],
3341                                           -default=>'red');
3342
3343                  print hidden('Reference','Monty Python and the Holy Grail');
3344
3345                  print "<p><em>What have you got there?</em><br>";
3346                  print scrolling_list(
3347                                -name=>'possessions',
3348                                -values=>['A Coconut','A Grail','An Icon',
3349                                          'A Sword','A Ticket'],
3350                                -size=>5,
3351                                -multiple=>'true');
3352
3353                  print "<p><em>Any parting comments?</em><br>";
3354                  print textarea(-name=>'Comments',
3355                                         -rows=>10,
3356                                         -columns=>50);
3357
3358                  print "<p>",reset;
3359                  print submit('Action','Shout');
3360                  print submit('Action','Scream');
3361                  print end_form;
3362                  print "<hr>\n";
3363               }
3364
3365               sub do_work {
3366
3367                  print "<h2>Here are the current settings in this form</h2>";
3368
3369                  for my $key (param) {
3370                     print "<strong>$key</strong> -> ";
3371                     my @values = param($key);
3372                     print join(", ",@values),"<br>\n";
3373                 }
3374               }
3375
3376               sub print_tail {
3377                  print <<END;
3378               <hr>
3379               <address>Lincoln D. Stein</address><br>
3380               <a href="/">Home Page</a>
3381               END
3382               }
3383

BUGS

3385       Please report them.
3386

SEE ALSO

3388       CGI::Carp - provides a Carp implementation tailored to the CGI
3389       environment.
3390
3391       CGI::Fast - supports running CGI applications under FastCGI
3392
3393       CGI::Pretty - pretty prints HTML generated by CGI.pm (with a
3394       performance penalty)
3395
3396
3397
3398perl v5.10.1                      2017-03-22                          CGI(3pm)
Impressum