1CGI(3pm) Perl Programmers Reference Guide CGI(3pm)
2
3
4
6 CGI - Simple Common Gateway Interface Class
7
9 # CGI script that creates a fill-out form
10 # and echoes back its values.
11
12 use CGI qw/:standard/;
13 print header,
14 start_html('A Simple Example'),
15 h1('A Simple Example'),
16 start_form,
17 "What's your name? ",textfield('name'),p,
18 "What's the combination?", p,
19 checkbox_group(-name=>'words',
20 -values=>['eenie','meenie','minie','moe'],
21 -defaults=>['eenie','minie']), p,
22 "What's your favorite color? ",
23 popup_menu(-name=>'color',
24 -values=>['red','green','blue','chartreuse']),p,
25 submit,
26 end_form,
27 hr;
28
29 if (param()) {
30 my $name = param('name');
31 my $keywords = join ', ',param('words');
32 my $color = param('color');
33 print "Your name is",em(escapeHTML($name)),p,
34 "The keywords are: ",em(escapeHTML($keywords)),p,
35 "Your favorite color is ",em(escapeHTML($color)),
36 hr;
37 }
38
40 This perl library uses perl5 objects to make it easy to create Web
41 fill-out forms and parse their contents. This package defines CGI
42 objects, entities that contain the values of the current query string
43 and other state variables. Using a CGI object's methods, you can exam‐
44 ine keywords and parameters passed to your script, and create forms
45 whose initial values are taken from the current query (thereby preserv‐
46 ing state information). The module provides shortcut functions that
47 produce boilerplate HTML, reducing typing and coding errors. It also
48 provides functionality for some of the more advanced features of CGI
49 scripting, including support for file uploads, cookies, cascading style
50 sheets, server push, and frames.
51
52 CGI.pm also provides a simple function-oriented programming style for
53 those who don't need its object-oriented features.
54
55 The current version of CGI.pm is available at
56
57 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
58 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
59
61 PROGRAMMING STYLE
62
63 There are two styles of programming with CGI.pm, an object-oriented
64 style and a function-oriented style. In the object-oriented style you
65 create one or more CGI objects and then use object methods to create
66 the various elements of the page. Each CGI object starts out with the
67 list of named parameters that were passed to your CGI script by the
68 server. You can modify the objects, save them to a file or database
69 and recreate them. Because each object corresponds to the "state" of
70 the CGI script, and because each object's parameter list is independent
71 of the others, this allows you to save the state of the script and
72 restore it later.
73
74 For example, using the object oriented style, here is how you create a
75 simple "Hello World" HTML page:
76
77 #!/usr/local/bin/perl -w
78 use CGI; # load CGI routines
79 $q = new CGI; # create new CGI object
80 print $q->header, # create the HTTP header
81 $q->start_html('hello world'), # start the HTML
82 $q->h1('hello world'), # level 1 header
83 $q->end_html; # end the HTML
84
85 In the function-oriented style, there is one default CGI object that
86 you rarely deal with directly. Instead you just call functions to
87 retrieve CGI parameters, create HTML tags, manage cookies, and so on.
88 This provides you with a cleaner programming interface, but limits you
89 to using one CGI object at a time. The following example prints the
90 same page, but uses the function-oriented interface. The main differ‐
91 ences are that we now need to import a set of functions into our name
92 space (usually the "standard" functions), and we don't need to create
93 the CGI object.
94
95 #!/usr/local/bin/perl
96 use CGI qw/:standard/; # load standard CGI routines
97 print header, # create the HTTP header
98 start_html('hello world'), # start the HTML
99 h1('hello world'), # level 1 header
100 end_html; # end the HTML
101
102 The examples in this document mainly use the object-oriented style.
103 See HOW TO IMPORT FUNCTIONS for important information on function-ori‐
104 ented programming in CGI.pm
105
106 CALLING CGI.PM ROUTINES
107
108 Most CGI.pm routines accept several arguments, sometimes as many as 20
109 optional ones! To simplify this interface, all routines use a named
110 argument calling style that looks like this:
111
112 print $q->header(-type=>'image/gif',-expires=>'+3d');
113
114 Each argument name is preceded by a dash. Neither case nor order mat‐
115 ters in the argument list. -type, -Type, and -TYPE are all acceptable.
116 In fact, only the first argument needs to begin with a dash. If a dash
117 is present in the first argument, CGI.pm assumes dashes for the subse‐
118 quent ones.
119
120 Several routines are commonly called with just one argument. In the
121 case of these routines you can provide the single argument without an
122 argument name. header() happens to be one of these routines. In this
123 case, the single argument is the document type.
124
125 print $q->header('text/html');
126
127 Other such routines are documented below.
128
129 Sometimes named arguments expect a scalar, sometimes a reference to an
130 array, and sometimes a reference to a hash. Often, you can pass any
131 type of argument and the routine will do whatever is most appropriate.
132 For example, the param() routine is used to set a CGI parameter to a
133 single or a multi-valued value. The two cases are shown below:
134
135 $q->param(-name=>'veggie',-value=>'tomato');
136 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
137
138 A large number of routines in CGI.pm actually aren't specifically
139 defined in the module, but are generated automatically as needed.
140 These are the "HTML shortcuts," routines that generate HTML tags for
141 use in dynamically-generated pages. HTML tags have both attributes
142 (the attribute="value" pairs within the tag itself) and contents (the
143 part between the opening and closing pairs.) To distinguish between
144 attributes and contents, CGI.pm uses the convention of passing HTML
145 attributes as a hash reference as the first argument, and the contents,
146 if any, as any subsequent arguments. It works out like this:
147
148 Code Generated HTML
149 ---- --------------
150 h1() <h1>
151 h1('some','contents'); <h1>some contents</h1>
152 h1({-align=>left}); <h1 align="LEFT">
153 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
154
155 HTML tags are described in more detail later.
156
157 Many newcomers to CGI.pm are puzzled by the difference between the
158 calling conventions for the HTML shortcuts, which require curly braces
159 around the HTML tag attributes, and the calling conventions for other
160 routines, which manage to generate attributes without the curly brack‐
161 ets. Don't be confused. As a convenience the curly braces are
162 optional in all but the HTML shortcuts. If you like, you can use curly
163 braces when calling any routine that takes named arguments. For exam‐
164 ple:
165
166 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
167
168 If you use the -w switch, you will be warned that some CGI.pm argument
169 names conflict with built-in Perl functions. The most frequent of
170 these is the -values argument, used to create multi-valued menus, radio
171 button clusters and the like. To get around this warning, you have
172 several choices:
173
174 1. Use another name for the argument, if one is available. For exam‐
175 ple, -value is an alias for -values.
176
177 2. Change the capitalization, e.g. -Values
178
179 3. Put quotes around the argument name, e.g. '-values'
180
181 Many routines will do something useful with a named argument that it
182 doesn't recognize. For example, you can produce non-standard HTTP
183 header fields by providing them as named arguments:
184
185 print $q->header(-type => 'text/html',
186 -cost => 'Three smackers',
187 -annoyance_level => 'high',
188 -complaints_to => 'bit bucket');
189
190 This will produce the following nonstandard HTTP header:
191
192 HTTP/1.0 200 OK
193 Cost: Three smackers
194 Annoyance-level: high
195 Complaints-to: bit bucket
196 Content-type: text/html
197
198 Notice the way that underscores are translated automatically into
199 hyphens. HTML-generating routines perform a different type of transla‐
200 tion.
201
202 This feature allows you to keep up with the rapidly changing HTTP and
203 HTML "standards".
204
205 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
206
207 $query = new CGI;
208
209 This will parse the input (from both POST and GET methods) and store it
210 into a perl5 object called $query.
211
212 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
213
214 $query = new CGI(INPUTFILE);
215
216 If you provide a file handle to the new() method, it will read parame‐
217 ters from the file (or STDIN, or whatever). The file can be in any of
218 the forms describing below under debugging (i.e. a series of newline
219 delimited TAG=VALUE pairs will work). Conveniently, this type of file
220 is created by the save() method (see below). Multiple records can be
221 saved and restored.
222
223 Perl purists will be pleased to know that this syntax accepts refer‐
224 ences to file handles, or even references to filehandle globs, which is
225 the "official" way to pass a filehandle:
226
227 $query = new CGI(\*STDIN);
228
229 You can also initialize the CGI object with a FileHandle or IO::File
230 object.
231
232 If you are using the function-oriented interface and want to initialize
233 CGI state from a file handle, the way to do this is with restore_param‐
234 eters(). This will (re)initialize the default CGI object from the
235 indicated file handle.
236
237 open (IN,"test.in") ⎪⎪ die;
238 restore_parameters(IN);
239 close IN;
240
241 You can also initialize the query object from an associative array ref‐
242 erence:
243
244 $query = new CGI( {'dinosaur'=>'barney',
245 'song'=>'I love you',
246 'friends'=>[qw/Jessica George Nancy/]}
247 );
248
249 or from a properly formatted, URL-escaped query string:
250
251 $query = new CGI('dinosaur=barney&color=purple');
252
253 or from a previously existing CGI object (currently this clones the
254 parameter list, but none of the other object-specific fields, such as
255 autoescaping):
256
257 $old_query = new CGI;
258 $new_query = new CGI($old_query);
259
260 To create an empty query, initialize it from an empty string or hash:
261
262 $empty_query = new CGI("");
263
264 -or-
265
266 $empty_query = new CGI({});
267
268 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
269
270 @keywords = $query->keywords
271
272 If the script was invoked as the result of an <ISINDEX> search, the
273 parsed keywords can be obtained as an array using the keywords()
274 method.
275
276 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
277
278 @names = $query->param
279
280 If the script was invoked with a parameter list (e.g.
281 "name1=value1&name2=value2&name3=value3"), the param() method will
282 return the parameter names as a list. If the script was invoked as an
283 <ISINDEX> script and contains a string without ampersands (e.g.
284 "value1+value2+value3") , there will be a single parameter named "key‐
285 words" containing the "+"-delimited keywords.
286
287 NOTE: As of version 1.5, the array of parameter names returned will be
288 in the same order as they were submitted by the browser. Usually this
289 order is the same as the order in which the parameters are defined in
290 the form (however, this isn't part of the spec, and so isn't guaran‐
291 teed).
292
293 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
294
295 @values = $query->param('foo');
296
297 -or-
298
299 $value = $query->param('foo');
300
301 Pass the param() method a single argument to fetch the value of the
302 named parameter. If the parameter is multivalued (e.g. from multiple
303 selections in a scrolling list), you can ask to receive an array. Oth‐
304 erwise the method will return a single value.
305
306 If a value is not given in the query string, as in the queries
307 "name1=&name2=" or "name1&name2", it will be returned as an empty
308 string. This feature is new in 2.63.
309
310 If the parameter does not exist at all, then param() will return undef
311 in a scalar context, and the empty list in a list context.
312
313 SETTING THE VALUE(S) OF A NAMED PARAMETER:
314
315 $query->param('foo','an','array','of','values');
316
317 This sets the value for the named parameter 'foo' to an array of val‐
318 ues. This is one way to change the value of a field AFTER the script
319 has been invoked once before. (Another way is with the -override
320 parameter accepted by all methods that generate form elements.)
321
322 param() also recognizes a named parameter style of calling described in
323 more detail later:
324
325 $query->param(-name=>'foo',-values=>['an','array','of','values']);
326
327 -or-
328
329 $query->param(-name=>'foo',-value=>'the value');
330
331 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
332
333 $query->append(-name=>'foo',-values=>['yet','more','values']);
334
335 This adds a value or list of values to the named parameter. The values
336 are appended to the end of the parameter if it already exists. Other‐
337 wise the parameter is created. Note that this method only recognizes
338 the named argument calling syntax.
339
340 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
341
342 $query->import_names('R');
343
344 This creates a series of variables in the 'R' namespace. For example,
345 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will
346 appear. If no namespace is given, this method will assume 'Q'. WARN‐
347 ING: don't import anything into 'main'; this is a major security
348 risk!!!!
349
350 NOTE 1: Variable names are transformed as necessary into legal Perl
351 variable names. All non-legal characters are transformed into under‐
352 scores. If you need to keep the original names, you should use the
353 param() method instead to access CGI variables by name.
354
355 NOTE 2: In older versions, this method was called import(). As of ver‐
356 sion 2.20, this name has been removed completely to avoid conflict with
357 the built-in Perl module import operator.
358
359 DELETING A PARAMETER COMPLETELY:
360
361 $query->delete('foo','bar','baz');
362
363 This completely clears a list of parameters. It sometimes useful for
364 resetting parameters that you don't want passed down between script
365 invocations.
366
367 If you are using the function call interface, use "Delete()" instead to
368 avoid conflicts with Perl's built-in delete operator.
369
370 DELETING ALL PARAMETERS:
371
372 $query->delete_all();
373
374 This clears the CGI object completely. It might be useful to ensure
375 that all the defaults are taken when you create a fill-out form.
376
377 Use Delete_all() instead if you are using the function call interface.
378
379 HANDLING NON-URLENCODED ARGUMENTS
380
381 If POSTed data is not of type application/x-www-form-urlencoded or mul‐
382 tipart/form-data, then the POSTed data will not be processed, but
383 instead be returned as-is in a parameter named POSTDATA. To retrieve
384 it, use code like this:
385
386 my $data = $query->param('POSTDATA');
387
388 (If you don't know what the preceding means, don't worry about it. It
389 only affects people trying to use CGI for XML processing and other spe‐
390 cialized tasks.)
391
392 DIRECT ACCESS TO THE PARAMETER LIST:
393
394 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
395 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
396
397 If you need access to the parameter list in a way that isn't covered by
398 the methods above, you can obtain a direct reference to it by calling
399 the param_fetch() method with the name of the . This will return an
400 array reference to the named parameters, which you then can manipulate
401 in any way you like.
402
403 You can also use a named argument style using the -name argument.
404
405 FETCHING THE PARAMETER LIST AS A HASH:
406
407 $params = $q->Vars;
408 print $params->{'address'};
409 @foo = split("\0",$params->{'foo'});
410 %params = $q->Vars;
411
412 use CGI ':cgi-lib';
413 $params = Vars;
414
415 Many people want to fetch the entire parameter list as a hash in which
416 the keys are the names of the CGI parameters, and the values are the
417 parameters' values. The Vars() method does this. Called in a scalar
418 context, it returns the parameter list as a tied hash reference.
419 Changing a key changes the value of the parameter in the underlying CGI
420 parameter list. Called in a list context, it returns the parameter
421 list as an ordinary hash. This allows you to read the contents of the
422 parameter list, but not to change it.
423
424 When using this, the thing you must watch out for are multivalued CGI
425 parameters. Because a hash cannot distinguish between scalar and list
426 context, multivalued parameters will be returned as a packed string,
427 separated by the "\0" (null) character. You must split this packed
428 string in order to get at the individual values. This is the conven‐
429 tion introduced long ago by Steve Brenner in his cgi-lib.pl module for
430 Perl version 4.
431
432 If you wish to use Vars() as a function, import the :cgi-lib set of
433 function calls (also see the section on CGI-LIB compatibility).
434
435 SAVING THE STATE OF THE SCRIPT TO A FILE:
436
437 $query->save(\*FILEHANDLE)
438
439 This will write the current state of the form to the provided filehan‐
440 dle. You can read it back in by providing a filehandle to the new()
441 method. Note that the filehandle can be a file, a pipe, or whatever!
442
443 The format of the saved file is:
444
445 NAME1=VALUE1
446 NAME1=VALUE1'
447 NAME2=VALUE2
448 NAME3=VALUE3
449 =
450
451 Both name and value are URL escaped. Multi-valued CGI parameters are
452 represented as repeated names. A session record is delimited by a sin‐
453 gle = symbol. You can write out multiple records and read them back in
454 with several calls to new. You can do this across several sessions by
455 opening the file in append mode, allowing you to create primitive guest
456 books, or to keep a history of users' queries. Here's a short example
457 of creating multiple session records:
458
459 use CGI;
460
461 open (OUT,">>test.out") ⎪⎪ die;
462 $records = 5;
463 foreach (0..$records) {
464 my $q = new CGI;
465 $q->param(-name=>'counter',-value=>$_);
466 $q->save(\*OUT);
467 }
468 close OUT;
469
470 # reopen for reading
471 open (IN,"test.out") ⎪⎪ die;
472 while (!eof(IN)) {
473 my $q = new CGI(\*IN);
474 print $q->param('counter'),"\n";
475 }
476
477 The file format used for save/restore is identical to that used by the
478 Whitehead Genome Center's data exchange format "Boulderio", and can be
479 manipulated and even databased using Boulderio utilities. See
480
481 http://stein.cshl.org/boulder/
482
483 for further details.
484
485 If you wish to use this method from the function-oriented (non-OO)
486 interface, the exported name for this method is save_parameters().
487
488 RETRIEVING CGI ERRORS
489
490 Errors can occur while processing user input, particularly when pro‐
491 cessing uploaded files. When these errors occur, CGI will stop pro‐
492 cessing and return an empty parameter list. You can test for the exis‐
493 tence and nature of errors using the cgi_error() function. The error
494 messages are formatted as HTTP status codes. You can either incorporate
495 the error text into an HTML page, or use it as the value of the HTTP
496 status:
497
498 my $error = $q->cgi_error;
499 if ($error) {
500 print $q->header(-status=>$error),
501 $q->start_html('Problems'),
502 $q->h2('Request not processed'),
503 $q->strong($error);
504 exit 0;
505 }
506
507 When using the function-oriented interface (see the next section),
508 errors may only occur the first time you call param(). Be ready for
509 this!
510
511 USING THE FUNCTION-ORIENTED INTERFACE
512
513 To use the function-oriented interface, you must specify which CGI.pm
514 routines or sets of routines to import into your script's namespace.
515 There is a small overhead associated with this importation, but it
516 isn't much.
517
518 use CGI <list of methods>;
519
520 The listed methods will be imported into the current package; you can
521 call them directly without creating a CGI object first. This example
522 shows how to import the param() and header() methods, and then use them
523 directly:
524
525 use CGI 'param','header';
526 print header('text/plain');
527 $zipcode = param('zipcode');
528
529 More frequently, you'll import common sets of functions by referring to
530 the groups by name. All function sets are preceded with a ":" charac‐
531 ter as in ":html3" (for tags defined in the HTML 3 standard).
532
533 Here is a list of the function sets you can import:
534
535 :cgi
536 Import all CGI-handling methods, such as param(), path_info() and
537 the like.
538
539 :form
540 Import all fill-out form generating methods, such as textfield().
541
542 :html2
543 Import all methods that generate HTML 2.0 standard elements.
544
545 :html3
546 Import all methods that generate HTML 3.0 elements (such as <ta‐
547 ble>, <super> and <sub>).
548
549 :html4
550 Import all methods that generate HTML 4 elements (such as <abbrev>,
551 <acronym> and <thead>).
552
553 :netscape
554 Import all methods that generate Netscape-specific HTML extensions.
555
556 :html
557 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
558 'netscape')...
559
560 :standard
561 Import "standard" features, 'html2', 'html3', 'html4', 'form' and
562 'cgi'.
563
564 :all
565 Import all the available methods. For the full list, see the
566 CGI.pm code, where the variable %EXPORT_TAGS is defined.
567
568 If you import a function name that is not part of CGI.pm, the module
569 will treat it as a new HTML tag and generate the appropriate subrou‐
570 tine. You can then use it like any other HTML tag. This is to provide
571 for the rapidly-evolving HTML "standard." For example, say Microsoft
572 comes out with a new tag called <gradient> (which causes the user's
573 desktop to be flooded with a rotating gradient fill until his machine
574 reboots). You don't need to wait for a new version of CGI.pm to start
575 using it immediately:
576
577 use CGI qw/:standard :html3 gradient/;
578 print gradient({-start=>'red',-end=>'blue'});
579
580 Note that in the interests of execution speed CGI.pm does not use the
581 standard Exporter syntax for specifying load symbols. This may change
582 in the future.
583
584 If you import any of the state-maintaining CGI or form-generating meth‐
585 ods, a default CGI object will be created and initialized automatically
586 the first time you use any of the methods that require one to be
587 present. This includes param(), textfield(), submit() and the like.
588 (If you need direct access to the CGI object, you can find it in the
589 global variable $CGI::Q). By importing CGI.pm methods, you can create
590 visually elegant scripts:
591
592 use CGI qw/:standard/;
593 print
594 header,
595 start_html('Simple Script'),
596 h1('Simple Script'),
597 start_form,
598 "What's your name? ",textfield('name'),p,
599 "What's the combination?",
600 checkbox_group(-name=>'words',
601 -values=>['eenie','meenie','minie','moe'],
602 -defaults=>['eenie','moe']),p,
603 "What's your favorite color?",
604 popup_menu(-name=>'color',
605 -values=>['red','green','blue','chartreuse']),p,
606 submit,
607 end_form,
608 hr,"\n";
609
610 if (param) {
611 print
612 "Your name is ",em(param('name')),p,
613 "The keywords are: ",em(join(", ",param('words'))),p,
614 "Your favorite color is ",em(param('color')),".\n";
615 }
616 print end_html;
617
618 PRAGMAS
619
620 In addition to the function sets, there are a number of pragmas that
621 you can import. Pragmas, which are always preceded by a hyphen, change
622 the way that CGI.pm functions in various ways. Pragmas, function sets,
623 and individual functions can all be imported in the same use() line.
624 For example, the following use statement imports the standard set of
625 functions and enables debugging mode (pragma -debug):
626
627 use CGI qw/:standard -debug/;
628
629 The current list of pragmas is as follows:
630
631 -any
632 When you use CGI -any, then any method that the query object
633 doesn't recognize will be interpreted as a new HTML tag. This
634 allows you to support the next ad hoc Netscape or Microsoft HTML
635 extension. This lets you go wild with new and unsupported tags:
636
637 use CGI qw(-any);
638 $q=new CGI;
639 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
640
641 Since using <cite>any</cite> causes any mistyped method name to be
642 interpreted as an HTML tag, use it with care or not at all.
643
644 -compile
645 This causes the indicated autoloaded methods to be compiled up
646 front, rather than deferred to later. This is useful for scripts
647 that run for an extended period of time under FastCGI or mod_perl,
648 and for those destined to be crunched by Malcom Beattie's Perl com‐
649 piler. Use it in conjunction with the methods or method families
650 you plan to use.
651
652 use CGI qw(-compile :standard :html3);
653
654 or even
655
656 use CGI qw(-compile :all);
657
658 Note that using the -compile pragma in this way will always have
659 the effect of importing the compiled functions into the current
660 namespace. If you want to compile without importing use the com‐
661 pile() method instead:
662
663 use CGI();
664 CGI->compile();
665
666 This is particularly useful in a mod_perl environment, in which you
667 might want to precompile all CGI routines in a startup script, and
668 then import the functions individually in each mod_perl script.
669
670 -nosticky
671 By default the CGI module implements a state-preserving behavior
672 called "sticky" fields. The way this works is that if you are
673 regenerating a form, the methods that generate the form field val‐
674 ues will interrogate param() to see if similarly-named parameters
675 are present in the query string. If they find a like-named parame‐
676 ter, they will use it to set their default values.
677
678 Sometimes this isn't what you want. The -nosticky pragma prevents
679 this behavior. You can also selectively change the sticky behavior
680 in each element that you generate.
681
682 -tabindex
683 Automatically add tab index attributes to each form field. With
684 this option turned off, you can still add tab indexes manually by
685 passing a -tabindex option to each field-generating method.
686
687 -no_undef_params
688 This keeps CGI.pm from including undef params in the parameter
689 list.
690
691 -no_xhtml
692 By default, CGI.pm versions 2.69 and higher emit XHTML
693 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
694 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for
695 this feature.
696
697 If start_html()'s -dtd parameter specifies an HTML 2.0 or 3.2 DTD,
698 XHTML will automatically be disabled without needing to use this
699 pragma.
700
701 -nph
702 This makes CGI.pm produce a header appropriate for an NPH (no
703 parsed header) script. You may need to do other things as well to
704 tell the server that the script is NPH. See the discussion of NPH
705 scripts below.
706
707 -newstyle_urls
708 Separate the name=value pairs in CGI parameter query strings with
709 semicolons rather than ampersands. For example:
710
711 ?name=fred;age=24;favorite_color=3
712
713 Semicolon-delimited query strings are always accepted, but will not
714 be emitted by self_url() and query_string() unless the -new‐
715 style_urls pragma is specified.
716
717 This became the default in version 2.64.
718
719 -oldstyle_urls
720 Separate the name=value pairs in CGI parameter query strings with
721 ampersands rather than semicolons. This is no longer the default.
722
723 -autoload
724 This overrides the autoloader so that any function in your program
725 that is not recognized is referred to CGI.pm for possible evalua‐
726 tion. This allows you to use all the CGI.pm functions without
727 adding them to your symbol table, which is of concern for mod_perl
728 users who are worried about memory consumption. Warning: when
729 -autoload is in effect, you cannot use "poetry mode" (functions
730 without the parenthesis). Use hr() rather than hr, or add some‐
731 thing like use subs qw/hr p header/ to the top of your script.
732
733 -no_debug
734 This turns off the command-line processing features. If you want
735 to run a CGI.pm script from the command line to produce HTML, and
736 you don't want it to read CGI parameters from the command line or
737 STDIN, then use this pragma:
738
739 use CGI qw(-no_debug :standard);
740
741 -debug
742 This turns on full debugging. In addition to reading CGI arguments
743 from the command-line processing, CGI.pm will pause and try to read
744 arguments from STDIN, producing the message "(offline mode: enter
745 name=value pairs on standard input)" features.
746
747 See the section on debugging for more details.
748
749 -private_tempfiles
750 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
751 file to a temporary directory, then deletes the file when done.
752 However, this opens the risk of eavesdropping as described in the
753 file upload section. Another CGI script author could peek at this
754 data during the upload, even if it is confidential information. On
755 Unix systems, the -private_tempfiles pragma will cause the tempo‐
756 rary file to be unlinked as soon as it is opened and before any
757 data is written into it, reducing, but not eliminating the risk of
758 eavesdropping (there is still a potential race condition). To make
759 life harder for the attacker, the program chooses tempfile names by
760 calculating a 32 bit checksum of the incoming HTTP headers.
761
762 To ensure that the temporary file cannot be read by other CGI
763 scripts, use suEXEC or a CGI wrapper program to run your script.
764 The temporary file is created with mode 0600 (neither world nor
765 group readable).
766
767 The temporary directory is selected using the following algorithm:
768
769 1. if the current user (e.g. "nobody") has a directory named
770 "tmp" in its home directory, use that (Unix systems only).
771
772 2. if the environment variable TMPDIR exists, use the location
773 indicated.
774
775 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
776 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
777
778 Each of these locations is checked that it is a directory and is
779 writable. If not, the algorithm tries the next choice.
780
781 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
782
783 Many of the methods generate HTML tags. As described below, tag func‐
784 tions automatically generate both the opening and closing tags. For
785 example:
786
787 print h1('Level 1 Header');
788
789 produces
790
791 <h1>Level 1 Header</h1>
792
793 There will be some times when you want to produce the start and end
794 tags yourself. In this case, you can use the form start_tag_name and
795 end_tag_name, as in:
796
797 print start_h1,'Level 1 Header',end_h1;
798
799 With a few exceptions (described below), start_tag_name and
800 end_tag_name functions are not generated automatically when you use
801 CGI. However, you can specify the tags you want to generate start/end
802 functions for by putting an asterisk in front of their name, or, alter‐
803 natively, requesting either "start_tag_name" or "end_tag_name" in the
804 import list.
805
806 Example:
807
808 use CGI qw/:standard *table start_ul/;
809
810 In this example, the following functions are generated in addition to
811 the standard ones:
812
813 1. start_table() (generates a <table> tag)
814 2. end_table() (generates a </table> tag)
815 3. start_ul() (generates a <ul> tag)
816 4. end_ul() (generates a </ul> tag)
817
819 Most of CGI.pm's functions deal with creating documents on the fly.
820 Generally you will produce the HTTP header first, followed by the docu‐
821 ment itself. CGI.pm provides functions for generating HTTP headers of
822 various types as well as for generating HTML. For creating GIF images,
823 see the GD.pm module.
824
825 Each of these functions produces a fragment of HTML or HTTP which you
826 can print out directly so that it displays in the browser window,
827 append to a string, or save to a file for later use.
828
829 CREATING A STANDARD HTTP HEADER:
830
831 Normally the first thing you will do in any CGI script is print out an
832 HTTP header. This tells the browser what type of document to expect,
833 and gives other optional information, such as the language, expiration
834 date, and whether to cache the document. The header can also be manip‐
835 ulated for special purposes, such as server push and pay per view
836 pages.
837
838 print header;
839
840 -or-
841
842 print header('image/gif');
843
844 -or-
845
846 print header('text/html','204 No response');
847
848 -or-
849
850 print header(-type=>'image/gif',
851 -nph=>1,
852 -status=>'402 Payment required',
853 -expires=>'+3d',
854 -cookie=>$cookie,
855 -charset=>'utf-7',
856 -attachment=>'foo.gif',
857 -Cost=>'$2.00');
858
859 header() returns the Content-type: header. You can provide your own
860 MIME type if you choose, otherwise it defaults to text/html. An
861 optional second parameter specifies the status code and a human-read‐
862 able message. For example, you can specify 204, "No response" to cre‐
863 ate a script that tells the browser to do nothing at all.
864
865 The last example shows the named argument style for passing arguments
866 to the CGI methods using named parameters. Recognized parameters are
867 -type, -status, -expires, and -cookie. Any other named parameters will
868 be stripped of their initial hyphens and turned into header fields,
869 allowing you to specify any HTTP header you desire. Internal under‐
870 scores will be turned into hyphens:
871
872 print header(-Content_length=>3002);
873
874 Most browsers will not cache the output from CGI scripts. Every time
875 the browser reloads the page, the script is invoked anew. You can
876 change this behavior with the -expires parameter. When you specify an
877 absolute or relative expiration interval with this parameter, some
878 browsers and proxy servers will cache the script's output until the
879 indicated expiration date. The following forms are all valid for the
880 -expires field:
881
882 +30s 30 seconds from now
883 +10m ten minutes from now
884 +1h one hour from now
885 -1d yesterday (i.e. "ASAP!")
886 now immediately
887 +3M in three months
888 +10y in ten years time
889 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
890
891 The -cookie parameter generates a header that tells the browser to pro‐
892 vide a "magic cookie" during all subsequent transactions with your
893 script. Netscape cookies have a special format that includes interest‐
894 ing attributes such as expiration time. Use the cookie() method to
895 create and retrieve session cookies.
896
897 The -nph parameter, if set to a true value, will issue the correct
898 headers to work with a NPH (no-parse-header) script. This is important
899 to use with certain servers that expect all their scripts to be NPH.
900
901 The -charset parameter can be used to control the character set sent to
902 the browser. If not provided, defaults to ISO-8859-1. As a side
903 effect, this sets the charset() method as well.
904
905 The -attachment parameter can be used to turn the page into an attach‐
906 ment. Instead of displaying the page, some browsers will prompt the
907 user to save it to disk. The value of the argument is the suggested
908 name for the saved file. In order for this to work, you may have to
909 set the -type to "application/octet-stream".
910
911 The -p3p parameter will add a P3P tag to the outgoing header. The
912 parameter can be an arrayref or a space-delimited string of P3P tags.
913 For example:
914
915 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
916 print header(-p3p=>'CAO DSP LAW CURa');
917
918 In either case, the outgoing header will be formatted as:
919
920 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
921
922 GENERATING A REDIRECTION HEADER
923
924 print redirect('http://somewhere.else/in/movie/land');
925
926 Sometimes you don't want to produce a document yourself, but simply re‐
927 direct the browser elsewhere, perhaps choosing a URL based on the time
928 of day or the identity of the user.
929
930 The redirect() function redirects the browser to a different URL. If
931 you use redirection like this, you should not print out a header as
932 well.
933
934 You should always use full URLs (including the http: or ftp: part) in
935 redirection requests. Relative URLs will not work correctly.
936
937 You can also use named arguments:
938
939 print redirect(-uri=>'http://somewhere.else/in/movie/land',
940 -nph=>1,
941 -status=>301);
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 CREATING THE HTML DOCUMENT HEADER
961
962 print start_html(-title=>'Secrets of the Pyramids',
963 -author=>'fred@capricorn.org',
964 -base=>'true',
965 -target=>'_blank',
966 -meta=>{'keywords'=>'pharaoh secret mummy',
967 'copyright'=>'copyright 1996 King Tut'},
968 -style=>{'src'=>'/styles/style1.css'},
969 -BGCOLOR=>'blue');
970
971 After creating the HTTP header, most CGI scripts will start writing out
972 an HTML document. The start_html() routine creates the top of the
973 page, along with a lot of optional information that controls the page's
974 appearance and behavior.
975
976 This method returns a canned HTML header and the opening <body> tag.
977 All parameters are optional. In the named parameter form, recognized
978 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
979 (see below for the explanation). Any additional parameters you pro‐
980 vide, such as the Netscape unofficial BGCOLOR attribute, are added to
981 the <body> tag. Additional parameters must be proceeded by a hyphen.
982
983 The argument -xbase allows you to provide an HREF for the <base> tag
984 different from the current location, as in
985
986 -xbase=>"http://home.mcom.com/"
987
988 All relative links will be interpreted relative to this tag.
989
990 The argument -target allows you to provide a default target frame for
991 all the links and fill-out forms on the page. This is a non-standard
992 HTTP feature which only works with Netscape browsers! See the Netscape
993 documentation on frames for details of how to manipulate this.
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 an associative array containing
1000 name/value pairs of meta information. These will be turned into a
1001 series of header <meta> 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 informa‐
1010 tion.
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 -declare_xml argument, when used in conjunction with XHTML, will
1026 put a <?xml> declaration at the top of the HTML header. The sole pur‐
1027 pose of this declaration is to declare the character set encoding. In
1028 the absence of -declare_xml, the output HTML will contain a <meta> tag
1029 that specifies the encoding, allowing the HTML to pass most validators.
1030 The default for -declare_xml is false.
1031
1032 You can place other arbitrary HTML elements to the <head> section with
1033 the -head tag. For example, to place the rarely-used <link> element in
1034 the head section, use this:
1035
1036 print start_html(-head=>Link({-rel=>'next',
1037 -href=>'http://www.capricorn.com/s2.html'}));
1038
1039 To incorporate multiple HTML elements into the <head> section, just
1040 pass an array reference:
1041
1042 print start_html(-head=>[
1043 Link({-rel=>'next',
1044 -href=>'http://www.capricorn.com/s2.html'}),
1045 Link({-rel=>'previous',
1046 -href=>'http://www.capricorn.com/s1.html'})
1047 ]
1048 );
1049
1050 And here's how to create an HTTP-EQUIV <meta> tag:
1051
1052 print start_html(-head=>meta({-http_equiv => 'Content-Type',
1053 -content => 'text/html'}))
1054
1055 JAVASCRIPTING: The -script, -noScript, -onLoad, -onMouseOver, -onMouse‐
1056 Out and -onUnload parameters are used to add Netscape JavaScript calls
1057 to your pages. -script should point to a block of text containing
1058 JavaScript function definitions. This block will be placed within a
1059 <script> block inside the HTML (not HTTP) header. The block is placed
1060 in the header in order to give your page a fighting chance of having
1061 all its JavaScript functions in place even if the user presses the stop
1062 button before the page has loaded completely. CGI.pm attempts to for‐
1063 mat the script in such a way that JavaScript-naive browsers will not
1064 choke on the code: unfortunately there are some browsers, such as
1065 Chimera for Unix, that get confused by it nevertheless.
1066
1067 The -onLoad and -onUnload parameters point to fragments of JavaScript
1068 code to execute when the page is respectively opened and closed by the
1069 browser. Usually these parameters are calls to functions defined in
1070 the -script field:
1071
1072 $query = new CGI;
1073 print header;
1074 $JSCRIPT=<<END;
1075 // Ask a silly question
1076 function riddle_me_this() {
1077 var r = prompt("What walks on four legs in the morning, " +
1078 "two legs in the afternoon, " +
1079 "and three legs in the evening?");
1080 response(r);
1081 }
1082 // Get a silly answer
1083 function response(answer) {
1084 if (answer == "man")
1085 alert("Right you are!");
1086 else
1087 alert("Wrong! Guess again.");
1088 }
1089 END
1090 print start_html(-title=>'The Riddle of the Sphinx',
1091 -script=>$JSCRIPT);
1092
1093 Use the -noScript parameter to pass some HTML text that will be dis‐
1094 played on browsers that do not have JavaScript (or browsers where
1095 JavaScript is turned off).
1096
1097 Netscape 3.0 recognizes several attributes of the <script> tag, includ‐
1098 ing LANGUAGE and SRC. The latter is particularly interesting, as it
1099 allows you to keep the JavaScript code in a file or CGI script rather
1100 than cluttering up each page with the source. To use these attributes
1101 pass a HASH reference in the -script parameter containing one or more
1102 of -language, -src, or -code:
1103
1104 print $q->start_html(-title=>'The Riddle of the Sphinx',
1105 -script=>{-language=>'JAVASCRIPT',
1106 -src=>'/javascript/sphinx.js'}
1107 );
1108
1109 print $q->(-title=>'The Riddle of the Sphinx',
1110 -script=>{-language=>'PERLSCRIPT',
1111 -code=>'print "hello world!\n;"'}
1112 );
1113
1114 A final feature allows you to incorporate multiple <script> sections
1115 into the header. Just pass the list of script sections as an array
1116 reference. this allows you to specify different source files for dif‐
1117 ferent dialects of JavaScript. Example:
1118
1119 print $q->start_html(-title=>'The Riddle of the Sphinx',
1120 -script=>[
1121 { -language => 'JavaScript1.0',
1122 -src => '/javascript/utilities10.js'
1123 },
1124 { -language => 'JavaScript1.1',
1125 -src => '/javascript/utilities11.js'
1126 },
1127 { -language => 'JavaScript1.2',
1128 -src => '/javascript/utilities12.js'
1129 },
1130 { -language => 'JavaScript28.2',
1131 -src => '/javascript/utilities219.js'
1132 }
1133 ]
1134 );
1135
1136 If this looks a bit extreme, take my advice and stick with straight CGI
1137 scripting.
1138
1139 See
1140
1141 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
1142
1143 for more information about JavaScript.
1144
1145 The old-style positional parameters are as follows:
1146
1147 Parameters:
1148 1. The title
1149
1150 2. The author's e-mail address (will create a <link rev="MADE"> tag if
1151 present
1152
1153 3. A 'true' flag if you want to include a <base> tag in the header.
1154 This helps resolve relative addresses to absolute ones when the
1155 document is moved, but makes the document hierarchy non-portable.
1156 Use with care!
1157
1158 4, 5, 6...
1159 Any other parameters you want to include in the <body> tag. This
1160 is a good place to put Netscape extensions, such as colors and
1161 wallpaper patterns.
1162
1163 ENDING THE HTML DOCUMENT:
1164
1165 print end_html
1166
1167 This ends an HTML document by printing the </body></html> tags.
1168
1169 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
1170
1171 $myself = self_url;
1172 print q(<a href="$myself">I'm talking to myself.</a>);
1173
1174 self_url() will return a URL, that, when selected, will reinvoke this
1175 script with all its state information intact. This is most useful when
1176 you want to jump around within the document using internal anchors but
1177 you don't want to disrupt the current contents of the form(s). Some‐
1178 thing like this will do the trick.
1179
1180 $myself = self_url;
1181 print "<a href=\"$myself#table1\">See table 1</a>";
1182 print "<a href=\"$myself#table2\">See table 2</a>";
1183 print "<a href=\"$myself#yourself\">See for yourself</a>";
1184
1185 If you want more control over what's returned, using the url() method
1186 instead.
1187
1188 You can also retrieve the unprocessed query string with query_string():
1189
1190 $the_string = query_string;
1191
1192 OBTAINING THE SCRIPT'S URL
1193
1194 $full_url = url();
1195 $full_url = url(-full=>1); #alternative syntax
1196 $relative_url = url(-relative=>1);
1197 $absolute_url = url(-absolute=>1);
1198 $url_with_path = url(-path_info=>1);
1199 $url_with_path_and_query = url(-path_info=>1,-query=>1);
1200 $netloc = url(-base => 1);
1201
1202 url() returns the script's URL in a variety of formats. Called without
1203 any arguments, it returns the full form of the URL, including host name
1204 and port number
1205
1206 http://your.host.com/path/to/script.cgi
1207
1208 You can modify this format with the following named arguments:
1209
1210 -absolute
1211 If true, produce an absolute URL, e.g.
1212
1213 /path/to/script.cgi
1214
1215 -relative
1216 Produce a relative URL. This is useful if you want to reinvoke
1217 your script with different parameters. For example:
1218
1219 script.cgi
1220
1221 -full
1222 Produce the full URL, exactly as if called without any arguments.
1223 This overrides the -relative and -absolute arguments.
1224
1225 -path (-path_info)
1226 Append the additional path information to the URL. This can be
1227 combined with -full, -absolute or -relative. -path_info is pro‐
1228 vided as a synonym.
1229
1230 -query (-query_string)
1231 Append the query string to the URL. This can be combined with
1232 -full, -absolute or -relative. -query_string is provided as a syn‐
1233 onym.
1234
1235 -base
1236 Generate just the protocol and net location, as in
1237 http://www.foo.com:8000
1238
1239 -rewrite
1240 If Apache's mod_rewrite is turned on, then the script name and path
1241 info probably won't match the request that the user sent. Set -re‐
1242 write=>1 (default) to return URLs that match what the user sent
1243 (the original request URI). Set -rewrite->0 to return URLs that
1244 match the URL after mod_rewrite's rules have run. Because the addi‐
1245 tional path information only makes sense in the context of the
1246 rewritten URL, -rewrite is set to false when you request path info
1247 in the URL.
1248
1249 MIXING POST AND URL PARAMETERS
1250
1251 $color = url_param('color');
1252
1253 It is possible for a script to receive CGI parameters in the URL as
1254 well as in the fill-out form by creating a form that POSTs to a URL
1255 containing a query string (a "?" mark followed by arguments). The
1256 param() method will always return the contents of the POSTed fill-out
1257 form, ignoring the URL's query string. To retrieve URL parameters,
1258 call the url_param() method. Use it in the same way as param(). The
1259 main difference is that it allows you to read the parameters, but not
1260 set them.
1261
1262 Under no circumstances will the contents of the URL query string inter‐
1263 fere with similarly-named CGI parameters in POSTed forms. If you try
1264 to mix a URL query string with a form submitted with the GET method,
1265 the results will not be what you expect.
1266
1268 CGI.pm defines general HTML shortcut methods for most, if not all of
1269 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
1270 HTML element and return a fragment of HTML text that you can then print
1271 or manipulate as you like. Each shortcut returns a fragment of HTML
1272 code that you can append to a string, save to a file, or, most com‐
1273 monly, print out so that it displays in the browser window.
1274
1275 This example shows how to use the HTML methods:
1276
1277 print $q->blockquote(
1278 "Many years ago on the island of",
1279 $q->a({href=>"http://crete.org/"},"Crete"),
1280 "there lived a Minotaur named",
1281 $q->strong("Fred."),
1282 ),
1283 $q->hr;
1284
1285 This results in the following HTML code (extra newlines have been added
1286 for readability):
1287
1288 <blockquote>
1289 Many years ago on the island of
1290 <a href="http://crete.org/">Crete</a> there lived
1291 a minotaur named <strong>Fred.</strong>
1292 </blockquote>
1293 <hr>
1294
1295 If you find the syntax for calling the HTML shortcuts awkward, you can
1296 import them into your namespace and dispense with the object syntax
1297 completely (see the next section for more details):
1298
1299 use CGI ':standard';
1300 print blockquote(
1301 "Many years ago on the island of",
1302 a({href=>"http://crete.org/"},"Crete"),
1303 "there lived a minotaur named",
1304 strong("Fred."),
1305 ),
1306 hr;
1307
1308 PROVIDING ARGUMENTS TO HTML SHORTCUTS
1309
1310 The HTML methods will accept zero, one or multiple arguments. If you
1311 provide no arguments, you get a single tag:
1312
1313 print hr; # <hr>
1314
1315 If you provide one or more string arguments, they are concatenated
1316 together with spaces and placed between opening and closing tags:
1317
1318 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
1319
1320 If the first argument is an associative array reference, then the keys
1321 and values of the associative array become the HTML tag's attributes:
1322
1323 print a({-href=>'fred.html',-target=>'_new'},
1324 "Open a new frame");
1325
1326 <a href="fred.html",target="_new">Open a new frame</a>
1327
1328 You may dispense with the dashes in front of the attribute names if you
1329 prefer:
1330
1331 print img {src=>'fred.gif',align=>'LEFT'};
1332
1333 <img align="LEFT" src="fred.gif">
1334
1335 Sometimes an HTML tag attribute has no argument. For example, ordered
1336 lists can be marked as COMPACT. The syntax for this is an argument
1337 that that points to an undef string:
1338
1339 print ol({compact=>undef},li('one'),li('two'),li('three'));
1340
1341 Prior to CGI.pm version 2.41, providing an empty ('') string as an
1342 attribute argument was the same as providing undef. However, this has
1343 changed in order to accommodate those who want to create tags of the
1344 form <img alt="">. The difference is shown in these two pieces of
1345 code:
1346
1347 CODE RESULT
1348 img({alt=>undef}) <img alt>
1349 img({alt=>''}) <img alt="">
1350
1351 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
1352
1353 One of the cool features of the HTML shortcuts is that they are dis‐
1354 tributive. If you give them an argument consisting of a reference to a
1355 list, the tag will be distributed across each element of the list. For
1356 example, here's one way to make an ordered list:
1357
1358 print ul(
1359 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
1360 );
1361
1362 This example will result in HTML output that looks like this:
1363
1364 <ul>
1365 <li type="disc">Sneezy</li>
1366 <li type="disc">Doc</li>
1367 <li type="disc">Sleepy</li>
1368 <li type="disc">Happy</li>
1369 </ul>
1370
1371 This is extremely useful for creating tables. For example:
1372
1373 print table({-border=>undef},
1374 caption('When Should You Eat Your Vegetables?'),
1375 Tr({-align=>CENTER,-valign=>TOP},
1376 [
1377 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
1378 td(['Tomatoes' , 'no', 'yes', 'yes']),
1379 td(['Broccoli' , 'no', 'no', 'yes']),
1380 td(['Onions' , 'yes','yes', 'yes'])
1381 ]
1382 )
1383 );
1384
1385 HTML SHORTCUTS AND LIST INTERPOLATION
1386
1387 Consider this bit of code:
1388
1389 print blockquote(em('Hi'),'mom!'));
1390
1391 It will ordinarily return the string that you probably expect, namely:
1392
1393 <blockquote><em>Hi</em> mom!</blockquote>
1394
1395 Note the space between the element "Hi" and the element "mom!". CGI.pm
1396 puts the extra space there using array interpolation, which is con‐
1397 trolled by the magic $" variable. Sometimes this extra space is not
1398 what you want, for example, when you are trying to align a series of
1399 images. In this case, you can simply change the value of $" to an
1400 empty string.
1401
1402 {
1403 local($") = '';
1404 print blockquote(em('Hi'),'mom!'));
1405 }
1406
1407 I suggest you put the code in a block as shown here. Otherwise the
1408 change to $" will affect all subsequent code until you explicitly reset
1409 it.
1410
1411 NON-STANDARD HTML SHORTCUTS
1412
1413 A few HTML tags don't follow the standard pattern for various reasons.
1414
1415 comment() generates an HTML comment (<!-- comment -->). Call it like
1416
1417 print comment('here is my comment');
1418
1419 Because of conflicts with built-in Perl functions, the following func‐
1420 tions begin with initial caps:
1421
1422 Select
1423 Tr
1424 Link
1425 Delete
1426 Accept
1427 Sub
1428
1429 In addition, start_html(), end_html(), start_form(), end_form(),
1430 start_multipart_form() and all the fill-out form tags are special. See
1431 their respective sections.
1432
1433 AUTOESCAPING HTML
1434
1435 By default, all HTML that is emitted by the form-generating functions
1436 is passed through a function called escapeHTML():
1437
1438 $escaped_string = escapeHTML("unescaped string");
1439 Escape HTML formatting characters in a string.
1440
1441 Provided that you have specified a character set of ISO-8859-1 (the
1442 default), the standard HTML escaping rules will be used. The "<" char‐
1443 acter becomes "<", ">" becomes ">", "&" becomes "&", and the
1444 quote character becomes """. In addition, the hexadecimal 0x8b
1445 and 0x9b characters, which some browsers incorrectly interpret as the
1446 left and right angle-bracket characters, are replaced by their numeric
1447 character entities ("‹" and "›"). If you manually change
1448 the charset, either by calling the charset() method explicitly or by
1449 passing a -charset argument to header(), then all characters will be
1450 replaced by their numeric entities, since CGI.pm has no lookup table
1451 for all the possible encodings.
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
1467 By default, all the HTML produced by these functions comes out as one
1468 long line without carriage returns or indentation. This is yuck, but it
1469 does reduce the size of the documents by 10-20%. To get pretty-printed
1470 output, please use CGI::Pretty, a subclass contributed by Brian
1471 Paulsen.
1472
1474 General note The various form-creating methods all return strings to
1475 the caller, containing the tag or tags that will create the requested
1476 form element. You are responsible for actually printing out these
1477 strings. It's set up this way so that you can place formatting tags
1478 around the form elements.
1479
1480 Another note The default values that you specify for the forms are only
1481 used the first time the script is invoked (when there is no query
1482 string). On subsequent invocations of the script (when there is a
1483 query string), the former values are used even if they are blank.
1484
1485 If you want to change the value of a field from its previous value, you
1486 have two choices:
1487
1488 (1) call the param() method to set it.
1489
1490 (2) use the -override (alias -force) parameter (a new feature in ver‐
1491 sion 2.15). This forces the default value to be used, regardless of
1492 the previous value:
1493
1494 print textfield(-name=>'field_name',
1495 -default=>'starting value',
1496 -override=>1,
1497 -size=>50,
1498 -maxlength=>80);
1499
1500 Yet another note By default, the text and labels of form elements are
1501 escaped according to HTML rules. This means that you can safely use
1502 "<CLICK ME>" as the label for a button. However, it also interferes
1503 with your ability to incorporate special HTML character sequences, such
1504 as Á, into your fields. If you wish to turn off automatic
1505 escaping, call the autoEscape() method with a false value immediately
1506 after creating the CGI object:
1507
1508 $query = new CGI;
1509 autoEscape(undef);
1510
1511 A Lurking Trap! Some of the form-element generating methods return mul‐
1512 tiple tags. In a scalar context, the tags will be concatenated
1513 together with spaces, or whatever is the current value of the $"
1514 global. In a list context, the methods will return a list of elements,
1515 allowing you to modify them if you wish. Usually you will not notice
1516 this behavior, but beware of this:
1517
1518 printf("%s\n",end_form())
1519
1520 end_form() produces several tags, and only the first of them will be
1521 printed because the format only expects one value.
1522
1523 <p>
1524
1525 CREATING AN ISINDEX TAG
1526
1527 print isindex(-action=>$action);
1528
1529 -or-
1530
1531 print isindex($action);
1532
1533 Prints out an <isindex> tag. Not very exciting. The parameter -action
1534 specifies the URL of the script to process the query. The default is
1535 to process the query with the current script.
1536
1537 STARTING AND ENDING A FORM
1538
1539 print start_form(-method=>$method,
1540 -action=>$action,
1541 -enctype=>$encoding);
1542 <... various form stuff ...>
1543 print endform;
1544
1545 -or-
1546
1547 print start_form($method,$action,$encoding);
1548 <... various form stuff ...>
1549 print endform;
1550
1551 start_form() will return a <form> tag with the optional method, action
1552 and form encoding that you specify. The defaults are:
1553
1554 method: POST
1555 action: this script
1556 enctype: application/x-www-form-urlencoded
1557
1558 endform() returns the closing </form> tag.
1559
1560 Start_form()'s enctype argument tells the browser how to package the
1561 various fields of the form before sending the form to the server. Two
1562 values are possible:
1563
1564 Note: This method was previously named startform(), and startform() is
1565 still recognized as an alias.
1566
1567 application/x-www-form-urlencoded
1568 This is the older type of encoding used by all browsers prior to
1569 Netscape 2.0. It is compatible with many CGI scripts and is suit‐
1570 able for short fields containing text data. For your convenience,
1571 CGI.pm stores the name of this encoding type in &CGI::URL_ENCODED.
1572
1573 multipart/form-data
1574 This is the newer type of encoding introduced by Netscape 2.0. It
1575 is suitable for forms that contain very large fields or that are
1576 intended for transferring binary data. Most importantly, it
1577 enables the "file upload" feature of Netscape 2.0 forms. For your
1578 convenience, CGI.pm stores the name of this encoding type in
1579 &CGI::MULTIPART
1580
1581 Forms that use this type of encoding are not easily interpreted by
1582 CGI scripts unless they use CGI.pm or another library designed to
1583 handle them.
1584
1585 If XHTML is activated (the default), then forms will be automati‐
1586 cally created using this type of encoding.
1587
1588 For compatibility, the start_form() method uses the older form of
1589 encoding by default. If you want to use the newer form of encoding by
1590 default, you can call start_multipart_form() instead of start_form().
1591
1592 JAVASCRIPTING: The -name and -onSubmit parameters are provided for use
1593 with JavaScript. The -name parameter gives the form a name so that it
1594 can be identified and manipulated by JavaScript functions. -onSubmit
1595 should point to a JavaScript function that will be executed just before
1596 the form is submitted to your server. You can use this opportunity to
1597 check the contents of the form for consistency and completeness. If
1598 you find something wrong, you can put up an alert box or maybe fix
1599 things up yourself. You can abort the submission by returning false
1600 from this function.
1601
1602 Usually the bulk of JavaScript functions are defined in a <script>
1603 block in the HTML header and -onSubmit points to one of these function
1604 call. See start_html() for details.
1605
1606 FORM ELEMENTS
1607
1608 After starting a form, you will typically create one or more
1609 textfields, popup menus, radio groups and other form elements. Each of
1610 these elements takes a standard set of named arguments. Some elements
1611 also have optional arguments. The standard arguments are as follows:
1612
1613 -name
1614 The name of the field. After submission this name can be used to
1615 retrieve the field's value using the param() method.
1616
1617 -value, -values
1618 The initial value of the field which will be returned to the script
1619 after form submission. Some form elements, such as text fields,
1620 take a single scalar -value argument. Others, such as popup menus,
1621 take a reference to an array of values. The two arguments are syn‐
1622 onyms.
1623
1624 -tabindex
1625 A numeric value that sets the order in which the form element
1626 receives focus when the user presses the tab key. Elements with
1627 lower values receive focus first.
1628
1629 -id A string identifier that can be used to identify this element to
1630 JavaScript and DHTML.
1631
1632 -override
1633 A boolean, which, if true, forces the element to take on the value
1634 specified by -value, overriding the sticky behavior described ear‐
1635 lier for the -no_sticky pragma.
1636
1637 -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect
1638 These are used to assign JavaScript event handlers. See the
1639 JavaScripting section for more details.
1640
1641 Other common arguments are described in the next section. In addition
1642 to these, all attributes described in the HTML specifications are sup‐
1643 ported.
1644
1645 CREATING A TEXT FIELD
1646
1647 print textfield(-name=>'field_name',
1648 -value=>'starting value',
1649 -size=>50,
1650 -maxlength=>80);
1651 -or-
1652
1653 print textfield('field_name','starting value',50,80);
1654
1655 textfield() will return a text input field.
1656
1657 Parameters
1658 1. The first parameter is the required name for the field (-name).
1659
1660 2. The optional second parameter is the default starting value for the
1661 field contents (-value, formerly known as -default).
1662
1663 3. The optional third parameter is the size of the field in
1664 characters (-size).
1665
1666 4. The optional fourth parameter is the maximum number of characters
1667 the
1668 field will accept (-maxlength).
1669
1670 As with all these methods, the field will be initialized with its pre‐
1671 vious contents from earlier invocations of the script. When the form
1672 is processed, the value of the text field can be retrieved with:
1673
1674 $value = param('foo');
1675
1676 If you want to reset it from its initial value after the script has
1677 been called once, you can do so like this:
1678
1679 param('foo',"I'm taking over this value!");
1680
1681 CREATING A BIG TEXT FIELD
1682
1683 print textarea(-name=>'foo',
1684 -default=>'starting value',
1685 -rows=>10,
1686 -columns=>50);
1687
1688 -or
1689
1690 print textarea('foo','starting value',10,50);
1691
1692 textarea() is just like textfield, but it allows you to specify rows
1693 and columns for a multiline text entry box. You can provide a starting
1694 value for the field, which can be long and contain multiple lines.
1695
1696 CREATING A PASSWORD FIELD
1697
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
1711 print filefield(-name=>'uploaded_file',
1712 -default=>'starting value',
1713 -size=>50,
1714 -maxlength=>80);
1715 -or-
1716
1717 print filefield('uploaded_file','starting value',50,80);
1718
1719 filefield() will return a file upload field for Netscape 2.0 browsers.
1720 In order to take full advantage of this you must use the new multipart
1721 encoding scheme for the form. You can do this either by calling
1722 start_form() with an encoding type of &CGI::MULTIPART, or by calling
1723 the new method start_multipart_form() instead of vanilla start_form().
1724
1725 Parameters
1726 1. The first parameter is the required name for the field (-name).
1727
1728 2. The optional second parameter is the starting value for the field
1729 contents to be used as the default file name (-default).
1730
1731 For security reasons, browsers don't pay any attention to this
1732 field, and so the starting value will always be blank. Worse, the
1733 field loses its "sticky" behavior and forgets its previous con‐
1734 tents. The starting value field is called for in the HTML specifi‐
1735 cation, however, and possibly some browser will eventually provide
1736 support for it.
1737
1738 3. The optional third parameter is the size of the field in characters
1739 (-size).
1740
1741 4. The optional fourth parameter is the maximum number of characters
1742 the field will accept (-maxlength).
1743
1744 When the form is processed, you can retrieve the entered filename by
1745 calling param():
1746
1747 $filename = param('uploaded_file');
1748
1749 Different browsers will return slightly different things for the name.
1750 Some browsers return the filename only. Others return the full path to
1751 the file, using the path conventions of the user's machine. Regard‐
1752 less, the name returned is always the name of the file on the user's
1753 machine, and is unrelated to the name of the temporary file that CGI.pm
1754 creates during upload spooling (see below).
1755
1756 The filename returned is also a file handle. You can read the contents
1757 of the file using standard Perl file reading calls:
1758
1759 # Read a text file and print it out
1760 while (<$filename>) {
1761 print;
1762 }
1763
1764 # Copy a binary file to somewhere safe
1765 open (OUTFILE,">>/usr/local/web/users/feedback");
1766 while ($bytesread=read($filename,$buffer,1024)) {
1767 print OUTFILE $buffer;
1768 }
1769
1770 However, there are problems with the dual nature of the upload fields.
1771 If you "use strict", then Perl will complain when you try to use a
1772 string as a filehandle. You can get around this by placing the file
1773 reading code in a block containing the "no strict" pragma. More seri‐
1774 ously, it is possible for the remote user to type garbage into the
1775 upload field, in which case what you get from param() is not a filehan‐
1776 dle at all, but a string.
1777
1778 To be safe, use the upload() function (new in version 2.47). When
1779 called with the name of an upload field, upload() returns a filehandle,
1780 or undef if the parameter is not a valid filehandle.
1781
1782 $fh = upload('uploaded_file');
1783 while (<$fh>) {
1784 print;
1785 }
1786
1787 In an list context, upload() will return an array of filehandles. This
1788 makes it possible to create forms that use the same name for multiple
1789 upload fields.
1790
1791 This is the recommended idiom.
1792
1793 When a file is uploaded the browser usually sends along some informa‐
1794 tion along with it in the format of headers. The information usually
1795 includes the MIME content type. Future browsers may send other infor‐
1796 mation as well (such as modification date and size). To retrieve this
1797 information, call uploadInfo(). It returns a reference to an associa‐
1798 tive array containing all the document headers.
1799
1800 $filename = param('uploaded_file');
1801 $type = uploadInfo($filename)->{'Content-Type'};
1802 unless ($type eq 'text/html') {
1803 die "HTML FILES ONLY!";
1804 }
1805
1806 If you are using a machine that recognizes "text" and "binary" data
1807 modes, be sure to understand when and how to use them (see the Camel
1808 book). Otherwise you may find that binary files are corrupted during
1809 file uploads.
1810
1811 There are occasionally problems involving parsing the uploaded file.
1812 This usually happens when the user presses "Stop" before the upload is
1813 finished. In this case, CGI.pm will return undef for the name of the
1814 uploaded file and set cgi_error() to the string "400 Bad request (mal‐
1815 formed multipart POST)". This error message is designed so that you
1816 can incorporate it into a status code to be sent to the browser. Exam‐
1817 ple:
1818
1819 $file = upload('uploaded_file');
1820 if (!$file && cgi_error) {
1821 print header(-status=>cgi_error);
1822 exit 0;
1823 }
1824
1825 You are free to create a custom HTML page to complain about the error,
1826 if you wish.
1827
1828 You can set up a callback that will be called whenever a file upload is
1829 being read during the form processing. This is much like the
1830 UPLOAD_HOOK facility available in Apache::Request, with the exception
1831 that the first argument to the callback is an Apache::Upload object,
1832 here it's the remote filename.
1833
1834 $q = CGI->new(\&hook,$data);
1835
1836 sub hook
1837 {
1838 my ($filename, $buffer, $bytes_read, $data) = @_;
1839 print "Read $bytes_read bytes of $filename\n";
1840 }
1841
1842 If using the function-oriented interface, call the CGI::upload_hook()
1843 method before calling param() or any other CGI functions:
1844
1845 CGI::upload_hook(\&hook,$data);
1846
1847 This method is not exported by default. You will have to import it
1848 explicitly if you wish to use it without the CGI:: prefix.
1849
1850 If you are using CGI.pm on a Windows platform and find that binary
1851 files get slightly larger when uploaded but that text files remain the
1852 same, then you have forgotten to activate binary mode on the output
1853 filehandle. Be sure to call binmode() on any handle that you create to
1854 write the uploaded file to disk.
1855
1856 JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver,
1857 -onMouseOut and -onSelect parameters are recognized. See textfield()
1858 for details.
1859
1860 CREATING A POPUP MENU
1861
1862 print popup_menu('menu_name',
1863 ['eenie','meenie','minie'],
1864 'meenie');
1865
1866 -or-
1867
1868 %labels = ('eenie'=>'your first choice',
1869 'meenie'=>'your second choice',
1870 'minie'=>'your third choice');
1871 %attributes = ('eenie'=>{'class'=>'class of first choice'});
1872 print popup_menu('menu_name',
1873 ['eenie','meenie','minie'],
1874 'meenie',\%labels,\%attributes);
1875
1876 -or (named parameter style)-
1877
1878 print popup_menu(-name=>'menu_name',
1879 -values=>['eenie','meenie','minie'],
1880 -default=>'meenie',
1881 -labels=>\%labels,
1882 -attributes=>\%attributes);
1883
1884 popup_menu() creates a menu.
1885
1886 1. The required first argument is the menu's name (-name).
1887
1888 2. The required second argument (-values) is an array reference con‐
1889 taining the list of menu items in the menu. You can pass the
1890 method an anonymous array, as shown in the example, or a reference
1891 to a named array, such as "\@foo".
1892
1893 3. The optional third parameter (-default) is the name of the default
1894 menu choice. If not specified, the first item will be the default.
1895 The values of the previous choice will be maintained across
1896 queries.
1897
1898 4. The optional fourth parameter (-labels) is provided for people who
1899 want to use different values for the user-visible label inside the
1900 popup menu and the value returned to your script. It's a pointer
1901 to an associative array relating menu values to user-visible
1902 labels. If you leave this parameter blank, the menu values will be
1903 displayed by default. (You can also leave a label undefined if you
1904 want to).
1905
1906 5. The optional fifth parameter (-attributes) is provided to assign
1907 any of the common HTML attributes to an individual menu item. It's
1908 a pointer to an associative array relating menu values to another
1909 associative array with the attribute's name as the key and the
1910 attribute's value as the value.
1911
1912 When the form is processed, the selected value of the popup menu can be
1913 retrieved using:
1914
1915 $popup_menu_value = param('menu_name');
1916
1917 CREATING AN OPTION GROUP
1918
1919 Named parameter style
1920
1921 print popup_menu(-name=>'menu_name',
1922 -values=>[qw/eenie meenie minie/,
1923 optgroup(-name=>'optgroup_name',
1924 -values => ['moe','catch'],
1925 -attributes=>{'catch'=>{'class'=>'red'}})],
1926 -labels=>{'eenie'=>'one',
1927 'meenie'=>'two',
1928 'minie'=>'three'},
1929 -default=>'meenie');
1930
1931 Old style
1932 print popup_menu('menu_name',
1933 ['eenie','meenie','minie',
1934 optgroup('optgroup_name', ['moe', 'catch'],
1935 {'catch'=>{'class'=>'red'}})],'meenie',
1936 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
1937
1938 optgroup() creates an option group within a popup menu.
1939
1940 1. The required first argument (-name) is the label attribute of the
1941 optgroup and is not inserted in the parameter list of the query.
1942
1943 2. The required second argument (-values) is an array reference con‐
1944 taining the list of menu items in the menu. You can pass the
1945 method an anonymous array, as shown in the example, or a reference
1946 to a named array, such as \@foo. If you pass a HASH reference, the
1947 keys will be used for the menu values, and the values will be used
1948 for the menu labels (see -labels below).
1949
1950 3. The optional third parameter (-labels) allows you to pass a refer‐
1951 ence to an associative array containing user-visible labels for one
1952 or more of the menu items. You can use this when you want the user
1953 to see one menu string, but have the browser return your program a
1954 different one. If you don't specify this, the value string will be
1955 used instead ("eenie", "meenie" and "minie" in this example). This
1956 is equivalent to using a hash reference for the -values parameter.
1957
1958 4. An optional fourth parameter (-labeled) can be set to a true value
1959 and indicates that the values should be used as the label attribute
1960 for each option element within the optgroup.
1961
1962 5. An optional fifth parameter (-novals) can be set to a true value
1963 and indicates to suppress the val attribut in each option element
1964 within the optgroup.
1965
1966 See the discussion on optgroup at W3C
1967 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
1968 for details.
1969
1970 6. An optional sixth parameter (-attributes) is provided to assign any
1971 of the common HTML attributes to an individual menu item. It's a
1972 pointer to an associative array relating menu values to another
1973 associative array with the attribute's name as the key and the
1974 attribute's value as the value.
1975
1976 CREATING A SCROLLING LIST
1977
1978 print scrolling_list('list_name',
1979 ['eenie','meenie','minie','moe'],
1980 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
1981 -or-
1982
1983 print scrolling_list('list_name',
1984 ['eenie','meenie','minie','moe'],
1985 ['eenie','moe'],5,'true',
1986 \%labels,%attributes);
1987
1988 -or-
1989
1990 print scrolling_list(-name=>'list_name',
1991 -values=>['eenie','meenie','minie','moe'],
1992 -default=>['eenie','moe'],
1993 -size=>5,
1994 -multiple=>'true',
1995 -labels=>\%labels,
1996 -attributes=>\%attributes);
1997
1998 scrolling_list() creates a scrolling list.
1999
2000 Parameters:
2001 1. The first and second arguments are the list name (-name) and values
2002 (-values). As in the popup menu, the second argument should be an
2003 array reference.
2004
2005 2. The optional third argument (-default) can be either a reference to
2006 a list containing the values to be selected by default, or can be a
2007 single value to select. If this argument is missing or undefined,
2008 then nothing is selected when the list first appears. In the named
2009 parameter version, you can use the synonym "-defaults" for this
2010 parameter.
2011
2012 3. The optional fourth argument is the size of the list (-size).
2013
2014 4. The optional fifth argument can be set to true to allow multiple
2015 simultaneous selections (-multiple). Otherwise only one selection
2016 will be allowed at a time.
2017
2018 5. The optional sixth argument is a pointer to an associative array
2019 containing long user-visible labels for the list items (-labels).
2020 If not provided, the values will be displayed.
2021
2022 6. The optional sixth parameter (-attributes) is provided to assign
2023 any of the common HTML attributes to an individual menu item. It's
2024 a pointer to an associative array relating menu values to another
2025 associative array with the attribute's name as the key and the
2026 attribute's value as the value.
2027
2028 When this form is processed, all selected list items will be
2029 returned as a list under the parameter name 'list_name'. The val‐
2030 ues of the selected items can be retrieved with:
2031
2032 @selected = param('list_name');
2033
2034 CREATING A GROUP OF RELATED CHECKBOXES
2035
2036 print checkbox_group(-name=>'group_name',
2037 -values=>['eenie','meenie','minie','moe'],
2038 -default=>['eenie','moe'],
2039 -linebreak=>'true',
2040 -labels=>\%labels,
2041 -attributes=>\%attributes);
2042
2043 print checkbox_group('group_name',
2044 ['eenie','meenie','minie','moe'],
2045 ['eenie','moe'],'true',\%labels,
2046 {'moe'=>{'class'=>'red'}});
2047
2048 HTML3-COMPATIBLE BROWSERS ONLY:
2049
2050 print checkbox_group(-name=>'group_name',
2051 -values=>['eenie','meenie','minie','moe'],
2052 -rows=2,-columns=>2);
2053
2054 checkbox_group() creates a list of checkboxes that are related by the
2055 same name.
2056
2057 Parameters:
2058 1. The first and second arguments are the checkbox name and values,
2059 respectively (-name and -values). As in the popup menu, the second
2060 argument should be an array reference. These values are used for
2061 the user-readable labels printed next to the checkboxes as well as
2062 for the values passed to your script in the query string.
2063
2064 2. The optional third argument (-default) can be either a reference to
2065 a list containing the values to be checked by default, or can be a
2066 single value to checked. If this argument is missing or undefined,
2067 then nothing is selected when the list first appears.
2068
2069 3. The optional fourth argument (-linebreak) can be set to true to
2070 place line breaks between the checkboxes so that they appear as a
2071 vertical list. Otherwise, they will be strung together on a hori‐
2072 zontal line.
2073
2074 The optional b<-labels> argument is a pointer to an associative array
2075 relating the checkbox values to the user-visible labels that will be
2076 printed next to them. If not provided, the values will be used as the
2077 default.
2078
2079 Modern browsers can take advantage of the optional parameters -rows,
2080 and -columns. These parameters cause checkbox_group() to return an
2081 HTML3 compatible table containing the checkbox group formatted with the
2082 specified number of rows and columns. You can provide just the -col‐
2083 umns parameter if you wish; checkbox_group will calculate the correct
2084 number of rows for you.
2085
2086 The optional -attributes argument is provided to assign any of the com‐
2087 mon HTML attributes to an individual menu item. It's a pointer to an
2088 associative array relating menu values to another associative array
2089 with the attribute's name as the key and the attribute's value as the
2090 value.
2091
2092 The optional -tabindex argument can be used to control the order in
2093 which radio buttons receive focus when the user presses the tab button.
2094 If passed a scalar numeric value, the first element in the group will
2095 receive this tab index and subsequent elements will be incremented by
2096 one. If given a reference to an array of radio button values, then the
2097 indexes will be jiggered so that the order specified in the array will
2098 correspond to the tab order. You can also pass a reference to a hash
2099 in which the hash keys are the radio button values and the values are
2100 the tab indexes of each button. Examples:
2101
2102 -tabindex => 100 # this group starts at index 100 and counts up
2103 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
2104 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2105
2106 When the form is processed, all checked boxes will be returned as a
2107 list under the parameter name 'group_name'. The values of the "on"
2108 checkboxes can be retrieved with:
2109
2110 @turned_on = param('group_name');
2111
2112 The value returned by checkbox_group() is actually an array of button
2113 elements. You can capture them and use them within tables, lists, or
2114 in other creative ways:
2115
2116 @h = checkbox_group(-name=>'group_name',-values=>\@values);
2117 &use_in_creative_way(@h);
2118
2119 CREATING A STANDALONE CHECKBOX
2120
2121 print checkbox(-name=>'checkbox_name',
2122 -checked=>1,
2123 -value=>'ON',
2124 -label=>'CLICK ME');
2125
2126 -or-
2127
2128 print checkbox('checkbox_name','checked','ON','CLICK ME');
2129
2130 checkbox() is used to create an isolated checkbox that isn't logically
2131 related to any others.
2132
2133 Parameters:
2134 1. The first parameter is the required name for the checkbox (-name).
2135 It will also be used for the user-readable label printed next to
2136 the checkbox.
2137
2138 2. The optional second parameter (-checked) specifies that the check‐
2139 box is turned on by default. Synonyms are -selected and -on.
2140
2141 3. The optional third parameter (-value) specifies the value of the
2142 checkbox when it is checked. If not provided, the word "on" is
2143 assumed.
2144
2145 4. The optional fourth parameter (-label) is the user-readable label
2146 to be attached to the checkbox. If not provided, the checkbox name
2147 is used.
2148
2149 The value of the checkbox can be retrieved using:
2150
2151 $turned_on = param('checkbox_name');
2152
2153 CREATING A RADIO BUTTON GROUP
2154
2155 print radio_group(-name=>'group_name',
2156 -values=>['eenie','meenie','minie'],
2157 -default=>'meenie',
2158 -linebreak=>'true',
2159 -labels=>\%labels,
2160 -attributes=>\%attributes);
2161
2162 -or-
2163
2164 print radio_group('group_name',['eenie','meenie','minie'],
2165 'meenie','true',\%labels,\%attributes);
2166
2167 HTML3-COMPATIBLE BROWSERS ONLY:
2168
2169 print radio_group(-name=>'group_name',
2170 -values=>['eenie','meenie','minie','moe'],
2171 -rows=2,-columns=>2);
2172
2173 radio_group() creates a set of logically-related radio buttons (turning
2174 one member of the group on turns the others off)
2175
2176 Parameters:
2177 1. The first argument is the name of the group and is required
2178 (-name).
2179
2180 2. The second argument (-values) is the list of values for the radio
2181 buttons. The values and the labels that appear on the page are
2182 identical. Pass an array reference in the second argument, either
2183 using an anonymous array, as shown, or by referencing a named array
2184 as in "\@foo".
2185
2186 3. The optional third parameter (-default) is the name of the default
2187 button to turn on. If not specified, the first item will be the
2188 default. You can provide a nonexistent button name, such as "-" to
2189 start up with no buttons selected.
2190
2191 4. The optional fourth parameter (-linebreak) can be set to 'true' to
2192 put line breaks between the buttons, creating a vertical list.
2193
2194 5. The optional fifth parameter (-labels) is a pointer to an associa‐
2195 tive array relating the radio button values to user-visible labels
2196 to be used in the display. If not provided, the values themselves
2197 are displayed.
2198
2199 All modern browsers can take advantage of the optional parameters
2200 -rows, and -columns. These parameters cause radio_group() to return an
2201 HTML3 compatible table containing the radio group formatted with the
2202 specified number of rows and columns. You can provide just the -col‐
2203 umns parameter if you wish; radio_group will calculate the correct num‐
2204 ber of rows for you.
2205
2206 To include row and column headings in the returned table, you can use
2207 the -rowheader and -colheader parameters. Both of these accept a
2208 pointer to an array of headings to use. The headings are just decora‐
2209 tive. They don't reorganize the interpretation of the radio buttons --
2210 they're still a single named unit.
2211
2212 The optional -tabindex argument can be used to control the order in
2213 which radio buttons receive focus when the user presses the tab button.
2214 If passed a scalar numeric value, the first element in the group will
2215 receive this tab index and subsequent elements will be incremented by
2216 one. If given a reference to an array of radio button values, then the
2217 indexes will be jiggered so that the order specified in the array will
2218 correspond to the tab order. You can also pass a reference to a hash
2219 in which the hash keys are the radio button values and the values are
2220 the tab indexes of each button. Examples:
2221
2222 -tabindex => 100 # this group starts at index 100 and counts up
2223 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
2224 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
2225
2226 The optional -attributes argument is provided to assign any of the com‐
2227 mon HTML attributes to an individual menu item. It's a pointer to an
2228 associative array relating menu values to another associative array
2229 with the attribute's name as the key and the attribute's value as the
2230 value.
2231
2232 When the form is processed, the selected radio button can be retrieved
2233 using:
2234
2235 $which_radio_button = param('group_name');
2236
2237 The value returned by radio_group() is actually an array of button ele‐
2238 ments. You can capture them and use them within tables, lists, or in
2239 other creative ways:
2240
2241 @h = radio_group(-name=>'group_name',-values=>\@values);
2242 &use_in_creative_way(@h);
2243
2244 CREATING A SUBMIT BUTTON
2245
2246 print submit(-name=>'button_name',
2247 -value=>'value');
2248
2249 -or-
2250
2251 print submit('button_name','value');
2252
2253 submit() will create the query submission button. Every form should
2254 have one of these.
2255
2256 Parameters:
2257 1. The first argument (-name) is optional. You can give the button a
2258 name if you have several submission buttons in your form and you
2259 want to distinguish between them.
2260
2261 2. The second argument (-value) is also optional. This gives the but‐
2262 ton a value that will be passed to your script in the query string.
2263 The name will also be used as the user-visible label.
2264
2265 3. You can use -label as an alias for -value. I always get confused
2266 about which of -name and -value changes the user-visible label on
2267 the button.
2268
2269 You can figure out which button was pressed by using different values
2270 for each one:
2271
2272 $which_one = param('button_name');
2273
2274 CREATING A RESET BUTTON
2275
2276 print reset
2277
2278 reset() creates the "reset" button. Note that it restores the form to
2279 its value from the last time the script was called, NOT necessarily to
2280 the defaults.
2281
2282 Note that this conflicts with the Perl reset() built-in. Use
2283 CORE::reset() to get the original reset function.
2284
2285 CREATING A DEFAULT BUTTON
2286
2287 print defaults('button_label')
2288
2289 defaults() creates a button that, when invoked, will cause the form to
2290 be completely reset to its defaults, wiping out all the changes the
2291 user ever made.
2292
2293 CREATING A HIDDEN FIELD
2294
2295 print hidden(-name=>'hidden_name',
2296 -default=>['value1','value2'...]);
2297
2298 -or-
2299
2300 print hidden('hidden_name','value1','value2'...);
2301
2302 hidden() produces a text field that can't be seen by the user. It is
2303 useful for passing state variable information from one invocation of
2304 the script to the next.
2305
2306 Parameters:
2307 1. The first argument is required and specifies the name of this field
2308 (-name).
2309
2310 2. The second argument is also required and specifies its value
2311 (-default). In the named parameter style of calling, you can pro‐
2312 vide a single value here or a reference to a whole list
2313
2314 Fetch the value of a hidden field this way:
2315
2316 $hidden_value = param('hidden_name');
2317
2318 Note, that just like all the other form elements, the value of a hidden
2319 field is "sticky". If you want to replace a hidden field with some
2320 other values after the script has been called once you'll have to do it
2321 manually:
2322
2323 param('hidden_name','new','values','here');
2324
2325 CREATING A CLICKABLE IMAGE BUTTON
2326
2327 print image_button(-name=>'button_name',
2328 -src=>'/source/URL',
2329 -align=>'MIDDLE');
2330
2331 -or-
2332
2333 print image_button('button_name','/source/URL','MIDDLE');
2334
2335 image_button() produces a clickable image. When it's clicked on the
2336 position of the click is returned to your script as "button_name.x" and
2337 "button_name.y", where "button_name" is the name you've assigned to it.
2338
2339 Parameters:
2340 1. The first argument (-name) is required and specifies the name of
2341 this field.
2342
2343 2. The second argument (-src) is also required and specifies the URL
2344
2345 3. The third option (-align, optional) is an alignment type, and may be
2346 TOP, BOTTOM or MIDDLE
2347
2348 Fetch the value of the button this way:
2349 $x = param('button_name.x');
2350 $y = param('button_name.y');
2351
2352 CREATING A JAVASCRIPT ACTION BUTTON
2353
2354 print button(-name=>'button_name',
2355 -value=>'user visible label',
2356 -onClick=>"do_something()");
2357
2358 -or-
2359
2360 print button('button_name',"do_something()");
2361
2362 button() produces a button that is compatible with Netscape 2.0's
2363 JavaScript. When it's pressed the fragment of JavaScript code pointed
2364 to by the -onClick parameter will be executed. On non-Netscape
2365 browsers this form element will probably not even display.
2366
2368 Netscape browsers versions 1.1 and higher, and all versions of Internet
2369 Explorer, support a so-called "cookie" designed to help maintain state
2370 within a browser session. CGI.pm has several methods that support
2371 cookies.
2372
2373 A cookie is a name=value pair much like the named parameters in a CGI
2374 query string. CGI scripts create one or more cookies and send them to
2375 the browser in the HTTP header. The browser maintains a list of cook‐
2376 ies that belong to a particular Web server, and returns them to the CGI
2377 script during subsequent interactions.
2378
2379 In addition to the required name=value pair, each cookie has several
2380 optional attributes:
2381
2382 1. an expiration time
2383 This is a time/date string (in a special GMT format) that indicates
2384 when a cookie expires. The cookie will be saved and returned to
2385 your script until this expiration date is reached if the user exits
2386 the browser and restarts it. If an expiration date isn't speci‐
2387 fied, the cookie will remain active until the user quits the
2388 browser.
2389
2390 2. a domain
2391 This is a partial or complete domain name for which the cookie is
2392 valid. The browser will return the cookie to any host that matches
2393 the partial domain name. For example, if you specify a domain name
2394 of ".capricorn.com", then the browser will return the cookie to Web
2395 servers running on any of the machines "www.capricorn.com",
2396 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
2397 must contain at least two periods to prevent attempts to match on
2398 top level domains like ".edu". If no domain is specified, then the
2399 browser will only return the cookie to servers on the host the
2400 cookie originated from.
2401
2402 3. a path
2403 If you provide a cookie path attribute, the browser will check it
2404 against your script's URL before returning the cookie. For exam‐
2405 ple, if you specify the path "/cgi-bin", then the cookie will be
2406 returned to each of the scripts "/cgi-bin/tally.pl",
2407 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
2408 but not to the script "/cgi-private/site_admin.pl". By default,
2409 path is set to "/", which causes the cookie to be sent to any CGI
2410 script on your site.
2411
2412 4. a "secure" flag
2413 If the "secure" attribute is set, the cookie will only be sent to
2414 your script if the CGI request is occurring on a secure channel,
2415 such as SSL.
2416
2417 The interface to HTTP cookies is the cookie() method:
2418
2419 $cookie = cookie(-name=>'sessionID',
2420 -value=>'xyzzy',
2421 -expires=>'+1h',
2422 -path=>'/cgi-bin/database',
2423 -domain=>'.capricorn.org',
2424 -secure=>1);
2425 print header(-cookie=>$cookie);
2426
2427 cookie() creates a new cookie. Its parameters include:
2428
2429 -name
2430 The name of the cookie (required). This can be any string at all.
2431 Although browsers limit their cookie names to non-whitespace
2432 alphanumeric characters, CGI.pm removes this restriction by escap‐
2433 ing and unescaping cookies behind the scenes.
2434
2435 -value
2436 The value of the cookie. This can be any scalar value, array ref‐
2437 erence, or even associative array reference. For example, you can
2438 store an entire associative array into a cookie this way:
2439
2440 $cookie=cookie(-name=>'family information',
2441 -value=>\%childrens_ages);
2442
2443 -path
2444 The optional partial path for which this cookie will be valid, as
2445 described above.
2446
2447 -domain
2448 The optional partial domain for which this cookie will be valid, as
2449 described above.
2450
2451 -expires
2452 The optional expiration date for this cookie. The format is as
2453 described in the section on the header() method:
2454
2455 "+1h" one hour from now
2456
2457 -secure
2458 If set to true, this cookie will only be used within a secure SSL
2459 session.
2460
2461 The cookie created by cookie() must be incorporated into the HTTP
2462 header within the string returned by the header() method:
2463
2464 print header(-cookie=>$my_cookie);
2465
2466 To create multiple cookies, give header() an array reference:
2467
2468 $cookie1 = cookie(-name=>'riddle_name',
2469 -value=>"The Sphynx's Question");
2470 $cookie2 = cookie(-name=>'answers',
2471 -value=>\%answers);
2472 print header(-cookie=>[$cookie1,$cookie2]);
2473
2474 To retrieve a cookie, request it by name by calling cookie() method
2475 without the -value parameter:
2476
2477 use CGI;
2478 $query = new CGI;
2479 $riddle = cookie('riddle_name');
2480 %answers = cookie('answers');
2481
2482 Cookies created with a single scalar value, such as the "riddle_name"
2483 cookie, will be returned in that form. Cookies with array and hash
2484 values can also be retrieved.
2485
2486 The cookie and CGI namespaces are separate. If you have a parameter
2487 named 'answers' and a cookie named 'answers', the values retrieved by
2488 param() and cookie() are independent of each other. However, it's sim‐
2489 ple to turn a CGI parameter into a cookie, and vice-versa:
2490
2491 # turn a CGI parameter into a cookie
2492 $c=cookie(-name=>'answers',-value=>[param('answers')]);
2493 # vice-versa
2494 param(-name=>'answers',-value=>[cookie('answers')]);
2495
2496 See the cookie.cgi example script for some ideas on how to use cookies
2497 effectively.
2498
2500 It's possible for CGI.pm scripts to write into several browser panels
2501 and windows using the HTML 4 frame mechanism. There are three tech‐
2502 niques for defining new frames programmatically:
2503
2504 1. Create a <Frameset> document
2505 After writing out the HTTP header, instead of creating a standard
2506 HTML document using the start_html() call, create a <frameset> doc‐
2507 ument that defines the frames on the page. Specify your script(s)
2508 (with appropriate parameters) as the SRC for each of the frames.
2509
2510 There is no specific support for creating <frameset> sections in
2511 CGI.pm, but the HTML is very simple to write. See the frame docu‐
2512 mentation in Netscape's home pages for details
2513
2514 http://home.netscape.com/assist/net_sites/frames.html
2515
2516 2. Specify the destination for the document in the HTTP header
2517 You may provide a -target parameter to the header() method:
2518
2519 print header(-target=>'ResultsWindow');
2520
2521 This will tell the browser to load the output of your script into
2522 the frame named "ResultsWindow". If a frame of that name doesn't
2523 already exist, the browser will pop up a new window and load your
2524 script's document into that. There are a number of magic names
2525 that you can use for targets. See the frame documents on Net‐
2526 scape's home pages for details.
2527
2528 3. Specify the destination for the document in the <form> tag
2529 You can specify the frame to load in the FORM tag itself. With
2530 CGI.pm it looks like this:
2531
2532 print start_form(-target=>'ResultsWindow');
2533
2534 When your script is reinvoked by the form, its output will be
2535 loaded into the frame named "ResultsWindow". If one doesn't
2536 already exist a new window will be created.
2537
2538 The script "frameset.cgi" in the examples directory shows one way to
2539 create pages in which the fill-out form and the response live in side-
2540 by-side frames.
2541
2543 Netscape versions 2.0 and higher incorporate an interpreted language
2544 called JavaScript. Internet Explorer, 3.0 and higher, supports a
2545 closely-related dialect called JScript. JavaScript isn't the same as
2546 Java, and certainly isn't at all the same as Perl, which is a great
2547 pity. JavaScript allows you to programatically change the contents of
2548 fill-out forms, create new windows, and pop up dialog box from within
2549 Netscape itself. From the point of view of CGI scripting, JavaScript is
2550 quite useful for validating fill-out forms prior to submitting them.
2551
2552 You'll need to know JavaScript in order to use it. There are many good
2553 sources in bookstores and on the web.
2554
2555 The usual way to use JavaScript is to define a set of functions in a
2556 <SCRIPT> block inside the HTML header and then to register event han‐
2557 dlers in the various elements of the page. Events include such things
2558 as the mouse passing over a form element, a button being clicked, the
2559 contents of a text field changing, or a form being submitted. When an
2560 event occurs that involves an element that has registered an event han‐
2561 dler, its associated JavaScript code gets called.
2562
2563 The elements that can register event handlers include the <BODY> of an
2564 HTML document, hypertext links, all the various elements of a fill-out
2565 form, and the form itself. There are a large number of events, and each
2566 applies only to the elements for which it is relevant. Here is a par‐
2567 tial list:
2568
2569 onLoad
2570 The browser is loading the current document. Valid in:
2571
2572 + The HTML <BODY> section only.
2573
2574 onUnload
2575 The browser is closing the current page or frame. Valid for:
2576
2577 + The HTML <BODY> section only.
2578
2579 onSubmit
2580 The user has pressed the submit button of a form. This event hap‐
2581 pens just before the form is submitted, and your function can
2582 return a value of false in order to abort the submission. Valid
2583 for:
2584
2585 + Forms only.
2586
2587 onClick
2588 The mouse has clicked on an item in a fill-out form. Valid for:
2589
2590 + Buttons (including submit, reset, and image buttons)
2591 + Checkboxes
2592 + Radio buttons
2593
2594 onChange
2595 The user has changed the contents of a field. Valid for:
2596
2597 + Text fields
2598 + Text areas
2599 + Password fields
2600 + File fields
2601 + Popup Menus
2602 + Scrolling lists
2603
2604 onFocus
2605 The user has selected a field to work with. Valid for:
2606
2607 + Text fields
2608 + Text areas
2609 + Password fields
2610 + File fields
2611 + Popup Menus
2612 + Scrolling lists
2613
2614 onBlur
2615 The user has deselected a field (gone to work somewhere else).
2616 Valid for:
2617
2618 + Text fields
2619 + Text areas
2620 + Password fields
2621 + File fields
2622 + Popup Menus
2623 + Scrolling lists
2624
2625 onSelect
2626 The user has changed the part of a text field that is selected.
2627 Valid for:
2628
2629 + Text fields
2630 + Text areas
2631 + Password fields
2632 + File fields
2633
2634 onMouseOver
2635 The mouse has moved over an element.
2636
2637 + Text fields
2638 + Text areas
2639 + Password fields
2640 + File fields
2641 + Popup Menus
2642 + Scrolling lists
2643
2644 onMouseOut
2645 The mouse has moved off an element.
2646
2647 + Text fields
2648 + Text areas
2649 + Password fields
2650 + File fields
2651 + Popup Menus
2652 + Scrolling lists
2653
2654 In order to register a JavaScript event handler with an HTML element,
2655 just use the event name as a parameter when you call the corresponding
2656 CGI method. For example, to have your validateAge() JavaScript code
2657 executed every time the textfield named "age" changes, generate the
2658 field like this:
2659
2660 print textfield(-name=>'age',-onChange=>"validateAge(this)");
2661
2662 This example assumes that you've already declared the validateAge()
2663 function by incorporating it into a <SCRIPT> block. The CGI.pm
2664 start_html() method provides a convenient way to create this section.
2665
2666 Similarly, you can create a form that checks itself over for consis‐
2667 tency and alerts the user if some essential value is missing by creat‐
2668 ing it this way:
2669 print startform(-onSubmit=>"validateMe(this)");
2670
2671 See the javascript.cgi script for a demonstration of how this all
2672 works.
2673
2675 CGI.pm has limited support for HTML3's cascading style sheets (css).
2676 To incorporate a stylesheet into your document, pass the start_html()
2677 method a -style parameter. The value of this parameter may be a
2678 scalar, in which case it is treated as the source URL for the
2679 stylesheet, or it may be a hash reference. In the latter case you
2680 should provide the hash with one or more of -src or -code. -src points
2681 to a URL where an externally-defined stylesheet can be found. -code
2682 points to a scalar value to be incorporated into a <style> section.
2683 Style definitions in -code override similarly-named ones in -src, hence
2684 the name "cascading."
2685
2686 You may also specify the type of the stylesheet by adding the optional
2687 -type parameter to the hash pointed to by -style. If not specified,
2688 the style defaults to 'text/css'.
2689
2690 To refer to a style within the body of your document, add the -class
2691 parameter to any HTML element:
2692
2693 print h1({-class=>'Fancy'},'Welcome to the Party');
2694
2695 Or define styles on the fly with the -style parameter:
2696
2697 print h1({-style=>'Color: red;'},'Welcome to Hell');
2698
2699 You may also use the new span() element to apply a style to a section
2700 of text:
2701
2702 print span({-style=>'Color: red;'},
2703 h1('Welcome to Hell'),
2704 "Where did that handbasket get to?"
2705 );
2706
2707 Note that you must import the ":html3" definitions to have the span()
2708 method available. Here's a quick and dirty example of using CSS's.
2709 See the CSS specification at http://www.w3.org/pub/WWW/TR/Wd-css-1.html
2710 for more information.
2711
2712 use CGI qw/:standard :html3/;
2713
2714 #here's a stylesheet incorporated directly into the page
2715 $newStyle=<<END;
2716 <!--
2717 P.Tip {
2718 margin-right: 50pt;
2719 margin-left: 50pt;
2720 color: red;
2721 }
2722 P.Alert {
2723 font-size: 30pt;
2724 font-family: sans-serif;
2725 color: red;
2726 }
2727 -->
2728 END
2729 print header();
2730 print start_html( -title=>'CGI with Style',
2731 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
2732 -code=>$newStyle}
2733 );
2734 print h1('CGI with Style'),
2735 p({-class=>'Tip'},
2736 "Better read the cascading style sheet spec before playing with this!"),
2737 span({-style=>'color: magenta'},
2738 "Look Mom, no hands!",
2739 p(),
2740 "Whooo wee!"
2741 );
2742 print end_html;
2743
2744 Pass an array reference to -code or -src in order to incorporate multi‐
2745 ple stylesheets into your document.
2746
2747 Should you wish to incorporate a verbatim stylesheet that includes
2748 arbitrary formatting in the header, you may pass a -verbatim tag to the
2749 -style hash, as follows:
2750
2751 print start_html (-STYLE => {-verbatim => '@import url("/server-com‐
2752 mon/css/'.$cssFile.'");',
2753 -src => '/server-common/css/core.css'});
2754 </blockquote></pre>
2755
2756 This will generate an HTML header that contains this:
2757
2758 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
2759 <style type="text/css">
2760 @import url("/server-common/css/main.css");
2761 </style>
2762
2763 Any additional arguments passed in the -style value will be incorpo‐
2764 rated into the <link> tag. For example:
2765
2766 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
2767 -media => 'all'});
2768
2769 This will give:
2770
2771 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
2772 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
2773
2774 <p>
2775
2776 To make more complicated <link> tags, use the Link() function and pass
2777 it to start_html() in the -head argument, as in:
2778
2779 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
2780 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
2781 print start_html({-head=>\@h})
2782
2784 If you are running the script from the command line or in the perl
2785 debugger, you can pass the script a list of keywords or parameter=value
2786 pairs on the command line or from standard input (you don't have to
2787 worry about tricking your script into reading from environment vari‐
2788 ables). You can pass keywords like this:
2789
2790 your_script.pl keyword1 keyword2 keyword3
2791
2792 or this:
2793
2794 your_script.pl keyword1+keyword2+keyword3
2795
2796 or this:
2797
2798 your_script.pl name1=value1 name2=value2
2799
2800 or this:
2801
2802 your_script.pl name1=value1&name2=value2
2803
2804 To turn off this feature, use the -no_debug pragma.
2805
2806 To test the POST method, you may enable full debugging with the -debug
2807 pragma. This will allow you to feed newline-delimited name=value pairs
2808 to the script on standard input.
2809
2810 When debugging, you can use quotes and backslashes to escape characters
2811 in the familiar shell manner, letting you place spaces and other funny
2812 characters in your parameter=value pairs:
2813
2814 your_script.pl "name1='I am a long value'" "name2=two\ words"
2815
2816 Finally, you can set the path info for the script by prefixing the
2817 first name/value parameter with the path followed by a question mark
2818 (?):
2819
2820 your_script.pl /your/path/here?name1=value1&name2=value2
2821
2822 DUMPING OUT ALL THE NAME/VALUE PAIRS
2823
2824 The Dump() method produces a string consisting of all the query's
2825 name/value pairs formatted nicely as a nested list. This is useful for
2826 debugging purposes:
2827
2828 print Dump
2829
2830 Produces something that looks like:
2831
2832 <ul>
2833 <li>name1
2834 <ul>
2835 <li>value1
2836 <li>value2
2837 </ul>
2838 <li>name2
2839 <ul>
2840 <li>value1
2841 </ul>
2842 </ul>
2843
2844 As a shortcut, you can interpolate the entire CGI object into a string
2845 and it will be replaced with the a nice HTML dump shown above:
2846
2847 $query=new CGI;
2848 print "<h2>Current Values</h2> $query\n";
2849
2851 Some of the more useful environment variables can be fetched through
2852 this interface. The methods are as follows:
2853
2854 Accept()
2855 Return a list of MIME types that the remote browser accepts. If you
2856 give this method a single argument corresponding to a MIME type, as
2857 in Accept('text/html'), it will return a floating point value cor‐
2858 responding to the browser's preference for this type from 0.0
2859 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's
2860 accept list are handled correctly.
2861
2862 Note that the capitalization changed between version 2.43 and 2.44
2863 in order to avoid conflict with Perl's accept() function.
2864
2865 raw_cookie()
2866 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
2867 Netscape browsers version 1.1 and higher, and all versions of
2868 Internet Explorer. Cookies have a special format, and this method
2869 call just returns the raw form (?cookie dough). See cookie() for
2870 ways of setting and retrieving cooked cookies.
2871
2872 Called with no parameters, raw_cookie() returns the packed cookie
2873 structure. You can separate it into individual cookies by split‐
2874 ting on the character sequence "; ". Called with the name of a
2875 cookie, retrieves the unescaped form of the cookie. You can use
2876 the regular cookie() method to get the names, or use the
2877 raw_fetch() method from the CGI::Cookie module.
2878
2879 user_agent()
2880 Returns the HTTP_USER_AGENT variable. If you give this method a
2881 single argument, it will attempt to pattern match on it, allowing
2882 you to do something like user_agent(netscape);
2883
2884 path_info()
2885 Returns additional path information from the script URL. E.G.
2886 fetching /cgi-bin/your_script/additional/stuff will result in
2887 path_info() returning "/additional/stuff".
2888
2889 NOTE: The Microsoft Internet Information Server is broken with
2890 respect to additional path information. If you use the Perl DLL
2891 library, the IIS server will attempt to execute the additional path
2892 information as a Perl script. If you use the ordinary file associ‐
2893 ations mapping, the path information will be present in the envi‐
2894 ronment, but incorrect. The best thing to do is to avoid using
2895 additional path information in CGI scripts destined for use with
2896 IIS.
2897
2898 path_translated()
2899 As per path_info() but returns the additional path information
2900 translated into a physical path, e.g.
2901 "/usr/local/etc/httpd/htdocs/additional/stuff".
2902
2903 The Microsoft IIS is broken with respect to the translated path as
2904 well.
2905
2906 remote_host()
2907 Returns either the remote host name or IP address. if the former
2908 is unavailable.
2909
2910 script_name() Return the script name as a partial URL, for self-refer‐
2911 ing scripts.
2912 referer()
2913 Return the URL of the page the browser was viewing prior to fetch‐
2914 ing your script. Not available for all browsers.
2915
2916 auth_type ()
2917 Return the authorization/verification method in use for this
2918 script, if any.
2919
2920 server_name ()
2921 Returns the name of the server, usually the machine's host name.
2922
2923 virtual_host ()
2924 When using virtual hosts, returns the name of the host that the
2925 browser attempted to contact
2926
2927 server_port ()
2928 Return the port that the server is listening on.
2929
2930 virtual_port ()
2931 Like server_port() except that it takes virtual hosts into account.
2932 Use this when running with virtual hosts.
2933
2934 server_software ()
2935 Returns the server software and version number.
2936
2937 remote_user ()
2938 Return the authorization/verification name used for user verifica‐
2939 tion, if this script is protected.
2940
2941 user_name ()
2942 Attempt to obtain the remote user's name, using a variety of dif‐
2943 ferent techniques. This only works with older browsers such as
2944 Mosaic. Newer browsers do not report the user name for privacy
2945 reasons!
2946
2947 request_method()
2948 Returns the method used to access your script, usually one of
2949 'POST', 'GET' or 'HEAD'.
2950
2951 content_type()
2952 Returns the content_type of data submitted in a POST, generally
2953 multipart/form-data or application/x-www-form-urlencoded
2954
2955 http()
2956 Called with no arguments returns the list of HTTP environment vari‐
2957 ables, including such things as HTTP_USER_AGENT, HTTP_ACCEPT_LAN‐
2958 GUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the like-named
2959 HTTP header fields in the request. Called with the name of an HTTP
2960 header field, returns its value. Capitalization and the use of
2961 hyphens versus underscores are not significant.
2962
2963 For example, all three of these examples are equivalent:
2964
2965 $requested_language = http('Accept-language');
2966 $requested_language = http('Accept_language');
2967 $requested_language = http('HTTP_ACCEPT_LANGUAGE');
2968
2969 https()
2970 The same as http(), but operates on the HTTPS environment variables
2971 present when the SSL protocol is in effect. Can be used to deter‐
2972 mine whether SSL is turned on.
2973
2975 NPH, or "no-parsed-header", scripts bypass the server completely by
2976 sending the complete HTTP header directly to the browser. This has
2977 slight performance benefits, but is of most use for taking advantage of
2978 HTTP extensions that are not directly supported by your server, such as
2979 server push and PICS headers.
2980
2981 Servers use a variety of conventions for designating CGI scripts as
2982 NPH. Many Unix servers look at the beginning of the script's name for
2983 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's Inter‐
2984 net Information Server, in contrast, try to decide whether a program is
2985 an NPH script by examining the first line of script output.
2986
2987 CGI.pm supports NPH scripts with a special NPH mode. When in this
2988 mode, CGI.pm will output the necessary extra header information when
2989 the header() and redirect() methods are called.
2990
2991 The Microsoft Internet Information Server requires NPH mode. As of
2992 version 2.30, CGI.pm will automatically detect when the script is run‐
2993 ning under IIS and put itself into this mode. You do not need to do
2994 this manually, although it won't hurt anything if you do. However,
2995 note that if you have applied Service Pack 6, much of the functionality
2996 of NPH scripts, including the ability to redirect while setting a
2997 cookie, b<do not work at all> on IIS without a special patch from Mi‐
2998 crosoft. See http://support.microsoft.com/support/kb/arti‐
2999 cles/Q280/3/41.ASP: Non-Parsed Headers Stripped From CGI Applications
3000 That Have nph- Prefix in Name.
3001
3002 In the use statement
3003 Simply add the "-nph" pragmato the list of symbols to be imported
3004 into your script:
3005
3006 use CGI qw(:standard -nph)
3007
3008 By calling the nph() method:
3009 Call nph() with a non-zero parameter at any point after using
3010 CGI.pm in your program.
3011
3012 CGI->nph(1)
3013
3014 By using -nph parameters
3015 in the header() and redirect() statements:
3016
3017 print header(-nph=>1);
3018
3020 CGI.pm provides four simple functions for producing multipart documents
3021 of the type needed to implement server push. These functions were gra‐
3022 ciously provided by Ed Jordan <ed@fidalgo.net>. To import these into
3023 your namespace, you must import the ":push" set. You are also advised
3024 to put the script into NPH mode and to set $⎪ to 1 to avoid buffering
3025 problems.
3026
3027 Here is a simple script that demonstrates server push:
3028
3029 #!/usr/local/bin/perl
3030 use CGI qw/:push -nph/;
3031 $⎪ = 1;
3032 print multipart_init(-boundary=>'----here we go!');
3033 foreach (0 .. 4) {
3034 print multipart_start(-type=>'text/plain'),
3035 "The current time is ",scalar(localtime),"\n";
3036 if ($_ < 4) {
3037 print multipart_end;
3038 } else {
3039 print multipart_final;
3040 }
3041 sleep 1;
3042 }
3043
3044 This script initializes server push by calling multipart_init(). It
3045 then enters a loop in which it begins a new multipart section by call‐
3046 ing multipart_start(), prints the current local time, and ends a multi‐
3047 part section with multipart_end(). It then sleeps a second, and begins
3048 again. On the final iteration, it ends the multipart section with mul‐
3049 tipart_final() rather than with multipart_end().
3050
3051 multipart_init()
3052 multipart_init(-boundary=>$boundary);
3053
3054 Initialize the multipart system. The -boundary argument specifies
3055 what MIME boundary string to use to separate parts of the document.
3056 If not provided, CGI.pm chooses a reasonable boundary for you.
3057
3058 multipart_start()
3059 multipart_start(-type=>$type)
3060
3061 Start a new part of the multipart document using the specified MIME
3062 type. If not specified, text/html is assumed.
3063
3064 multipart_end()
3065 multipart_end()
3066
3067 End a part. You must remember to call multipart_end() once for
3068 each multipart_start(), except at the end of the last part of the
3069 multipart document when multipart_final() should be called instead
3070 of multipart_end().
3071
3072 multipart_final()
3073 multipart_final()
3074
3075 End all parts. You should call multipart_final() rather than mul‐
3076 tipart_end() at the end of the last part of the multipart document.
3077
3078 Users interested in server push applications should also have a look at
3079 the CGI::Push module.
3080
3081 Only Netscape Navigator supports server push. Internet Explorer
3082 browsers do not.
3083
3085 A potential problem with CGI.pm is that, by default, it attempts to
3086 process form POSTings no matter how large they are. A wily hacker
3087 could attack your site by sending a CGI script a huge POST of many
3088 megabytes. CGI.pm will attempt to read the entire POST into a vari‐
3089 able, growing hugely in size until it runs out of memory. While the
3090 script attempts to allocate the memory the system may slow down dramat‐
3091 ically. This is a form of denial of service attack.
3092
3093 Another possible attack is for the remote user to force CGI.pm to
3094 accept a huge file upload. CGI.pm will accept the upload and store it
3095 in a temporary directory even if your script doesn't expect to receive
3096 an uploaded file. CGI.pm will delete the file automatically when it
3097 terminates, but in the meantime the remote user may have filled up the
3098 server's disk space, causing problems for other programs.
3099
3100 The best way to avoid denial of service attacks is to limit the amount
3101 of memory, CPU time and disk space that CGI scripts can use. Some Web
3102 servers come with built-in facilities to accomplish this. In other
3103 cases, you can use the shell limit or ulimit commands to put ceilings
3104 on CGI resource usage.
3105
3106 CGI.pm also has some simple built-in protections against denial of ser‐
3107 vice attacks, but you must activate them before you can use them.
3108 These take the form of two global variables in the CGI name space:
3109
3110 $CGI::POST_MAX
3111 If set to a non-negative integer, this variable puts a ceiling on
3112 the size of POSTings, in bytes. If CGI.pm detects a POST that is
3113 greater than the ceiling, it will immediately exit with an error
3114 message. This value will affect both ordinary POSTs and multipart
3115 POSTs, meaning that it limits the maximum size of file uploads as
3116 well. You should set this to a reasonably high value, such as 1
3117 megabyte.
3118
3119 $CGI::DISABLE_UPLOADS
3120 If set to a non-zero value, this will disable file uploads com‐
3121 pletely. Other fill-out form values will work as usual.
3122
3123 You can use these variables in either of two ways.
3124
3125 1. On a script-by-script basis
3126 Set the variable at the top of the script, right after the "use"
3127 statement:
3128
3129 use CGI qw/:standard/;
3130 use CGI::Carp 'fatalsToBrowser';
3131 $CGI::POST_MAX=1024 * 100; # max 100K posts
3132 $CGI::DISABLE_UPLOADS = 1; # no uploads
3133
3134 2. Globally for all scripts
3135 Open up CGI.pm, find the definitions for $POST_MAX and $DIS‐
3136 ABLE_UPLOADS, and set them to the desired values. You'll find them
3137 towards the top of the file in a subroutine named initialize_glob‐
3138 als().
3139
3140 An attempt to send a POST larger than $POST_MAX bytes will cause
3141 param() to return an empty CGI parameter list. You can test for this
3142 event by checking cgi_error(), either after you create the CGI object
3143 or, if you are using the function-oriented interface, call <param()>
3144 for the first time. If the POST was intercepted, then cgi_error() will
3145 return the message "413 POST too large".
3146
3147 This error message is actually defined by the HTTP protocol, and is
3148 designed to be returned to the browser as the CGI script's status
3149 code. For example:
3150
3151 $uploaded_file = param('upload');
3152 if (!$uploaded_file && cgi_error()) {
3153 print header(-status=>cgi_error());
3154 exit 0;
3155 }
3156
3157 However it isn't clear that any browser currently knows what to do with
3158 this status code. It might be better just to create an HTML page that
3159 warns the user of the problem.
3160
3162 To make it easier to port existing programs that use cgi-lib.pl the
3163 compatibility routine "ReadParse" is provided. Porting is simple:
3164
3165 OLD VERSION
3166 require "cgi-lib.pl";
3167 &ReadParse;
3168 print "The value of the antique is $in{antique}.\n";
3169
3170 NEW VERSION
3171 use CGI;
3172 CGI::ReadParse();
3173 print "The value of the antique is $in{antique}.\n";
3174
3175 CGI.pm's ReadParse() routine creates a tied variable named %in, which
3176 can be accessed to obtain the query variables. Like ReadParse, you can
3177 also provide your own variable. Infrequently used features of Read‐
3178 Parse, such as the creation of @in and $in variables, are not sup‐
3179 ported.
3180
3181 Once you use ReadParse, you can retrieve the query object itself this
3182 way:
3183
3184 $q = $in{CGI};
3185 print textfield(-name=>'wow',
3186 -value=>'does this really work?');
3187
3188 This allows you to start using the more interesting features of CGI.pm
3189 without rewriting your old scripts from scratch.
3190
3192 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
3193
3194 This library is free software; you can redistribute it and/or modify it
3195 under the same terms as Perl itself.
3196
3197 Address bug reports and comments to: lstein@cshl.org. When sending bug
3198 reports, please provide the version of CGI.pm, the version of Perl, the
3199 name and version of your Web server, and the name and version of the
3200 operating system you are using. If the problem is even remotely
3201 browser dependent, please provide information about the affected brow‐
3202 ers as well.
3203
3205 Thanks very much to:
3206
3207 Matt Heffron (heffron@falstaff.css.beckman.com)
3208 James Taylor (james.taylor@srs.gov)
3209 Scott Anguish <sanguish@digifix.com>
3210 Mike Jewell (mlj3u@virginia.edu)
3211 Timothy Shimmin (tes@kbs.citri.edu.au)
3212 Joergen Haegg (jh@axis.se)
3213 Laurent Delfosse (delfosse@delfosse.com)
3214 Richard Resnick (applepi1@aol.com)
3215 Craig Bishop (csb@barwonwater.vic.gov.au)
3216 Tony Curtis (tc@vcpc.univie.ac.at)
3217 Tim Bunce (Tim.Bunce@ig.co.uk)
3218 Tom Christiansen (tchrist@convex.com)
3219 Andreas Koenig (k@franz.ww.TU-Berlin.DE)
3220 Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
3221 Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
3222 Stephen Dahmen (joyfire@inxpress.net)
3223 Ed Jordan (ed@fidalgo.net)
3224 David Alan Pisoni (david@cnation.com)
3225 Doug MacEachern (dougm@opengroup.org)
3226 Robin Houston (robin@oneworld.org)
3227 ...and many many more...
3228 for suggestions and bug fixes.
3229
3231 #!/usr/local/bin/perl
3232
3233 use CGI ':standard';
3234
3235 print header;
3236 print start_html("Example CGI.pm Form");
3237 print "<h1> Example CGI.pm Form</h1>\n";
3238 print_prompt();
3239 do_work();
3240 print_tail();
3241 print end_html;
3242
3243 sub print_prompt {
3244 print start_form;
3245 print "<em>What's your name?</em><br>";
3246 print textfield('name');
3247 print checkbox('Not my real name');
3248
3249 print "<p><em>Where can you find English Sparrows?</em><br>";
3250 print checkbox_group(
3251 -name=>'Sparrow locations',
3252 -values=>[England,France,Spain,Asia,Hoboken],
3253 -linebreak=>'yes',
3254 -defaults=>[England,Asia]);
3255
3256 print "<p><em>How far can they fly?</em><br>",
3257 radio_group(
3258 -name=>'how far',
3259 -values=>['10 ft','1 mile','10 miles','real far'],
3260 -default=>'1 mile');
3261
3262 print "<p><em>What's your favorite color?</em> ";
3263 print popup_menu(-name=>'Color',
3264 -values=>['black','brown','red','yellow'],
3265 -default=>'red');
3266
3267 print hidden('Reference','Monty Python and the Holy Grail');
3268
3269 print "<p><em>What have you got there?</em><br>";
3270 print scrolling_list(
3271 -name=>'possessions',
3272 -values=>['A Coconut','A Grail','An Icon',
3273 'A Sword','A Ticket'],
3274 -size=>5,
3275 -multiple=>'true');
3276
3277 print "<p><em>Any parting comments?</em><br>";
3278 print textarea(-name=>'Comments',
3279 -rows=>10,
3280 -columns=>50);
3281
3282 print "<p>",reset;
3283 print submit('Action','Shout');
3284 print submit('Action','Scream');
3285 print endform;
3286 print "<hr>\n";
3287 }
3288
3289 sub do_work {
3290 my(@values,$key);
3291
3292 print "<h2>Here are the current settings in this form</h2>";
3293
3294 foreach $key (param) {
3295 print "<strong>$key</strong> -> ";
3296 @values = param($key);
3297 print join(", ",@values),"<br>\n";
3298 }
3299 }
3300
3301 sub print_tail {
3302 print <<END;
3303 <hr>
3304 <address>Lincoln D. Stein</address><br>
3305 <a href="/">Home Page</a>
3306 END
3307 }
3308
3310 Please report them.
3311
3313 CGI::Carp, CGI::Fast, CGI::Pretty
3314
3315
3316
3317perl v5.8.8 2001-09-21 CGI(3pm)