1CGI(3) User Contributed Perl Documentation CGI(3)
2
3
4
6 CGI - Handle Common Gateway Interface requests and responses
7
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
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 POST, GET and DELETE methods) and store
197 it 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
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. Note that
848 RFC 2616 expects the human-readable phase to be there as well as the
849 numeric status code.
850
851 The last example shows the named argument style for passing arguments
852 to the CGI methods using named parameters. Recognized parameters are
853 -type, -status, -expires, and -cookie. Any other named parameters will
854 be stripped of their initial hyphens and turned into header fields,
855 allowing you to specify any HTTP header you desire. Internal
856 underscores will be turned into hyphens:
857
858 print header(-Content_length=>3002);
859
860 Most browsers will not cache the output from CGI scripts. Every time
861 the browser reloads the page, the script is invoked anew. You can
862 change this behavior with the -expires parameter. When you specify an
863 absolute or relative expiration interval with this parameter, some
864 browsers and proxy servers will cache the script's output until the
865 indicated expiration date. The following forms are all valid for the
866 -expires field:
867
868 +30s 30 seconds from now
869 +10m ten minutes from now
870 +1h one hour from now
871 -1d yesterday (i.e. "ASAP!")
872 now immediately
873 +3M in three months
874 +10y in ten years time
875 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
876
877 The -cookie parameter generates a header that tells the browser to
878 provide a "magic cookie" during all subsequent transactions with your
879 script. Some cookies have a special format that includes interesting
880 attributes such as expiration time. Use the cookie() method to create
881 and retrieve session cookies.
882
883 The -nph parameter, if set to a true value, will issue the correct
884 headers to work with a NPH (no-parse-header) script. This is important
885 to use with certain servers that expect all their scripts to be NPH.
886
887 The -charset parameter can be used to control the character set sent to
888 the browser. If not provided, defaults to ISO-8859-1. As a side
889 effect, this sets the charset() method as well.
890
891 The -attachment parameter can be used to turn the page into an
892 attachment. Instead of displaying the page, some browsers will prompt
893 the user to save it to disk. The value of the argument is the
894 suggested name for the saved file. In order for this to work, you may
895 have to set the -type to "application/octet-stream".
896
897 The -p3p parameter will add a P3P tag to the outgoing header. The
898 parameter can be an arrayref or a space-delimited string of P3P tags.
899 For example:
900
901 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
902 print header(-p3p=>'CAO DSP LAW CURa');
903
904 In either case, the outgoing header will be formatted as:
905
906 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
907
908 CGI.pm will accept valid multi-line headers when each line is separated
909 with a CRLF value ("\r\n" on most platforms) followed by at least one
910 space. For example:
911
912 print header( -ingredients => "ham\r\n\seggs\r\n\sbacon" );
913
914 Invalid multi-line header input will trigger in an exception. When
915 multi-line headers are received, CGI.pm will always output them back as
916 a single line, according to the folding rules of RFC 2616: the newlines
917 will be removed, while the white space remains.
918
919 GENERATING A REDIRECTION HEADER
920 print $q->redirect('http://somewhere.else/in/movie/land');
921
922 Sometimes you don't want to produce a document yourself, but simply
923 redirect the browser elsewhere, perhaps choosing a URL based on the
924 time of day or the identity of the user.
925
926 The redirect() method redirects the browser to a different URL. If you
927 use redirection like this, you should not print out a header as well.
928
929 You should always use full URLs (including the http: or ftp: part) in
930 redirection requests. Relative URLs will not work correctly.
931
932 You can also use named arguments:
933
934 print $q->redirect(
935 -uri=>'http://somewhere.else/in/movie/land',
936 -nph=>1,
937 -status=>'301 Moved Permanently');
938
939 All names arguments recognized by header() are also recognized by
940 redirect(). However, most HTTP headers, including those generated by
941 -cookie and -target, are ignored by the browser.
942
943 The -nph parameter, if set to a true value, will issue the correct
944 headers to work with a NPH (no-parse-header) script. This is important
945 to use with certain servers, such as Microsoft IIS, which expect all
946 their scripts to be NPH.
947
948 The -status parameter will set the status of the redirect. HTTP
949 defines three different possible redirection status codes:
950
951 301 Moved Permanently
952 302 Found
953 303 See Other
954
955 The default if not specified is 302, which means "moved temporarily."
956 You may change the status to another status code if you wish. Be
957 advised that changing the status to anything other than 301, 302 or 303
958 will probably break redirection.
959
960 Note that the human-readable phrase is also expected to be present to
961 conform with RFC 2616, section 6.1.
962
963 CREATING THE HTML DOCUMENT HEADER
964 print start_html(-title=>'Secrets of the Pyramids',
965 -author=>'fred@capricorn.org',
966 -base=>'true',
967 -target=>'_blank',
968 -meta=>{'keywords'=>'pharaoh secret mummy',
969 'copyright'=>'copyright 1996 King Tut'},
970 -style=>{'src'=>'/styles/style1.css'},
971 -BGCOLOR=>'blue');
972
973 The start_html() routine creates the top of the page, along with a lot
974 of optional information that controls the page's appearance and
975 behavior.
976
977 This method returns a canned HTML header and the opening <body> tag.
978 All parameters are optional. In the named parameter form, recognized
979 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
980 (see below for the explanation). Any additional parameters you
981 provide, such as the unofficial BGCOLOR attribute, are added to the
982 <body> tag. Additional parameters must be proceeded by a hyphen.
983
984 The argument -xbase allows you to provide an HREF for the <base> tag
985 different from the current location, as in
986
987 -xbase=>"http://home.mcom.com/"
988
989 All relative links will be interpreted relative to this tag.
990
991 The argument -target allows you to provide a default target frame for
992 all the links and fill-out forms on the page. This is a non-standard
993 HTTP feature which only works with some browsers!
994
995 -target=>"answer_window"
996
997 All relative links will be interpreted relative to this tag. You add
998 arbitrary meta information to the header with the -meta argument. This
999 argument expects a reference to a hash containing name/value pairs of
1000 meta information. These will be turned into a series of header <meta>
1001 tags that look something like this:
1002
1003 <meta name="keywords" content="pharaoh secret mummy">
1004 <meta name="description" content="copyright 1996 King Tut">
1005
1006 To create an HTTP-EQUIV type of <meta> tag, use -head, described below.
1007
1008 The -style argument is used to incorporate cascading stylesheets into
1009 your code. See the section on CASCADING STYLESHEETS for more
1010 information.
1011
1012 The -lang argument is used to incorporate a language attribute into the
1013 <html> tag. For example:
1014
1015 print $q->start_html(-lang=>'fr-CA');
1016
1017 The default if not specified is "en-US" for US English, unless the -dtd
1018 parameter specifies an HTML 2.0 or 3.2 DTD, in which case the lang
1019 attribute is left off. You can force the lang attribute to left off in
1020 other cases by passing an empty string (-lang=>'').
1021
1022 The -encoding argument can be used to specify the character set for
1023 XHTML. It defaults to iso-8859-1 if not specified.
1024
1025 The -dtd argument can be used to specify a public DTD identifier
1026 string. For example:
1027
1028 -dtd => '-//W3C//DTD HTML 4.01 Transitional//EN')
1029
1030 Alternatively, it can take public and system DTD identifiers as an
1031 array:
1032
1033 dtd => [ '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd' ]
1034
1035 For the public DTD identifier to be considered, it must be valid.
1036 Otherwise it will be replaced by the default DTD. If the public DTD
1037 contains 'XHTML', CGI.pm will emit XML.
1038
1039 The -declare_xml argument, when used in conjunction with XHTML, will
1040 put a <?xml> declaration at the top of the HTML header. The sole
1041 purpose of this declaration is to declare the character set encoding.
1042 In the absence of -declare_xml, the output HTML will contain a <meta>
1043 tag that specifies the encoding, allowing the HTML to pass most
1044 validators. The default for -declare_xml is false.
1045
1046 You can place other arbitrary HTML elements to the <head> section with
1047 the -head tag. For example, to place a <link> element in the head
1048 section, use this:
1049
1050 print start_html(-head=>Link({-rel=>'shortcut icon',
1051 -href=>'favicon.ico'}));
1052
1053 To incorporate multiple HTML elements into the <head> section, just
1054 pass an array reference:
1055
1056 print start_html(-head=>[
1057 Link({-rel=>'next',
1058 -href=>'http://www.capricorn.com/s2.html'}),
1059 Link({-rel=>'previous',
1060 -href=>'http://www.capricorn.com/s1.html'})
1061 ]
1062 );
1063
1064 And here's how to create an HTTP-EQUIV <meta> tag:
1065
1066 print start_html(-head=>meta({-http_equiv => 'Content-Type',
1067 -content => 'text/html'}))
1068
1069 JAVASCRIPTING: The -script, -noScript, -onLoad, -onMouseOver,
1070 -onMouseOut and -onUnload parameters are used to add JavaScript calls
1071 to your pages. -script should point to a block of text containing
1072 JavaScript function definitions. This block will be placed within a
1073 <script> block inside the HTML (not HTTP) header. The block is placed
1074 in the header in order to give your page a fighting chance of having
1075 all its JavaScript functions in place even if the user presses the stop
1076 button before the page has loaded completely. CGI.pm attempts to
1077 format the script in such a way that JavaScript-naive browsers will not
1078 choke on the code: unfortunately there are some browsers, such as
1079 Chimera for Unix, that get confused by it nevertheless.
1080
1081 The -onLoad and -onUnload parameters point to fragments of JavaScript
1082 code to execute when the page is respectively opened and closed by the
1083 browser. Usually these parameters are calls to functions defined in
1084 the -script field:
1085
1086 $query = CGI->new;
1087 print header;
1088 $JSCRIPT=<<END;
1089 // Ask a silly question
1090 function riddle_me_this() {
1091 var r = prompt("What walks on four legs in the morning, " +
1092 "two legs in the afternoon, " +
1093 "and three legs in the evening?");
1094 response(r);
1095 }
1096 // Get a silly answer
1097 function response(answer) {
1098 if (answer == "man")
1099 alert("Right you are!");
1100 else
1101 alert("Wrong! Guess again.");
1102 }
1103 END
1104 print start_html(-title=>'The Riddle of the Sphinx',
1105 -script=>$JSCRIPT);
1106
1107 Use the -noScript parameter to pass some HTML text that will be
1108 displayed on browsers that do not have JavaScript (or browsers where
1109 JavaScript is turned off).
1110
1111 The <script> tag, has several attributes including "type", "charset"
1112 and "src". "src" allows you to keep JavaScript code in an external
1113 file. To use these attributes pass a HASH reference in the -script
1114 parameter containing one or more of -type, -src, or -code:
1115
1116 print $q->start_html(-title=>'The Riddle of the Sphinx',
1117 -script=>{-type=>'JAVASCRIPT',
1118 -src=>'/javascript/sphinx.js'}
1119 );
1120
1121 print $q->(-title=>'The Riddle of the Sphinx',
1122 -script=>{-type=>'PERLSCRIPT',
1123 -code=>'print "hello world!\n;"'}
1124 );
1125
1126 A final feature allows you to incorporate multiple <script> sections
1127 into the header. Just pass the list of script sections as an array
1128 reference. this allows you to specify different source files for
1129 different dialects of JavaScript. Example:
1130
1131 print $q->start_html(-title=>'The Riddle of the Sphinx',
1132 -script=>[
1133 { -type => 'text/javascript',
1134 -src => '/javascript/utilities10.js'
1135 },
1136 { -type => 'text/javascript',
1137 -src => '/javascript/utilities11.js'
1138 },
1139 { -type => 'text/jscript',
1140 -src => '/javascript/utilities12.js'
1141 },
1142 { -type => 'text/ecmascript',
1143 -src => '/javascript/utilities219.js'
1144 }
1145 ]
1146 );
1147
1148 The option "-language" is a synonym for -type, and is supported for
1149 backwards compatibility.
1150
1151 The old-style positional parameters are as follows:
1152
1153 Parameters:
1154 1. The title
1155
1156 2. The author's e-mail address (will create a <link rev="MADE"> tag if
1157 present
1158
1159 3. A 'true' flag if you want to include a <base> tag in the header.
1160 This helps resolve relative addresses to absolute ones when the
1161 document is moved, but makes the document hierarchy non-portable.
1162 Use with care!
1163
1164 4, 5, 6...
1165 Any other parameters you want to include in the <body> tag. This
1166 is a good place to put HTML extensions, such as colors and
1167 wallpaper patterns.
1168
1169 ENDING THE HTML DOCUMENT:
1170 print $q->end_html;
1171
1172 This ends an HTML document by printing the </body></html> tags.
1173
1174 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
1175 $myself = $q->self_url;
1176 print q(<a href="$myself">I'm talking to myself.</a>);
1177
1178 self_url() will return a URL, that, when selected, will reinvoke this
1179 script with all its state information intact. This is most useful when
1180 you want to jump around within the document using internal anchors but
1181 you don't want to disrupt the current contents of the form(s).
1182 Something like this will do the trick.
1183
1184 $myself = $q->self_url;
1185 print "<a href=\"$myself#table1\">See table 1</a>";
1186 print "<a href=\"$myself#table2\">See table 2</a>";
1187 print "<a href=\"$myself#yourself\">See for yourself</a>";
1188
1189 If you want more control over what's returned, using the url() method
1190 instead.
1191
1192 You can also retrieve the unprocessed query string with query_string():
1193
1194 $the_string = $q->query_string();
1195
1196 The behavior of calling query_string is currently undefined when the
1197 HTTP method is something other than GET.
1198
1199 OBTAINING THE SCRIPT'S URL
1200 $full_url = url();
1201 $full_url = url(-full=>1); #alternative syntax
1202 $relative_url = url(-relative=>1);
1203 $absolute_url = url(-absolute=>1);
1204 $url_with_path = url(-path_info=>1);
1205 $url_with_path_and_query = url(-path_info=>1,-query=>1);
1206 $netloc = url(-base => 1);
1207
1208 url() returns the script's URL in a variety of formats. Called without
1209 any arguments, it returns the full form of the URL, including host name
1210 and port number
1211
1212 http://your.host.com/path/to/script.cgi
1213
1214 You can modify this format with the following named arguments:
1215
1216 -absolute
1217 If true, produce an absolute URL, e.g.
1218
1219 /path/to/script.cgi
1220
1221 -relative
1222 Produce a relative URL. This is useful if you want to reinvoke
1223 your script with different parameters. For example:
1224
1225 script.cgi
1226
1227 -full
1228 Produce the full URL, exactly as if called without any arguments.
1229 This overrides the -relative and -absolute arguments.
1230
1231 -path (-path_info)
1232 Append the additional path information to the URL. This can be
1233 combined with -full, -absolute or -relative. -path_info is
1234 provided as a synonym.
1235
1236 -query (-query_string)
1237 Append the query string to the URL. This can be combined with
1238 -full, -absolute or -relative. -query_string is provided as a
1239 synonym.
1240
1241 -base
1242 Generate just the protocol and net location, as in
1243 http://www.foo.com:8000
1244
1245 -rewrite
1246 If Apache's mod_rewrite is turned on, then the script name and path
1247 info probably won't match the request that the user sent. Set
1248 -rewrite=>1 (default) to return URLs that match what the user sent
1249 (the original request URI). Set -rewrite=>0 to return URLs that
1250 match the URL after mod_rewrite's rules have run.
1251
1252 MIXING POST AND URL PARAMETERS
1253 $color = url_param('color');
1254
1255 It is possible for a script to receive CGI parameters in the URL as
1256 well as in the fill-out form by creating a form that POSTs to a URL
1257 containing a query string (a "?" mark followed by arguments). The
1258 param() method will always return the contents of the POSTed fill-out
1259 form, ignoring the URL's query string. To retrieve URL parameters,
1260 call the url_param() method. Use it in the same way as param(). The
1261 main difference is that it allows you to read the parameters, but not
1262 set them.
1263
1264 Under no circumstances will the contents of the URL query string
1265 interfere with similarly-named CGI parameters in POSTed forms. If you
1266 try to mix a URL query string with a form submitted with the GET
1267 method, the results will not be what you expect.
1268
1270 CGI.pm defines general HTML shortcut methods for many HTML tags. HTML
1271 shortcuts are named after a single HTML element and return a fragment
1272 of HTML text. Example:
1273
1274 print $q->blockquote(
1275 "Many years ago on the island of",
1276 $q->a({href=>"http://crete.org/"},"Crete"),
1277 "there lived a Minotaur named",
1278 $q->strong("Fred."),
1279 ),
1280 $q->hr;
1281
1282 This results in the following HTML code (extra newlines have been added
1283 for readability):
1284
1285 <blockquote>
1286 Many years ago on the island of
1287 <a href="http://crete.org/">Crete</a> there lived
1288 a minotaur named <strong>Fred.</strong>
1289 </blockquote>
1290 <hr>
1291
1292 If you find the syntax for calling the HTML shortcuts awkward, you can
1293 import them into your namespace and dispense with the object syntax
1294 completely (see the next section for more details):
1295
1296 use CGI ':standard';
1297 print blockquote(
1298 "Many years ago on the island of",
1299 a({href=>"http://crete.org/"},"Crete"),
1300 "there lived a minotaur named",
1301 strong("Fred."),
1302 ),
1303 hr;
1304
1305 PROVIDING ARGUMENTS TO HTML SHORTCUTS
1306 The HTML methods will accept zero, one or multiple arguments. If you
1307 provide no arguments, you get a single tag:
1308
1309 print hr; # <hr>
1310
1311 If you provide one or more string arguments, they are concatenated
1312 together with spaces and placed between opening and closing tags:
1313
1314 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
1315
1316 If the first argument is a hash reference, then the keys and values of
1317 the hash become the HTML tag's attributes:
1318
1319 print a({-href=>'fred.html',-target=>'_new'},
1320 "Open a new frame");
1321
1322 <a href="fred.html",target="_new">Open a new frame</a>
1323
1324 You may dispense with the dashes in front of the attribute names if you
1325 prefer:
1326
1327 print img {src=>'fred.gif',align=>'LEFT'};
1328
1329 <img align="LEFT" src="fred.gif">
1330
1331 Sometimes an HTML tag attribute has no argument. For example, ordered
1332 lists can be marked as COMPACT. The syntax for this is an argument
1333 that that points to an undef string:
1334
1335 print ol({compact=>undef},li('one'),li('two'),li('three'));
1336
1337 Prior to CGI.pm version 2.41, providing an empty ('') string as an
1338 attribute argument was the same as providing undef. However, this has
1339 changed in order to accommodate those who want to create tags of the
1340 form <img alt="">. The difference is shown in these two pieces of
1341 code:
1342
1343 CODE RESULT
1344 img({alt=>undef}) <img alt>
1345 img({alt=>''}) <img alt="">
1346
1347 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
1348 One of the cool features of the HTML shortcuts is that they are
1349 distributive. If you give them an argument consisting of a reference
1350 to a list, the tag will be distributed across each element of the list.
1351 For example, here's one way to make an ordered list:
1352
1353 print ul(
1354 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
1355 );
1356
1357 This example will result in HTML output that looks like this:
1358
1359 <ul>
1360 <li type="disc">Sneezy</li>
1361 <li type="disc">Doc</li>
1362 <li type="disc">Sleepy</li>
1363 <li type="disc">Happy</li>
1364 </ul>
1365
1366 This is extremely useful for creating tables. For example:
1367
1368 print table({-border=>undef},
1369 caption('When Should You Eat Your Vegetables?'),
1370 Tr({-align=>'CENTER',-valign=>'TOP'},
1371 [
1372 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
1373 td(['Tomatoes' , 'no', 'yes', 'yes']),
1374 td(['Broccoli' , 'no', 'no', 'yes']),
1375 td(['Onions' , 'yes','yes', 'yes'])
1376 ]
1377 )
1378 );
1379
1380 HTML SHORTCUTS AND LIST INTERPOLATION
1381 Consider this bit of code:
1382
1383 print blockquote(em('Hi'),'mom!'));
1384
1385 It will ordinarily return the string that you probably expect, namely:
1386
1387 <blockquote><em>Hi</em> mom!</blockquote>
1388
1389 Note the space between the element "Hi" and the element "mom!". CGI.pm
1390 puts the extra space there using array interpolation, which is
1391 controlled by the magic $" variable. Sometimes this extra space is not
1392 what you want, for example, when you are trying to align a series of
1393 images. In this case, you can simply change the value of $" to an
1394 empty string.
1395
1396 {
1397 local($") = '';
1398 print blockquote(em('Hi'),'mom!'));
1399 }
1400
1401 I suggest you put the code in a block as shown here. Otherwise the
1402 change to $" will affect all subsequent code until you explicitly reset
1403 it.
1404
1405 NON-STANDARD HTML SHORTCUTS
1406 A few HTML tags don't follow the standard pattern for various reasons.
1407
1408 comment() generates an HTML comment (<!-- comment -->). Call it like
1409
1410 print comment('here is my comment');
1411
1412 Because of conflicts with built-in Perl functions, the following
1413 functions begin with initial caps:
1414
1415 Select
1416 Tr
1417 Link
1418 Delete
1419 Accept
1420 Sub
1421
1422 In addition, start_html(), end_html(), start_form(), end_form(),
1423 start_multipart_form() and all the fill-out form tags are special. See
1424 their respective sections.
1425
1426 AUTOESCAPING HTML
1427 By default, all HTML that is emitted by the form-generating functions
1428 is passed through a function called escapeHTML():
1429
1430 $escaped_string = escapeHTML("unescaped string");
1431 Escape HTML formatting characters in a string.
1432
1433 Provided that you have specified a character set of ISO-8859-1 (the
1434 default), the standard HTML escaping rules will be used. The "<"
1435 character becomes "<", ">" becomes ">", "&" becomes "&", and
1436 the quote character becomes """. In addition, the hexadecimal
1437 0x8b and 0x9b characters, which some browsers incorrectly interpret as
1438 the left and right angle-bracket characters, are replaced by their
1439 numeric character entities ("‹" and "›"). If you manually
1440 change the charset, either by calling the charset() method explicitly
1441 or by passing a -charset argument to header(), then all characters will
1442 be replaced by their numeric entities, since CGI.pm has no lookup table
1443 for all the possible encodings.
1444
1445 "escapeHTML()" expects the supplied string to be a character string.
1446 This means you should Encode::decode data received from "outside" and
1447 Encode::encode your strings before sending them back outside. If your
1448 source code UTF-8 encoded and you want to upgrade string literals in
1449 your source to character strings, you can use "use utf8". See
1450 perlunitut, perlunifaq and perlunicode for more information on how Perl
1451 handles the difference between bytes and characters.
1452
1453 The automatic escaping does not apply to other shortcuts, such as h1().
1454 You should call escapeHTML() yourself on untrusted data in order to
1455 protect your pages against nasty tricks that people may enter into
1456 guestbooks, etc.. To change the character set, use charset(). To turn
1457 autoescaping off completely, use autoEscape(0):
1458
1459 $charset = charset([$charset]);
1460 Get or set the current character set.
1461
1462 $flag = autoEscape([$flag]);
1463 Get or set the value of the autoescape flag.
1464
1465 PRETTY-PRINTING HTML
1466 By default, all the HTML produced by these functions comes out as one
1467 long line without carriage returns or indentation. This is yuck, but it
1468 does reduce the size of the documents by 10-20%. To get pretty-printed
1469 output, please use CGI::Pretty, a subclass contributed by Brian
1470 Paulsen.
1471
1473 General note The various form-creating methods all return strings to
1474 the caller, containing the tag or tags that will create the requested
1475 form element. You are responsible for actually printing out these
1476 strings. It's set up this way so that you can place formatting tags
1477 around the form elements.
1478
1479 Another note The default values that you specify for the forms are only
1480 used the first time the script is invoked (when there is no query
1481 string). On subsequent invocations of the script (when there is a
1482 query string), the former values are used even if they are blank.
1483
1484 If you want to change the value of a field from its previous value, you
1485 have two choices:
1486
1487 (1) call the param() method to set it.
1488
1489 (2) use the -override (alias -force) parameter (a new feature in
1490 version 2.15). This forces the default value to be used, regardless of
1491 the previous value:
1492
1493 print textfield(-name=>'field_name',
1494 -default=>'starting value',
1495 -override=>1,
1496 -size=>50,
1497 -maxlength=>80);
1498
1499 Yet another note By default, the text and labels of form elements are
1500 escaped according to HTML rules. This means that you can safely use
1501 "<CLICK ME>" as the label for a button. However, it also interferes
1502 with your ability to incorporate special HTML character sequences, such
1503 as Á, into your fields. If you wish to turn off automatic
1504 escaping, call the autoEscape() method with a false value immediately
1505 after creating the CGI object:
1506
1507 $query = CGI->new;
1508 $query->autoEscape(0);
1509
1510 Note that autoEscape() is exclusively used to effect the behavior of
1511 how some CGI.pm HTML generation functions handle escaping. Calling
1512 escapeHTML() explicitly will always escape the HTML.
1513
1514 A Lurking Trap! Some of the form-element generating methods return
1515 multiple tags. In a scalar context, the tags will be concatenated
1516 together with spaces, or whatever is the current value of the $"
1517 global. In a list context, the methods will return a list of elements,
1518 allowing you to modify them if you wish. Usually you will not notice
1519 this behavior, but beware of this:
1520
1521 printf("%s\n",end_form())
1522
1523 end_form() produces several tags, and only the first of them will be
1524 printed because the format only expects one value.
1525
1526 <p>
1527
1528 CREATING AN ISINDEX TAG
1529 print isindex(-action=>$action);
1530
1531 -or-
1532
1533 print isindex($action);
1534
1535 Prints out an <isindex> tag. Not very exciting. The parameter -action
1536 specifies the URL of the script to process the query. The default is
1537 to process the query with the current script.
1538
1539 STARTING AND ENDING A FORM
1540 print start_form(-method=>$method,
1541 -action=>$action,
1542 -enctype=>$encoding);
1543 <... various form stuff ...>
1544 print end_form;
1545
1546 -or-
1547
1548 print start_form($method,$action,$encoding);
1549 <... various form stuff ...>
1550 print end_form;
1551
1552 start_form() will return a <form> tag with the optional method, action
1553 and form encoding that you specify. The defaults are:
1554
1555 method: POST
1556 action: this script
1557 enctype: application/x-www-form-urlencoded for non-XHTML
1558 multipart/form-data for XHTML, see multipart/form-data below.
1559
1560 end_form() returns the closing </form> tag.
1561
1562 Start_form()'s enctype argument tells the browser how to package the
1563 various fields of the form before sending the form to the server. Two
1564 values are possible:
1565
1566 Note: These methods were previously named startform() and endform().
1567 These methods are now DEPRECATED. Please use start_form() and
1568 end_form() instead.
1569
1570 application/x-www-form-urlencoded
1571 This is the older type of encoding. It is compatible with many CGI
1572 scripts and is suitable for short fields containing text data. For
1573 your convenience, CGI.pm stores the name of this encoding type in
1574 &CGI::URL_ENCODED.
1575
1576 multipart/form-data
1577 This is the newer type of encoding. It is suitable for forms that
1578 contain very large fields or that are intended for transferring
1579 binary data. Most importantly, it enables the "file upload"
1580 feature. For your convenience, CGI.pm stores the name of this
1581 encoding type in &CGI::MULTIPART
1582
1583 Forms that use this type of encoding are not easily interpreted by
1584 CGI scripts unless they use CGI.pm or another library designed to
1585 handle them.
1586
1587 If XHTML is activated (the default), then forms will be
1588 automatically created using this type of encoding.
1589
1590 The start_form() method uses the older form of encoding by default
1591 unless XHTML is requested. If you want to use the newer form of
1592 encoding by default, you can call start_multipart_form() instead of
1593 start_form(). The method end_multipart_form() is an alias to
1594 end_form().
1595
1596 JAVASCRIPTING: The -name and -onSubmit parameters are provided for use
1597 with JavaScript. The -name parameter gives the form a name so that it
1598 can be identified and manipulated by JavaScript functions. -onSubmit
1599 should point to a JavaScript function that will be executed just before
1600 the form is submitted to your server. You can use this opportunity to
1601 check the contents of the form for consistency and completeness. If
1602 you find something wrong, you can put up an alert box or maybe fix
1603 things up yourself. You can abort the submission by returning false
1604 from this function.
1605
1606 Usually the bulk of JavaScript functions are defined in a <script>
1607 block in the HTML header and -onSubmit points to one of these function
1608 call. See start_html() for details.
1609
1610 FORM ELEMENTS
1611 After starting a form, you will typically create one or more
1612 textfields, popup menus, radio groups and other form elements. Each of
1613 these elements takes a standard set of named arguments. Some elements
1614 also have optional arguments. The standard arguments are as follows:
1615
1616 -name
1617 The name of the field. After submission this name can be used to
1618 retrieve the field's value using the param() method.
1619
1620 -value, -values
1621 The initial value of the field which will be returned to the script
1622 after form submission. Some form elements, such as text fields,
1623 take a single scalar -value argument. Others, such as popup menus,
1624 take a reference to an array of values. The two arguments are
1625 synonyms.
1626
1627 -tabindex
1628 A numeric value that sets the order in which the form element
1629 receives focus when the user presses the tab key. Elements with
1630 lower values receive focus first.
1631
1632 -id A string identifier that can be used to identify this element to
1633 JavaScript and DHTML.
1634
1635 -override
1636 A boolean, which, if true, forces the element to take on the value
1637 specified by -value, overriding the sticky behavior described
1638 earlier for the -nosticky pragma.
1639
1640 -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect
1641 These are used to assign JavaScript event handlers. See the
1642 JavaScripting section for more details.
1643
1644 Other common arguments are described in the next section. In addition
1645 to these, all attributes described in the HTML specifications are
1646 supported.
1647
1648 CREATING A TEXT FIELD
1649 print textfield(-name=>'field_name',
1650 -value=>'starting value',
1651 -size=>50,
1652 -maxlength=>80);
1653 -or-
1654
1655 print textfield('field_name','starting value',50,80);
1656
1657 textfield() will return a text input field.
1658
1659 Parameters
1660 1. The first parameter is the required name for the field (-name).
1661
1662 2. The optional second parameter is the default starting value for the
1663 field contents (-value, formerly known as -default).
1664
1665 3. The optional third parameter is the size of the field in
1666 characters (-size).
1667
1668 4. The optional fourth parameter is the maximum number of characters
1669 the
1670 field will accept (-maxlength).
1671
1672 As with all these methods, the field will be initialized with its
1673 previous contents from earlier invocations of the script. When the
1674 form is processed, the value of the text field can be retrieved with:
1675
1676 $value = param('foo');
1677
1678 If you want to reset it from its initial value after the script has
1679 been called once, you can do so like this:
1680
1681 param('foo',"I'm taking over this value!");
1682
1683 CREATING A BIG TEXT FIELD
1684 print textarea(-name=>'foo',
1685 -default=>'starting value',
1686 -rows=>10,
1687 -columns=>50);
1688
1689 -or
1690
1691 print textarea('foo','starting value',10,50);
1692
1693 textarea() is just like textfield, but it allows you to specify rows
1694 and columns for a multiline text entry box. You can provide a starting
1695 value for the field, which can be long and contain multiple lines.
1696
1697 CREATING A PASSWORD FIELD
1698 print password_field(-name=>'secret',
1699 -value=>'starting value',
1700 -size=>50,
1701 -maxlength=>80);
1702 -or-
1703
1704 print password_field('secret','starting value',50,80);
1705
1706 password_field() is identical to textfield(), except that its contents
1707 will be starred out on the web page.
1708
1709 CREATING A FILE UPLOAD FIELD
1710 print filefield(-name=>'uploaded_file',
1711 -default=>'starting value',
1712 -size=>50,
1713 -maxlength=>80);
1714 -or-
1715
1716 print filefield('uploaded_file','starting value',50,80);
1717
1718 filefield() will return a file upload field. In order to take full
1719 advantage of this you must use the new multipart encoding scheme for
1720 the form. You can do this either by calling start_form() with an
1721 encoding type of &CGI::MULTIPART, or by calling the new method
1722 start_multipart_form() instead of vanilla start_form().
1723
1724 Parameters
1725 1. The first parameter is the required name for the field (-name).
1726
1727 2. The optional second parameter is the starting value for the field
1728 contents to be used as the default file name (-default).
1729
1730 For security reasons, browsers don't pay any attention to this
1731 field, and so the starting value will always be blank. Worse, the
1732 field loses its "sticky" behavior and forgets its previous
1733 contents. The starting value field is called for in the HTML
1734 specification, however, and possibly some browser will eventually
1735 provide support for it.
1736
1737 3. The optional third parameter is the size of the field in characters
1738 (-size).
1739
1740 4. The optional fourth parameter is the maximum number of characters
1741 the field will accept (-maxlength).
1742
1743 JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver,
1744 -onMouseOut and -onSelect parameters are recognized. See textfield()
1745 for details.
1746
1747 PROCESSING A FILE UPLOAD FIELD
1748 Basics
1749
1750 When the form is processed, you can retrieve an IO::Handle compatible
1751 handle for a file upload field like this:
1752
1753 $lightweight_fh = $q->upload('field_name');
1754
1755 # undef may be returned if it's not a valid file handle
1756 if (defined $lightweight_fh) {
1757 # Upgrade the handle to one compatible with IO::Handle:
1758 my $io_handle = $lightweight_fh->handle;
1759
1760 open (OUTFILE,'>>','/usr/local/web/users/feedback');
1761 while ($bytesread = $io_handle->read($buffer,1024)) {
1762 print OUTFILE $buffer;
1763 }
1764 }
1765
1766 In a list context, upload() will return an array of filehandles. This
1767 makes it possible to process forms that use the same name for multiple
1768 upload fields.
1769
1770 If you want the entered file name for the file, you can just call
1771 param():
1772
1773 $filename = $q->param('field_name');
1774
1775 Different browsers will return slightly different things for the name.
1776 Some browsers return the filename only. Others return the full path to
1777 the file, using the path conventions of the user's machine.
1778 Regardless, the name returned is always the name of the file on the
1779 user's machine, and is unrelated to the name of the temporary file that
1780 CGI.pm creates during upload spooling (see below).
1781
1782 When a file is uploaded the browser usually sends along some
1783 information along with it in the format of headers. The information
1784 usually includes the MIME content type. To retrieve this information,
1785 call uploadInfo(). It returns a reference to a hash containing all the
1786 document headers.
1787
1788 $filename = $q->param('uploaded_file');
1789 $type = $q->uploadInfo($filename)->{'Content-Type'};
1790 unless ($type eq 'text/html') {
1791 die "HTML FILES ONLY!";
1792 }
1793
1794 If you are using a machine that recognizes "text" and "binary" data
1795 modes, be sure to understand when and how to use them (see the Camel
1796 book). Otherwise you may find that binary files are corrupted during
1797 file uploads.
1798
1799 Accessing the temp files directly
1800
1801 When processing an uploaded file, CGI.pm creates a temporary file on
1802 your hard disk and passes you a file handle to that file. After you are
1803 finished with the file handle, CGI.pm unlinks (deletes) the temporary
1804 file. If you need to you can access the temporary file directly. You
1805 can access the temp file for a file upload by passing the file name to
1806 the tmpFileName() method:
1807
1808 $filename = $query->param('uploaded_file');
1809 $tmpfilename = $query->tmpFileName($filename);
1810
1811 The temporary file will be deleted automatically when your program
1812 exits unless you manually rename it. On some operating systems (such as
1813 Windows NT), you will need to close the temporary file's filehandle
1814 before your program exits. Otherwise the attempt to delete the
1815 temporary file will fail.
1816
1817 Handling interrupted file uploads
1818
1819 There are occasionally problems involving parsing the uploaded file.
1820 This usually happens when the user presses "Stop" before the upload is
1821 finished. In this case, CGI.pm will return undef for the name of the
1822 uploaded file and set cgi_error() to the string "400 Bad request
1823 (malformed multipart POST)". This error message is designed so that
1824 you can incorporate it into a status code to be sent to the browser.
1825 Example:
1826
1827 $file = $q->upload('uploaded_file');
1828 if (!$file && $q->cgi_error) {
1829 print $q->header(-status=>$q->cgi_error);
1830 exit 0;
1831 }
1832
1833 You are free to create a custom HTML page to complain about the error,
1834 if you wish.
1835
1836 Progress bars for file uploads and avoiding temp files
1837
1838 CGI.pm gives you low-level access to file upload management through a
1839 file upload hook. You can use this feature to completely turn off the
1840 temp file storage of file uploads, or potentially write your own file
1841 upload progress meter.
1842
1843 This is much like the UPLOAD_HOOK facility available in
1844 Apache::Request, with the exception that the first argument to the
1845 callback is an Apache::Upload object, here it's the remote filename.
1846
1847 $q = CGI->new(\&hook [,$data [,$use_tempfile]]);
1848
1849 sub hook {
1850 my ($filename, $buffer, $bytes_read, $data) = @_;
1851 print "Read $bytes_read bytes of $filename\n";
1852 }
1853
1854 The $data field is optional; it lets you pass configuration information
1855 (e.g. a database handle) to your hook callback.
1856
1857 The $use_tempfile field is a flag that lets you turn on and off
1858 CGI.pm's use of a temporary disk-based file during file upload. If you
1859 set this to a FALSE value (default true) then
1860 $q->param('uploaded_file') will no longer work, and the only way to get
1861 at the uploaded data is via the hook you provide.
1862
1863 If using the function-oriented interface, call the CGI::upload_hook()
1864 method before calling param() or any other CGI functions:
1865
1866 CGI::upload_hook(\&hook [,$data [,$use_tempfile]]);
1867
1868 This method is not exported by default. You will have to import it
1869 explicitly if you wish to use it without the CGI:: prefix.
1870
1871 Troubleshooting file uploads on Windows
1872
1873 If you are using CGI.pm on a Windows platform and find that binary
1874 files get slightly larger when uploaded but that text files remain the
1875 same, then you have forgotten to activate binary mode on the output
1876 filehandle. Be sure to call binmode() on any handle that you create to
1877 write the uploaded file to disk.
1878
1879 Older ways to process file uploads
1880
1881 ( This section is here for completeness. if you are building a new
1882 application with CGI.pm, you can skip it. )
1883
1884 The original way to process file uploads with CGI.pm was to use
1885 param(). The value it returns has a dual nature as both a file name and
1886 a lightweight filehandle. This dual nature is problematic if you
1887 following the recommended practice of having "use strict" in your code.
1888 Perl will complain when you try to use a string as a filehandle. More
1889 seriously, it is possible for the remote user to type garbage into the
1890 upload field, in which case what you get from param() is not a
1891 filehandle at all, but a string.
1892
1893 To solve this problem the upload() method was added, which always
1894 returns a lightweight filehandle. This generally works well, but will
1895 have trouble interoperating with some other modules because the file
1896 handle is not derived from IO::Handle. So that brings us to current
1897 recommendation given above, which is to call the handle() method on the
1898 file handle returned by upload(). That upgrades the handle to an
1899 IO::Handle. It's a big win for compatibility for a small penalty of
1900 loading IO::Handle the first time you call it.
1901
1902 CREATING A POPUP MENU
1903 print popup_menu('menu_name',
1904 ['eenie','meenie','minie'],
1905 'meenie');
1906
1907 -or-
1908
1909 %labels = ('eenie'=>'your first choice',
1910 'meenie'=>'your second choice',
1911 'minie'=>'your third choice');
1912 %attributes = ('eenie'=>{'class'=>'class of first choice'});
1913 print popup_menu('menu_name',
1914 ['eenie','meenie','minie'],
1915 'meenie',\%labels,\%attributes);
1916
1917 -or (named parameter style)-
1918
1919 print popup_menu(-name=>'menu_name',
1920 -values=>['eenie','meenie','minie'],
1921 -default=>['meenie','minie'],
1922 -labels=>\%labels,
1923 -attributes=>\%attributes);
1924
1925 popup_menu() creates a menu.
1926
1927 1. The required first argument is the menu's name (-name).
1928
1929 2. The required second argument (-values) is an array reference
1930 containing the list of menu items in the menu. You can pass the
1931 method an anonymous array, as shown in the example, or a reference
1932 to a named array, such as "\@foo".
1933
1934 3. The optional third parameter (-default) is the name of the default
1935 menu choice. If not specified, the first item will be the default.
1936 The values of the previous choice will be maintained across
1937 queries. Pass an array reference to select multiple defaults.
1938
1939 4. The optional fourth parameter (-labels) is provided for people who
1940 want to use different values for the user-visible label inside the
1941 popup menu and the value returned to your script. It's a pointer
1942 to an hash relating menu values to user-visible labels. If you
1943 leave this parameter blank, the menu values will be displayed by
1944 default. (You can also leave a label undefined if you want to).
1945
1946 5. The optional fifth parameter (-attributes) is provided to assign
1947 any of the common HTML attributes to an individual menu item. It's
1948 a pointer to a hash relating menu values to another hash with the
1949 attribute's name as the key and the attribute's value as the value.
1950
1951 When the form is processed, the selected value of the popup menu can be
1952 retrieved using:
1953
1954 $popup_menu_value = param('menu_name');
1955
1956 CREATING AN OPTION GROUP
1957 Named parameter style
1958
1959 print popup_menu(-name=>'menu_name',
1960 -values=>[qw/eenie meenie minie/,
1961 optgroup(-name=>'optgroup_name',
1962 -values => ['moe','catch'],
1963 -attributes=>{'catch'=>{'class'=>'red'}})],
1964 -labels=>{'eenie'=>'one',
1965 'meenie'=>'two',
1966 'minie'=>'three'},
1967 -default=>'meenie');
1968
1969 Old style
1970 print popup_menu('menu_name',
1971 ['eenie','meenie','minie',
1972 optgroup('optgroup_name', ['moe', 'catch'],
1973 {'catch'=>{'class'=>'red'}})],'meenie',
1974 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
1975
1976 optgroup() creates an option group within a popup menu.
1977
1978 1. The required first argument (-name) is the label attribute of the
1979 optgroup and is not inserted in the parameter list of the query.
1980
1981 2. The required second argument (-values) is an array reference
1982 containing the list of menu items in the menu. You can pass the
1983 method an anonymous array, as shown in the example, or a reference
1984 to a named array, such as \@foo. If you pass a HASH reference, the
1985 keys will be used for the menu values, and the values will be used
1986 for the menu labels (see -labels below).
1987
1988 3. The optional third parameter (-labels) allows you to pass a
1989 reference to a hash containing user-visible labels for one or more
1990 of the menu items. You can use this when you want the user to see
1991 one menu string, but have the browser return your program a
1992 different one. If you don't specify this, the value string will be
1993 used instead ("eenie", "meenie" and "minie" in this example). This
1994 is equivalent to using a hash reference for the -values parameter.
1995
1996 4. An optional fourth parameter (-labeled) can be set to a true value
1997 and indicates that the values should be used as the label attribute
1998 for each option element within the optgroup.
1999
2000 5. An optional fifth parameter (-novals) can be set to a true value
2001 and indicates to suppress the val attribute in each option element
2002 within the optgroup.
2003
2004 See the discussion on optgroup at W3C
2005 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
2006 for details.
2007
2008 6. An optional sixth parameter (-attributes) is provided to assign any
2009 of the common HTML attributes to an individual menu item. It's a
2010 pointer to a hash relating menu values to another hash with the
2011 attribute's name as the key and the attribute's value as the value.
2012
2013 CREATING A SCROLLING LIST
2014 print scrolling_list('list_name',
2015 ['eenie','meenie','minie','moe'],
2016 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
2017 -or-
2018
2019 print scrolling_list('list_name',
2020 ['eenie','meenie','minie','moe'],
2021 ['eenie','moe'],5,'true',
2022 \%labels,%attributes);
2023
2024 -or-
2025
2026 print scrolling_list(-name=>'list_name',
2027 -values=>['eenie','meenie','minie','moe'],
2028 -default=>['eenie','moe'],
2029 -size=>5,
2030 -multiple=>'true',
2031 -labels=>\%labels,
2032 -attributes=>\%attributes);
2033
2034 scrolling_list() creates a scrolling list.
2035
2036 Parameters:
2037 1. The first and second arguments are the list name (-name) and values
2038 (-values). As in the popup menu, the second argument should be an
2039 array reference.
2040
2041 2. The optional third argument (-default) can be either a reference to
2042 a list containing the values to be selected by default, or can be a
2043 single value to select. If this argument is missing or undefined,
2044 then nothing is selected when the list first appears. In the named
2045 parameter version, you can use the synonym "-defaults" for this
2046 parameter.
2047
2048 3. The optional fourth argument is the size of the list (-size).
2049
2050 4. The optional fifth argument can be set to true to allow multiple
2051 simultaneous selections (-multiple). Otherwise only one selection
2052 will be allowed at a time.
2053
2054 5. The optional sixth argument is a pointer to a hash containing long
2055 user-visible labels for the list items (-labels). If not provided,
2056 the values will be displayed.
2057
2058 6. The optional sixth parameter (-attributes) is provided to assign
2059 any of the common HTML attributes to an individual menu item. It's
2060 a pointer to a hash relating menu values to another hash with the
2061 attribute's name as the key and the attribute's value as the value.
2062
2063 When this form is processed, all selected list items will be
2064 returned as a list under the parameter name 'list_name'. The
2065 values of the selected items can be retrieved with:
2066
2067 @selected = param('list_name');
2068
2069 CREATING A GROUP OF RELATED CHECKBOXES
2070 print checkbox_group(-name=>'group_name',
2071 -values=>['eenie','meenie','minie','moe'],
2072 -default=>['eenie','moe'],
2073 -linebreak=>'true',
2074 -disabled => ['moe'],
2075 -labels=>\%labels,
2076 -attributes=>\%attributes);
2077
2078 print checkbox_group('group_name',
2079 ['eenie','meenie','minie','moe'],
2080 ['eenie','moe'],'true',\%labels,
2081 {'moe'=>{'class'=>'red'}});
2082
2083 HTML3-COMPATIBLE BROWSERS ONLY:
2084
2085 print checkbox_group(-name=>'group_name',
2086 -values=>['eenie','meenie','minie','moe'],
2087 -rows=2,-columns=>2);
2088
2089 checkbox_group() creates a list of checkboxes that are related by the
2090 same name.
2091
2092 Parameters:
2093 1. The first and second arguments are the checkbox name and values,
2094 respectively (-name and -values). As in the popup menu, the second
2095 argument should be an array reference. These values are used for
2096 the user-readable labels printed next to the checkboxes as well as
2097 for the values passed to your script in the query string.
2098
2099 2. The optional third argument (-default) can be either a reference to
2100 a list containing the values to be checked by default, or can be a
2101 single value to checked. If this argument is missing or undefined,
2102 then nothing is selected when the list first appears.
2103
2104 3. The optional fourth argument (-linebreak) can be set to true to
2105 place line breaks between the checkboxes so that they appear as a
2106 vertical list. Otherwise, they will be strung together on a
2107 horizontal line.
2108
2109 The optional -labels argument is a pointer to a hash relating the
2110 checkbox values to the user-visible labels that will be printed next to
2111 them. If not provided, the values will be used as the default.
2112
2113 The optional parameters -rows, and -columns cause checkbox_group() to
2114 return an HTML3 compatible table containing the checkbox group
2115 formatted with the specified number of rows and columns. You can
2116 provide just the -columns parameter if you wish; checkbox_group will
2117 calculate the correct number of rows for you.
2118
2119 The option -disabled takes an array of checkbox values and disables
2120 them by greying them out (this may not be supported by all browsers).
2121
2122 The optional -attributes argument is provided to assign any of the
2123 common HTML attributes to an individual menu item. It's a pointer to a
2124 hash relating menu values to another hash with the attribute's name as
2125 the key and the attribute's value as the value.
2126
2127 The optional -tabindex argument can be used to control the order in
2128 which radio buttons receive focus when the user presses the tab button.
2129 If passed a scalar numeric value, the first element in the group will
2130 receive this tab index and subsequent elements will be incremented by
2131 one. If given a reference to an array of radio button values, then the
2132 indexes will be jiggered so that the order specified in the array will
2133 correspond to the tab order. You can also pass a reference to a hash
2134 in which the hash keys are the radio button values and the values are
2135 the tab indexes of each button. Examples:
2136
2137 -tabindex => 100 # this group starts at index 100 and counts up
2138 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
2139 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2140
2141 The optional -labelattributes argument will contain attributes attached
2142 to the <label> element that surrounds each button.
2143
2144 When the form is processed, all checked boxes will be returned as a
2145 list under the parameter name 'group_name'. The values of the "on"
2146 checkboxes can be retrieved with:
2147
2148 @turned_on = param('group_name');
2149
2150 The value returned by checkbox_group() is actually an array of button
2151 elements. You can capture them and use them within tables, lists, or
2152 in other creative ways:
2153
2154 @h = checkbox_group(-name=>'group_name',-values=>\@values);
2155 &use_in_creative_way(@h);
2156
2157 CREATING A STANDALONE CHECKBOX
2158 print checkbox(-name=>'checkbox_name',
2159 -checked=>1,
2160 -value=>'ON',
2161 -label=>'CLICK ME');
2162
2163 -or-
2164
2165 print checkbox('checkbox_name','checked','ON','CLICK ME');
2166
2167 checkbox() is used to create an isolated checkbox that isn't logically
2168 related to any others.
2169
2170 Parameters:
2171 1. The first parameter is the required name for the checkbox (-name).
2172 It will also be used for the user-readable label printed next to
2173 the checkbox.
2174
2175 2. The optional second parameter (-checked) specifies that the
2176 checkbox is turned on by default. Synonyms are -selected and -on.
2177
2178 3. The optional third parameter (-value) specifies the value of the
2179 checkbox when it is checked. If not provided, the word "on" is
2180 assumed.
2181
2182 4. The optional fourth parameter (-label) is the user-readable label
2183 to be attached to the checkbox. If not provided, the checkbox name
2184 is used.
2185
2186 The value of the checkbox can be retrieved using:
2187
2188 $turned_on = param('checkbox_name');
2189
2190 CREATING A RADIO BUTTON GROUP
2191 print radio_group(-name=>'group_name',
2192 -values=>['eenie','meenie','minie'],
2193 -default=>'meenie',
2194 -linebreak=>'true',
2195 -labels=>\%labels,
2196 -attributes=>\%attributes);
2197
2198 -or-
2199
2200 print radio_group('group_name',['eenie','meenie','minie'],
2201 'meenie','true',\%labels,\%attributes);
2202
2203
2204 HTML3-COMPATIBLE BROWSERS ONLY:
2205
2206 print radio_group(-name=>'group_name',
2207 -values=>['eenie','meenie','minie','moe'],
2208 -rows=2,-columns=>2);
2209
2210 radio_group() creates a set of logically-related radio buttons (turning
2211 one member of the group on turns the others off)
2212
2213 Parameters:
2214 1. The first argument is the name of the group and is required
2215 (-name).
2216
2217 2. The second argument (-values) is the list of values for the radio
2218 buttons. The values and the labels that appear on the page are
2219 identical. Pass an array reference in the second argument, either
2220 using an anonymous array, as shown, or by referencing a named array
2221 as in "\@foo".
2222
2223 3. The optional third parameter (-default) is the name of the default
2224 button to turn on. If not specified, the first item will be the
2225 default. You can provide a nonexistent button name, such as "-" to
2226 start up with no buttons selected.
2227
2228 4. The optional fourth parameter (-linebreak) can be set to 'true' to
2229 put line breaks between the buttons, creating a vertical list.
2230
2231 5. The optional fifth parameter (-labels) is a pointer to an
2232 associative array relating the radio button values to user-visible
2233 labels to be used in the display. If not provided, the values
2234 themselves are displayed.
2235
2236 All modern browsers can take advantage of the optional parameters
2237 -rows, and -columns. These parameters cause radio_group() to return an
2238 HTML3 compatible table containing the radio group formatted with the
2239 specified number of rows and columns. You can provide just the
2240 -columns parameter if you wish; radio_group will calculate the correct
2241 number of rows for you.
2242
2243 To include row and column headings in the returned table, you can use
2244 the -rowheaders and -colheaders parameters. Both of these accept a
2245 pointer to an array of headings to use. The headings are just
2246 decorative. They don't reorganize the interpretation of the radio
2247 buttons -- they're still a single named unit.
2248
2249 The optional -tabindex argument can be used to control the order in
2250 which radio buttons receive focus when the user presses the tab button.
2251 If passed a scalar numeric value, the first element in the group will
2252 receive this tab index and subsequent elements will be incremented by
2253 one. If given a reference to an array of radio button values, then the
2254 indexes will be jiggered so that the order specified in the array will
2255 correspond to the tab order. You can also pass a reference to a hash
2256 in which the hash keys are the radio button values and the values are
2257 the tab indexes of each button. Examples:
2258
2259 -tabindex => 100 # this group starts at index 100 and counts up
2260 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
2261 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2262
2263 The optional -attributes argument is provided to assign any of the
2264 common HTML attributes to an individual menu item. It's a pointer to a
2265 hash relating menu values to another hash with the attribute's name as
2266 the key and the attribute's value as the value.
2267
2268 The optional -labelattributes argument will contain attributes attached
2269 to the <label> element that surrounds each button.
2270
2271 When the form is processed, the selected radio button can be retrieved
2272 using:
2273
2274 $which_radio_button = param('group_name');
2275
2276 The value returned by radio_group() is actually an array of button
2277 elements. You can capture them and use them within tables, lists, or
2278 in other creative ways:
2279
2280 @h = radio_group(-name=>'group_name',-values=>\@values);
2281 &use_in_creative_way(@h);
2282
2283 CREATING A SUBMIT BUTTON
2284 print submit(-name=>'button_name',
2285 -value=>'value');
2286
2287 -or-
2288
2289 print submit('button_name','value');
2290
2291 submit() will create the query submission button. Every form should
2292 have one of these.
2293
2294 Parameters:
2295 1. The first argument (-name) is optional. You can give the button a
2296 name if you have several submission buttons in your form and you
2297 want to distinguish between them.
2298
2299 2. The second argument (-value) is also optional. This gives the
2300 button a value that will be passed to your script in the query
2301 string. The name will also be used as the user-visible label.
2302
2303 3. You can use -label as an alias for -value. I always get confused
2304 about which of -name and -value changes the user-visible label on
2305 the button.
2306
2307 You can figure out which button was pressed by using different values
2308 for each one:
2309
2310 $which_one = param('button_name');
2311
2312 CREATING A RESET BUTTON
2313 print reset
2314
2315 reset() creates the "reset" button. Note that it restores the form to
2316 its value from the last time the script was called, NOT necessarily to
2317 the defaults.
2318
2319 Note that this conflicts with the Perl reset() built-in. Use
2320 CORE::reset() to get the original reset function.
2321
2322 CREATING A DEFAULT BUTTON
2323 print defaults('button_label')
2324
2325 defaults() creates a button that, when invoked, will cause the form to
2326 be completely reset to its defaults, wiping out all the changes the
2327 user ever made.
2328
2329 CREATING A HIDDEN FIELD
2330 print hidden(-name=>'hidden_name',
2331 -default=>['value1','value2'...]);
2332
2333 -or-
2334
2335 print hidden('hidden_name','value1','value2'...);
2336
2337 hidden() produces a text field that can't be seen by the user. It is
2338 useful for passing state variable information from one invocation of
2339 the script to the next.
2340
2341 Parameters:
2342 1. The first argument is required and specifies the name of this field
2343 (-name).
2344
2345 2. The second argument is also required and specifies its value
2346 (-default). In the named parameter style of calling, you can
2347 provide a single value here or a reference to a whole list
2348
2349 Fetch the value of a hidden field this way:
2350
2351 $hidden_value = param('hidden_name');
2352
2353 Note, that just like all the other form elements, the value of a hidden
2354 field is "sticky". If you want to replace a hidden field with some
2355 other values after the script has been called once you'll have to do it
2356 manually:
2357
2358 param('hidden_name','new','values','here');
2359
2360 CREATING A CLICKABLE IMAGE BUTTON
2361 print image_button(-name=>'button_name',
2362 -src=>'/source/URL',
2363 -align=>'MIDDLE');
2364
2365 -or-
2366
2367 print image_button('button_name','/source/URL','MIDDLE');
2368
2369 image_button() produces a clickable image. When it's clicked on the
2370 position of the click is returned to your script as "button_name.x" and
2371 "button_name.y", where "button_name" is the name you've assigned to it.
2372
2373 Parameters:
2374 1. The first argument (-name) is required and specifies the name of
2375 this field.
2376
2377 2. The second argument (-src) is also required and specifies the URL
2378
2379 3. The third option (-align, optional) is an alignment type, and may be
2380 TOP, BOTTOM or MIDDLE
2381
2382 Fetch the value of the button this way:
2383 $x = param('button_name.x');
2384 $y = param('button_name.y');
2385
2386 CREATING A JAVASCRIPT ACTION BUTTON
2387 print button(-name=>'button_name',
2388 -value=>'user visible label',
2389 -onClick=>"do_something()");
2390
2391 -or-
2392
2393 print button('button_name',"user visible value","do_something()");
2394
2395 button() produces an "<input>" tag with "type="button"". When it's
2396 pressed the fragment of JavaScript code pointed to by the -onClick
2397 parameter will be executed.
2398
2400 Browsers support a so-called "cookie" designed to help maintain state
2401 within a browser session. CGI.pm has several methods that support
2402 cookies.
2403
2404 A cookie is a name=value pair much like the named parameters in a CGI
2405 query string. CGI scripts create one or more cookies and send them to
2406 the browser in the HTTP header. The browser maintains a list of
2407 cookies that belong to a particular Web server, and returns them to the
2408 CGI script during subsequent interactions.
2409
2410 In addition to the required name=value pair, each cookie has several
2411 optional attributes:
2412
2413 1. an expiration time
2414 This is a time/date string (in a special GMT format) that indicates
2415 when a cookie expires. The cookie will be saved and returned to
2416 your script until this expiration date is reached if the user exits
2417 the browser and restarts it. If an expiration date isn't
2418 specified, the cookie will remain active until the user quits the
2419 browser.
2420
2421 2. a domain
2422 This is a partial or complete domain name for which the cookie is
2423 valid. The browser will return the cookie to any host that matches
2424 the partial domain name. For example, if you specify a domain name
2425 of ".capricorn.com", then the browser will return the cookie to Web
2426 servers running on any of the machines "www.capricorn.com",
2427 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
2428 must contain at least two periods to prevent attempts to match on
2429 top level domains like ".edu". If no domain is specified, then the
2430 browser will only return the cookie to servers on the host the
2431 cookie originated from.
2432
2433 3. a path
2434 If you provide a cookie path attribute, the browser will check it
2435 against your script's URL before returning the cookie. For
2436 example, if you specify the path "/cgi-bin", then the cookie will
2437 be returned to each of the scripts "/cgi-bin/tally.pl",
2438 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
2439 but not to the script "/cgi-private/site_admin.pl". By default,
2440 path is set to "/", which causes the cookie to be sent to any CGI
2441 script on your site.
2442
2443 4. a "secure" flag
2444 If the "secure" attribute is set, the cookie will only be sent to
2445 your script if the CGI request is occurring on a secure channel,
2446 such as SSL.
2447
2448 The interface to HTTP cookies is the cookie() method:
2449
2450 $cookie = cookie(-name=>'sessionID',
2451 -value=>'xyzzy',
2452 -expires=>'+1h',
2453 -path=>'/cgi-bin/database',
2454 -domain=>'.capricorn.org',
2455 -secure=>1);
2456 print header(-cookie=>$cookie);
2457
2458 cookie() creates a new cookie. Its parameters include:
2459
2460 -name
2461 The name of the cookie (required). This can be any string at all.
2462 Although browsers limit their cookie names to non-whitespace
2463 alphanumeric characters, CGI.pm removes this restriction by
2464 escaping and unescaping cookies behind the scenes.
2465
2466 -value
2467 The value of the cookie. This can be any scalar value, array
2468 reference, or even hash reference. For example, you can store an
2469 entire hash into a cookie this way:
2470
2471 $cookie=cookie(-name=>'family information',
2472 -value=>\%childrens_ages);
2473
2474 -path
2475 The optional partial path for which this cookie will be valid, as
2476 described above.
2477
2478 -domain
2479 The optional partial domain for which this cookie will be valid, as
2480 described above.
2481
2482 -expires
2483 The optional expiration date for this cookie. The format is as
2484 described in the section on the header() method:
2485
2486 "+1h" one hour from now
2487
2488 -secure
2489 If set to true, this cookie will only be used within a secure SSL
2490 session.
2491
2492 The cookie created by cookie() must be incorporated into the HTTP
2493 header within the string returned by the header() method:
2494
2495 use CGI ':standard';
2496 print header(-cookie=>$my_cookie);
2497
2498 To create multiple cookies, give header() an array reference:
2499
2500 $cookie1 = cookie(-name=>'riddle_name',
2501 -value=>"The Sphynx's Question");
2502 $cookie2 = cookie(-name=>'answers',
2503 -value=>\%answers);
2504 print header(-cookie=>[$cookie1,$cookie2]);
2505
2506 To retrieve a cookie, request it by name by calling cookie() method
2507 without the -value parameter. This example uses the object-oriented
2508 form:
2509
2510 use CGI;
2511 $query = CGI->new;
2512 $riddle = $query->cookie('riddle_name');
2513 %answers = $query->cookie('answers');
2514
2515 Cookies created with a single scalar value, such as the "riddle_name"
2516 cookie, will be returned in that form. Cookies with array and hash
2517 values can also be retrieved.
2518
2519 The cookie and CGI namespaces are separate. If you have a parameter
2520 named 'answers' and a cookie named 'answers', the values retrieved by
2521 param() and cookie() are independent of each other. However, it's
2522 simple to turn a CGI parameter into a cookie, and vice-versa:
2523
2524 # turn a CGI parameter into a cookie
2525 $c=cookie(-name=>'answers',-value=>[param('answers')]);
2526 # vice-versa
2527 param(-name=>'answers',-value=>[cookie('answers')]);
2528
2529 If you call cookie() without any parameters, it will return a list of
2530 the names of all cookies passed to your script:
2531
2532 @cookies = cookie();
2533
2534 See the cookie.cgi example script for some ideas on how to use cookies
2535 effectively.
2536
2538 It's possible for CGI.pm scripts to write into several browser panels
2539 and windows using the HTML 4 frame mechanism. There are three
2540 techniques for defining new frames programmatically:
2541
2542 1. Create a <Frameset> document
2543 After writing out the HTTP header, instead of creating a standard
2544 HTML document using the start_html() call, create a <frameset>
2545 document that defines the frames on the page. Specify your
2546 script(s) (with appropriate parameters) as the SRC for each of the
2547 frames.
2548
2549 There is no specific support for creating <frameset> sections in
2550 CGI.pm, but the HTML is very simple to write.
2551
2552 2. Specify the destination for the document in the HTTP header
2553 You may provide a -target parameter to the header() method:
2554
2555 print header(-target=>'ResultsWindow');
2556
2557 This will tell the browser to load the output of your script into
2558 the frame named "ResultsWindow". If a frame of that name doesn't
2559 already exist, the browser will pop up a new window and load your
2560 script's document into that. There are a number of magic names
2561 that you can use for targets. See the HTML "<frame>" documentation
2562 for details.
2563
2564 3. Specify the destination for the document in the <form> tag
2565 You can specify the frame to load in the FORM tag itself. With
2566 CGI.pm it looks like this:
2567
2568 print start_form(-target=>'ResultsWindow');
2569
2570 When your script is reinvoked by the form, its output will be
2571 loaded into the frame named "ResultsWindow". If one doesn't
2572 already exist a new window will be created.
2573
2574 The script "frameset.cgi" in the examples directory shows one way to
2575 create pages in which the fill-out form and the response live in side-
2576 by-side frames.
2577
2579 The usual way to use JavaScript is to define a set of functions in a
2580 <SCRIPT> block inside the HTML header and then to register event
2581 handlers in the various elements of the page. Events include such
2582 things as the mouse passing over a form element, a button being
2583 clicked, the contents of a text field changing, or a form being
2584 submitted. When an event occurs that involves an element that has
2585 registered an event handler, its associated JavaScript code gets
2586 called.
2587
2588 The elements that can register event handlers include the <BODY> of an
2589 HTML document, hypertext links, all the various elements of a fill-out
2590 form, and the form itself. There are a large number of events, and each
2591 applies only to the elements for which it is relevant. Here is a
2592 partial list:
2593
2594 onLoad
2595 The browser is loading the current document. Valid in:
2596
2597 + The HTML <BODY> section only.
2598
2599 onUnload
2600 The browser is closing the current page or frame. Valid for:
2601
2602 + The HTML <BODY> section only.
2603
2604 onSubmit
2605 The user has pressed the submit button of a form. This event
2606 happens just before the form is submitted, and your function can
2607 return a value of false in order to abort the submission. Valid
2608 for:
2609
2610 + Forms only.
2611
2612 onClick
2613 The mouse has clicked on an item in a fill-out form. Valid for:
2614
2615 + Buttons (including submit, reset, and image buttons)
2616 + Checkboxes
2617 + Radio buttons
2618
2619 onChange
2620 The user has changed the contents of a field. Valid for:
2621
2622 + Text fields
2623 + Text areas
2624 + Password fields
2625 + File fields
2626 + Popup Menus
2627 + Scrolling lists
2628
2629 onFocus
2630 The user has selected a field to work with. Valid for:
2631
2632 + Text fields
2633 + Text areas
2634 + Password fields
2635 + File fields
2636 + Popup Menus
2637 + Scrolling lists
2638
2639 onBlur
2640 The user has deselected a field (gone to work somewhere else).
2641 Valid for:
2642
2643 + Text fields
2644 + Text areas
2645 + Password fields
2646 + File fields
2647 + Popup Menus
2648 + Scrolling lists
2649
2650 onSelect
2651 The user has changed the part of a text field that is selected.
2652 Valid for:
2653
2654 + Text fields
2655 + Text areas
2656 + Password fields
2657 + File fields
2658
2659 onMouseOver
2660 The mouse has moved over an element.
2661
2662 + Text fields
2663 + Text areas
2664 + Password fields
2665 + File fields
2666 + Popup Menus
2667 + Scrolling lists
2668
2669 onMouseOut
2670 The mouse has moved off an element.
2671
2672 + Text fields
2673 + Text areas
2674 + Password fields
2675 + File fields
2676 + Popup Menus
2677 + Scrolling lists
2678
2679 In order to register a JavaScript event handler with an HTML element,
2680 just use the event name as a parameter when you call the corresponding
2681 CGI method. For example, to have your validateAge() JavaScript code
2682 executed every time the textfield named "age" changes, generate the
2683 field like this:
2684
2685 print textfield(-name=>'age',-onChange=>"validateAge(this)");
2686
2687 This example assumes that you've already declared the validateAge()
2688 function by incorporating it into a <SCRIPT> block. The CGI.pm
2689 start_html() method provides a convenient way to create this section.
2690
2691 Similarly, you can create a form that checks itself over for
2692 consistency and alerts the user if some essential value is missing by
2693 creating it this way:
2694 print start_form(-onSubmit=>"validateMe(this)");
2695
2696 See the javascript.cgi script for a demonstration of how this all
2697 works.
2698
2700 CGI.pm has limited support for HTML3's cascading style sheets (css).
2701 To incorporate a stylesheet into your document, pass the start_html()
2702 method a -style parameter. The value of this parameter may be a
2703 scalar, in which case it is treated as the source URL for the
2704 stylesheet, or it may be a hash reference. In the latter case you
2705 should provide the hash with one or more of -src or -code. -src points
2706 to a URL where an externally-defined stylesheet can be found. -code
2707 points to a scalar value to be incorporated into a <style> section.
2708 Style definitions in -code override similarly-named ones in -src, hence
2709 the name "cascading."
2710
2711 You may also specify the type of the stylesheet by adding the optional
2712 -type parameter to the hash pointed to by -style. If not specified,
2713 the style defaults to 'text/css'.
2714
2715 To refer to a style within the body of your document, add the -class
2716 parameter to any HTML element:
2717
2718 print h1({-class=>'Fancy'},'Welcome to the Party');
2719
2720 Or define styles on the fly with the -style parameter:
2721
2722 print h1({-style=>'Color: red;'},'Welcome to Hell');
2723
2724 You may also use the new span() element to apply a style to a section
2725 of text:
2726
2727 print span({-style=>'Color: red;'},
2728 h1('Welcome to Hell'),
2729 "Where did that handbasket get to?"
2730 );
2731
2732 Note that you must import the ":html3" definitions to have the span()
2733 method available. Here's a quick and dirty example of using CSS's.
2734 See the CSS specification at http://www.w3.org/Style/CSS/ for more
2735 information.
2736
2737 use CGI qw/:standard :html3/;
2738
2739 #here's a stylesheet incorporated directly into the page
2740 $newStyle=<<END;
2741 <!--
2742 P.Tip {
2743 margin-right: 50pt;
2744 margin-left: 50pt;
2745 color: red;
2746 }
2747 P.Alert {
2748 font-size: 30pt;
2749 font-family: sans-serif;
2750 color: red;
2751 }
2752 -->
2753 END
2754 print header();
2755 print start_html( -title=>'CGI with Style',
2756 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
2757 -code=>$newStyle}
2758 );
2759 print h1('CGI with Style'),
2760 p({-class=>'Tip'},
2761 "Better read the cascading style sheet spec before playing with this!"),
2762 span({-style=>'color: magenta'},
2763 "Look Mom, no hands!",
2764 p(),
2765 "Whooo wee!"
2766 );
2767 print end_html;
2768
2769 Pass an array reference to -code or -src in order to incorporate
2770 multiple stylesheets into your document.
2771
2772 Should you wish to incorporate a verbatim stylesheet that includes
2773 arbitrary formatting in the header, you may pass a -verbatim tag to the
2774 -style hash, as follows:
2775
2776 print start_html (-style => {-verbatim => '@import
2777 url("/server-common/css/'.$cssFile.'");',
2778 -src => '/server-common/css/core.css'});
2779
2780 This will generate an HTML header that contains this:
2781
2782 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
2783 <style type="text/css">
2784 @import url("/server-common/css/main.css");
2785 </style>
2786
2787 Any additional arguments passed in the -style value will be
2788 incorporated into the <link> tag. For example:
2789
2790 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
2791 -media => 'all'});
2792
2793 This will give:
2794
2795 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
2796 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
2797
2798 <p>
2799
2800 To make more complicated <link> tags, use the Link() function and pass
2801 it to start_html() in the -head argument, as in:
2802
2803 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
2804 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
2805 print start_html({-head=>\@h})
2806
2807 To create primary and "alternate" stylesheet, use the -alternate
2808 option:
2809
2810 start_html(-style=>{-src=>[
2811 {-src=>'/styles/print.css'},
2812 {-src=>'/styles/alt.css',-alternate=>1}
2813 ]
2814 });
2815
2817 If you are running the script from the command line or in the perl
2818 debugger, you can pass the script a list of keywords or parameter=value
2819 pairs on the command line or from standard input (you don't have to
2820 worry about tricking your script into reading from environment
2821 variables). You can pass keywords like this:
2822
2823 your_script.pl keyword1 keyword2 keyword3
2824
2825 or this:
2826
2827 your_script.pl keyword1+keyword2+keyword3
2828
2829 or this:
2830
2831 your_script.pl name1=value1 name2=value2
2832
2833 or this:
2834
2835 your_script.pl name1=value1&name2=value2
2836
2837 To turn off this feature, use the -no_debug pragma.
2838
2839 To test the POST method, you may enable full debugging with the -debug
2840 pragma. This will allow you to feed newline-delimited name=value pairs
2841 to the script on standard input.
2842
2843 When debugging, you can use quotes and backslashes to escape characters
2844 in the familiar shell manner, letting you place spaces and other funny
2845 characters in your parameter=value pairs:
2846
2847 your_script.pl "name1='I am a long value'" "name2=two\ words"
2848
2849 Finally, you can set the path info for the script by prefixing the
2850 first name/value parameter with the path followed by a question mark
2851 (?):
2852
2853 your_script.pl /your/path/here?name1=value1&name2=value2
2854
2855 DUMPING OUT ALL THE NAME/VALUE PAIRS
2856 The Dump() method produces a string consisting of all the query's
2857 name/value pairs formatted nicely as a nested list. This is useful for
2858 debugging purposes:
2859
2860 print Dump
2861
2862 Produces something that looks like:
2863
2864 <ul>
2865 <li>name1
2866 <ul>
2867 <li>value1
2868 <li>value2
2869 </ul>
2870 <li>name2
2871 <ul>
2872 <li>value1
2873 </ul>
2874 </ul>
2875
2876 As a shortcut, you can interpolate the entire CGI object into a string
2877 and it will be replaced with the a nice HTML dump shown above:
2878
2879 $query=CGI->new;
2880 print "<h2>Current Values</h2> $query\n";
2881
2883 Some of the more useful environment variables can be fetched through
2884 this interface. The methods are as follows:
2885
2886 Accept()
2887 Return a list of MIME types that the remote browser accepts. If you
2888 give this method a single argument corresponding to a MIME type, as
2889 in Accept('text/html'), it will return a floating point value
2890 corresponding to the browser's preference for this type from 0.0
2891 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's
2892 accept list are handled correctly.
2893
2894 Note that the capitalization changed between version 2.43 and 2.44
2895 in order to avoid conflict with Perl's accept() function.
2896
2897 raw_cookie()
2898 Returns the HTTP_COOKIE variable. Cookies have a special format,
2899 and this method call just returns the raw form (?cookie dough).
2900 See cookie() for ways of setting and retrieving cooked cookies.
2901
2902 Called with no parameters, raw_cookie() returns the packed cookie
2903 structure. You can separate it into individual cookies by
2904 splitting on the character sequence "; ". Called with the name of
2905 a cookie, retrieves the unescaped form of the cookie. You can use
2906 the regular cookie() method to get the names, or use the
2907 raw_fetch() method from the CGI::Cookie module.
2908
2909 user_agent()
2910 Returns the HTTP_USER_AGENT variable. If you give this method a
2911 single argument, it will attempt to pattern match on it, allowing
2912 you to do something like user_agent(Mozilla);
2913
2914 path_info()
2915 Returns additional path information from the script URL. E.G.
2916 fetching /cgi-bin/your_script/additional/stuff will result in
2917 path_info() returning "/additional/stuff".
2918
2919 NOTE: The Microsoft Internet Information Server is broken with
2920 respect to additional path information. If you use the Perl DLL
2921 library, the IIS server will attempt to execute the additional path
2922 information as a Perl script. If you use the ordinary file
2923 associations mapping, the path information will be present in the
2924 environment, but incorrect. The best thing to do is to avoid using
2925 additional path information in CGI scripts destined for use with
2926 IIS.
2927
2928 path_translated()
2929 As per path_info() but returns the additional path information
2930 translated into a physical path, e.g.
2931 "/usr/local/etc/httpd/htdocs/additional/stuff".
2932
2933 The Microsoft IIS is broken with respect to the translated path as
2934 well.
2935
2936 remote_host()
2937 Returns either the remote host name or IP address. if the former
2938 is unavailable.
2939
2940 remote_addr()
2941 Returns the remote host IP address, or 127.0.0.1 if the address is
2942 unavailable.
2943
2944 script_name() Return the script name as a partial URL, for self-
2945 referring scripts.
2946 referer()
2947 Return the URL of the page the browser was viewing prior to
2948 fetching your script. Not available for all browsers.
2949
2950 auth_type ()
2951 Return the authorization/verification method in use for this
2952 script, if any.
2953
2954 server_name ()
2955 Returns the name of the server, usually the machine's host name.
2956
2957 virtual_host ()
2958 When using virtual hosts, returns the name of the host that the
2959 browser attempted to contact
2960
2961 server_port ()
2962 Return the port that the server is listening on.
2963
2964 virtual_port ()
2965 Like server_port() except that it takes virtual hosts into account.
2966 Use this when running with virtual hosts.
2967
2968 server_software ()
2969 Returns the server software and version number.
2970
2971 remote_user ()
2972 Return the authorization/verification name used for user
2973 verification, if this script is protected.
2974
2975 user_name ()
2976 Attempt to obtain the remote user's name, using a variety of
2977 different techniques. This only works with older browsers such as
2978 Mosaic. Newer browsers do not report the user name for privacy
2979 reasons!
2980
2981 request_method()
2982 Returns the method used to access your script, usually one of
2983 'POST', 'GET' or 'HEAD'.
2984
2985 content_type()
2986 Returns the content_type of data submitted in a POST, generally
2987 multipart/form-data or application/x-www-form-urlencoded
2988
2989 http()
2990 Called with no arguments returns the list of HTTP environment
2991 variables, including such things as HTTP_USER_AGENT,
2992 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
2993 like-named HTTP header fields in the request. Called with the name
2994 of an HTTP header field, returns its value. Capitalization and the
2995 use of hyphens versus underscores are not significant.
2996
2997 For example, all three of these examples are equivalent:
2998
2999 $requested_language = http('Accept-language');
3000 $requested_language = http('Accept_language');
3001 $requested_language = http('HTTP_ACCEPT_LANGUAGE');
3002
3003 https()
3004 The same as http(), but operates on the HTTPS environment variables
3005 present when the SSL protocol is in effect. Can be used to
3006 determine whether SSL is turned on.
3007
3009 NPH, or "no-parsed-header", scripts bypass the server completely by
3010 sending the complete HTTP header directly to the browser. This has
3011 slight performance benefits, but is of most use for taking advantage of
3012 HTTP extensions that are not directly supported by your server, such as
3013 server push and PICS headers.
3014
3015 Servers use a variety of conventions for designating CGI scripts as
3016 NPH. Many Unix servers look at the beginning of the script's name for
3017 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
3018 Internet Information Server, in contrast, try to decide whether a
3019 program is an NPH script by examining the first line of script output.
3020
3021 CGI.pm supports NPH scripts with a special NPH mode. When in this
3022 mode, CGI.pm will output the necessary extra header information when
3023 the header() and redirect() methods are called.
3024
3025 The Microsoft Internet Information Server requires NPH mode. As of
3026 version 2.30, CGI.pm will automatically detect when the script is
3027 running under IIS and put itself into this mode. You do not need to do
3028 this manually, although it won't hurt anything if you do. However,
3029 note that if you have applied Service Pack 6, much of the functionality
3030 of NPH scripts, including the ability to redirect while setting a
3031 cookie, do not work at all on IIS without a special patch from
3032 Microsoft. See
3033 http://web.archive.org/web/20010812012030/http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP
3034 Non-Parsed Headers Stripped From CGI Applications That Have nph- Prefix
3035 in Name.
3036
3037 In the use statement
3038 Simply add the "-nph" pragma to the list of symbols to be imported
3039 into your script:
3040
3041 use CGI qw(:standard -nph)
3042
3043 By calling the nph() method:
3044 Call nph() with a non-zero parameter at any point after using
3045 CGI.pm in your program.
3046
3047 CGI->nph(1)
3048
3049 By using -nph parameters
3050 in the header() and redirect() statements:
3051
3052 print header(-nph=>1);
3053
3055 CGI.pm provides four simple functions for producing multipart documents
3056 of the type needed to implement server push. These functions were
3057 graciously provided by Ed Jordan <ed@fidalgo.net>. To import these
3058 into your namespace, you must import the ":push" set. You are also
3059 advised to put the script into NPH mode and to set $| to 1 to avoid
3060 buffering problems.
3061
3062 Here is a simple script that demonstrates server push:
3063
3064 #!/usr/local/bin/perl
3065 use CGI qw/:push -nph/;
3066 $| = 1;
3067 print multipart_init(-boundary=>'----here we go!');
3068 for (0 .. 4) {
3069 print multipart_start(-type=>'text/plain'),
3070 "The current time is ",scalar(localtime),"\n";
3071 if ($_ < 4) {
3072 print multipart_end;
3073 } else {
3074 print multipart_final;
3075 }
3076 sleep 1;
3077 }
3078
3079 This script initializes server push by calling multipart_init(). It
3080 then enters a loop in which it begins a new multipart section by
3081 calling multipart_start(), prints the current local time, and ends a
3082 multipart section with multipart_end(). It then sleeps a second, and
3083 begins again. On the final iteration, it ends the multipart section
3084 with multipart_final() rather than with multipart_end().
3085
3086 multipart_init()
3087 multipart_init(-boundary=>$boundary);
3088
3089 Initialize the multipart system. The -boundary argument specifies
3090 what MIME boundary string to use to separate parts of the document.
3091 If not provided, CGI.pm chooses a reasonable boundary for you.
3092
3093 multipart_start()
3094 multipart_start(-type=>$type)
3095
3096 Start a new part of the multipart document using the specified MIME
3097 type. If not specified, text/html is assumed.
3098
3099 multipart_end()
3100 multipart_end()
3101
3102 End a part. You must remember to call multipart_end() once for
3103 each multipart_start(), except at the end of the last part of the
3104 multipart document when multipart_final() should be called instead
3105 of multipart_end().
3106
3107 multipart_final()
3108 multipart_final()
3109
3110 End all parts. You should call multipart_final() rather than
3111 multipart_end() at the end of the last part of the multipart
3112 document.
3113
3114 Users interested in server push applications should also have a look at
3115 the CGI::Push module.
3116
3118 A potential problem with CGI.pm is that, by default, it attempts to
3119 process form POSTings no matter how large they are. A wily hacker
3120 could attack your site by sending a CGI script a huge POST of many
3121 megabytes. CGI.pm will attempt to read the entire POST into a
3122 variable, growing hugely in size until it runs out of memory. While
3123 the script attempts to allocate the memory the system may slow down
3124 dramatically. This is a form of denial of service attack.
3125
3126 Another possible attack is for the remote user to force CGI.pm to
3127 accept a huge file upload. CGI.pm will accept the upload and store it
3128 in a temporary directory even if your script doesn't expect to receive
3129 an uploaded file. CGI.pm will delete the file automatically when it
3130 terminates, but in the meantime the remote user may have filled up the
3131 server's disk space, causing problems for other programs.
3132
3133 The best way to avoid denial of service attacks is to limit the amount
3134 of memory, CPU time and disk space that CGI scripts can use. Some Web
3135 servers come with built-in facilities to accomplish this. In other
3136 cases, you can use the shell limit or ulimit commands to put ceilings
3137 on CGI resource usage.
3138
3139 CGI.pm also has some simple built-in protections against denial of
3140 service attacks, but you must activate them before you can use them.
3141 These take the form of two global variables in the CGI name space:
3142
3143 $CGI::POST_MAX
3144 If set to a non-negative integer, this variable puts a ceiling on
3145 the size of POSTings, in bytes. If CGI.pm detects a POST that is
3146 greater than the ceiling, it will immediately exit with an error
3147 message. This value will affect both ordinary POSTs and multipart
3148 POSTs, meaning that it limits the maximum size of file uploads as
3149 well. You should set this to a reasonably high value, such as 1
3150 megabyte.
3151
3152 $CGI::DISABLE_UPLOADS
3153 If set to a non-zero value, this will disable file uploads
3154 completely. Other fill-out form values will work as usual.
3155
3156 You can use these variables in either of two ways.
3157
3158 1. On a script-by-script basis
3159 Set the variable at the top of the script, right after the "use"
3160 statement:
3161
3162 use CGI qw/:standard/;
3163 use CGI::Carp 'fatalsToBrowser';
3164 $CGI::POST_MAX=1024 * 100; # max 100K posts
3165 $CGI::DISABLE_UPLOADS = 1; # no uploads
3166
3167 2. Globally for all scripts
3168 Open up CGI.pm, find the definitions for $POST_MAX and
3169 $DISABLE_UPLOADS, and set them to the desired values. You'll find
3170 them towards the top of the file in a subroutine named
3171 initialize_globals().
3172
3173 An attempt to send a POST larger than $POST_MAX bytes will cause
3174 param() to return an empty CGI parameter list. You can test for this
3175 event by checking cgi_error(), either after you create the CGI object
3176 or, if you are using the function-oriented interface, call <param()>
3177 for the first time. If the POST was intercepted, then cgi_error() will
3178 return the message "413 POST too large".
3179
3180 This error message is actually defined by the HTTP protocol, and is
3181 designed to be returned to the browser as the CGI script's status
3182 code. For example:
3183
3184 $uploaded_file = param('upload');
3185 if (!$uploaded_file && cgi_error()) {
3186 print header(-status=>cgi_error());
3187 exit 0;
3188 }
3189
3190 However it isn't clear that any browser currently knows what to do with
3191 this status code. It might be better just to create an HTML page that
3192 warns the user of the problem.
3193
3195 To make it easier to port existing programs that use cgi-lib.pl the
3196 compatibility routine "ReadParse" is provided. Porting is simple:
3197
3198 OLD VERSION
3199
3200 require "cgi-lib.pl";
3201 &ReadParse;
3202 print "The value of the antique is $in{antique}.\n";
3203
3204 NEW VERSION
3205
3206 use CGI;
3207 CGI::ReadParse();
3208 print "The value of the antique is $in{antique}.\n";
3209
3210 CGI.pm's ReadParse() routine creates a tied variable named %in, which
3211 can be accessed to obtain the query variables. Like ReadParse, you can
3212 also provide your own variable. Infrequently used features of
3213 ReadParse, such as the creation of @in and $in variables, are not
3214 supported.
3215
3216 Once you use ReadParse, you can retrieve the query object itself this
3217 way:
3218
3219 $q = $in{CGI};
3220 print $q->textfield(-name=>'wow',
3221 -value=>'does this really work?');
3222
3223 This allows you to start using the more interesting features of CGI.pm
3224 without rewriting your old scripts from scratch.
3225
3226 An even simpler way to mix cgi-lib calls with CGI.pm calls is to import
3227 both the ":cgi-lib" and ":standard" method:
3228
3229 use CGI qw(:cgi-lib :standard);
3230 &ReadParse;
3231 print "The price of your purchase is $in{price}.\n";
3232 print textfield(-name=>'price', -default=>'$1.99');
3233
3234 Cgi-lib functions that are available in CGI.pm
3235 In compatibility mode, the following cgi-lib.pl functions are available
3236 for your use:
3237
3238 ReadParse()
3239 PrintHeader()
3240 HtmlTop()
3241 HtmlBot()
3242 SplitParam()
3243 MethGet()
3244 MethPost()
3245
3246 Cgi-lib functions that are not available in CGI.pm
3247 * Extended form of ReadParse()
3248 The extended form of ReadParse() that provides for file upload
3249 spooling, is not available.
3250
3251 * MyBaseURL()
3252 This function is not available. Use CGI.pm's url() method instead.
3253
3254 * MyFullURL()
3255 This function is not available. Use CGI.pm's self_url() method
3256 instead.
3257
3258 * CgiError(), CgiDie()
3259 These functions are not supported. Look at CGI::Carp for the way I
3260 prefer to handle error messages.
3261
3262 * PrintVariables()
3263 This function is not available. To achieve the same effect,
3264 just print out the CGI object:
3265
3266 use CGI qw(:standard);
3267 $q = CGI->new;
3268 print h1("The Variables Are"),$q;
3269
3270 * PrintEnv()
3271 This function is not available. You'll have to roll your own if you really need it.
3272
3274 The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is
3275 distributed under GPL and the Artistic License 2.0. It is currently
3276 maintained by Mark Stosberg with help from many contributors.
3277
3278 Address bug reports and comments to:
3279 https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm When sending
3280 bug reports, please provide the version of CGI.pm, the version of Perl,
3281 the name and version of your Web server, and the name and version of
3282 the operating system you are using. If the problem is even remotely
3283 browser dependent, please provide information about the affected
3284 browsers as well.
3285
3287 Thanks very much to:
3288
3289 Matt Heffron (heffron@falstaff.css.beckman.com)
3290 James Taylor (james.taylor@srs.gov)
3291 Scott Anguish <sanguish@digifix.com>
3292 Mike Jewell (mlj3u@virginia.edu)
3293 Timothy Shimmin (tes@kbs.citri.edu.au)
3294 Joergen Haegg (jh@axis.se)
3295 Laurent Delfosse (delfosse@delfosse.com)
3296 Richard Resnick (applepi1@aol.com)
3297 Craig Bishop (csb@barwonwater.vic.gov.au)
3298 Tony Curtis (tc@vcpc.univie.ac.at)
3299 Tim Bunce (Tim.Bunce@ig.co.uk)
3300 Tom Christiansen (tchrist@convex.com)
3301 Andreas Koenig (k@franz.ww.TU-Berlin.DE)
3302 Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
3303 Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
3304 Stephen Dahmen (joyfire@inxpress.net)
3305 Ed Jordan (ed@fidalgo.net)
3306 David Alan Pisoni (david@cnation.com)
3307 Doug MacEachern (dougm@opengroup.org)
3308 Robin Houston (robin@oneworld.org)
3309 ...and many many more...
3310 for suggestions and bug fixes.
3311
3313 #!/usr/local/bin/perl
3314
3315 use CGI ':standard';
3316
3317 print header;
3318 print start_html("Example CGI.pm Form");
3319 print "<h1> Example CGI.pm Form</h1>\n";
3320 print_prompt();
3321 do_work();
3322 print_tail();
3323 print end_html;
3324
3325 sub print_prompt {
3326 print start_form;
3327 print "<em>What's your name?</em><br>";
3328 print textfield('name');
3329 print checkbox('Not my real name');
3330
3331 print "<p><em>Where can you find English Sparrows?</em><br>";
3332 print checkbox_group(
3333 -name=>'Sparrow locations',
3334 -values=>[England,France,Spain,Asia,Hoboken],
3335 -linebreak=>'yes',
3336 -defaults=>[England,Asia]);
3337
3338 print "<p><em>How far can they fly?</em><br>",
3339 radio_group(
3340 -name=>'how far',
3341 -values=>['10 ft','1 mile','10 miles','real far'],
3342 -default=>'1 mile');
3343
3344 print "<p><em>What's your favorite color?</em> ";
3345 print popup_menu(-name=>'Color',
3346 -values=>['black','brown','red','yellow'],
3347 -default=>'red');
3348
3349 print hidden('Reference','Monty Python and the Holy Grail');
3350
3351 print "<p><em>What have you got there?</em><br>";
3352 print scrolling_list(
3353 -name=>'possessions',
3354 -values=>['A Coconut','A Grail','An Icon',
3355 'A Sword','A Ticket'],
3356 -size=>5,
3357 -multiple=>'true');
3358
3359 print "<p><em>Any parting comments?</em><br>";
3360 print textarea(-name=>'Comments',
3361 -rows=>10,
3362 -columns=>50);
3363
3364 print "<p>",reset;
3365 print submit('Action','Shout');
3366 print submit('Action','Scream');
3367 print end_form;
3368 print "<hr>\n";
3369 }
3370
3371 sub do_work {
3372
3373 print "<h2>Here are the current settings in this form</h2>";
3374
3375 for my $key (param) {
3376 print "<strong>$key</strong> -> ";
3377 my @values = param($key);
3378 print join(", ",@values),"<br>\n";
3379 }
3380 }
3381
3382 sub print_tail {
3383 print <<END;
3384 <hr>
3385 <address>Lincoln D. Stein</address><br>
3386 <a href="/">Home Page</a>
3387 END
3388 }
3389
3391 Please report them.
3392
3394 CGI::Carp - provides a Carp implementation tailored to the CGI
3395 environment.
3396
3397 CGI::Fast - supports running CGI applications under FastCGI
3398
3399 CGI::Pretty - pretty prints HTML generated by CGI.pm (with a
3400 performance penalty)
3401
3403 Hey! The above document had some coding errors, which are explained
3404 below:
3405
3406 Around line 5513:
3407 Expected text after =item, not a number
3408
3409 Around line 5517:
3410 Expected text after =item, not a number
3411
3412 Around line 5521:
3413 Expected text after =item, not a number
3414
3415 Around line 6083:
3416 Expected text after =item, not a number
3417
3418 Around line 6087:
3419 Expected text after =item, not a number
3420
3421 Around line 6092:
3422 Expected text after =item, not a number
3423
3424 Around line 6097:
3425 Expected text after =item, not a number
3426
3427 Around line 6166:
3428 Expected text after =item, not a number
3429
3430 Around line 6170:
3431 Expected text after =item, not a number
3432
3433 Around line 6181:
3434 Expected text after =item, not a number
3435
3436 Around line 6186:
3437 Expected text after =item, not a number
3438
3439 Around line 6521:
3440 Expected text after =item, not a number
3441
3442 Around line 6527:
3443 Expected text after =item, not a number
3444
3445 Around line 6536:
3446 Expected text after =item, not a number
3447
3448 Around line 6540:
3449 Expected text after =item, not a number
3450
3451 Around line 6546:
3452 Expected text after =item, not a number
3453
3454 Around line 6552:
3455 Expected text after =item, not a number
3456
3457 Around line 6597:
3458 Expected text after =item, not a number
3459
3460 Around line 6605:
3461 Expected text after =item, not a number
3462
3463 Around line 6612:
3464 Expected text after =item, not a number
3465
3466 Around line 6690:
3467 Expected text after =item, not a number
3468
3469 Around line 6696:
3470 Expected text after =item, not a number
3471
3472 Around line 6701:
3473 Expected text after =item, not a number
3474
3475 Around line 6707:
3476 Expected text after =item, not a number
3477
3478 Around line 6747:
3479 Expected text after =item, not a number
3480
3481 Around line 6751:
3482 Expected text after =item, not a number
3483
3484 Around line 6759:
3485 Expected text after =item, not a number
3486
3487 Around line 6766:
3488 Expected text after =item, not a number
3489
3490 Around line 6771:
3491 Expected text after =item, not a number
3492
3493 Around line 6847:
3494 Expected text after =item, not a number
3495
3496 Around line 6853:
3497 Expected text after =item, not a number
3498
3499 Around line 6859:
3500 Expected text after =item, not a number
3501
3502 Around line 6908:
3503 Expected text after =item, not a number
3504
3505 Around line 6913:
3506 Expected text after =item, not a number
3507
3508 Around line 6951:
3509 Expected text after =item, not a number
3510
3511 Around line 6956:
3512 Expected text after =item, not a number
3513
3514
3515
3516perl v5.16.3 2012-11-14 CGI(3)