1CGI(3) User Contributed Perl Documentation CGI(3)
2
3
4
6 CGI - Handle Common Gateway Interface requests and responses
7
9 use strict;
10 use warnings;
11
12 use CGI;
13
14 # create a CGI object (query) for use
15 my $q = CGI->new;
16
17 # Process an HTTP request
18 my @values = $q->multi_param('form_field');
19 my $value = $q->param('param_name');
20
21 my $fh = $q->upload('file_field');
22
23 my $riddle = $q->cookie('riddle_name');
24 my %answers = $q->cookie('answers');
25
26 # Prepare various HTTP responses
27 print $q->header();
28 print $q->header('application/json');
29
30 my $cookie1 = $q->cookie(
31 -name => 'riddle_name',
32 -value => "The Sphynx's Question"
33 );
34
35 my $cookie2 = $q->cookie(
36 -name => 'answers',
37 -value => \%answers
38 );
39
40 print $q->header(
41 -type => 'image/gif',
42 -expires => '+3d',
43 -cookie => [ $cookie1,$cookie2 ]
44 );
45
46 print $q->redirect('http://somewhere.else/in/movie/land');
47
49 CGI.pm is a stable, complete and mature solution for processing and
50 preparing HTTP requests and responses. Major features including
51 processing form submissions, file uploads, reading and writing cookies,
52 query string generation and manipulation, and processing and preparing
53 HTTP headers.
54
55 CGI.pm performs very well in a vanilla CGI.pm environment and also
56 comes with built-in support for mod_perl and mod_perl2 as well as
57 FastCGI.
58
59 It has the benefit of having developed and refined over 20 years with
60 input from dozens of contributors and being deployed on thousands of
61 websites. CGI.pm was included in the perl distribution from perl v5.4
62 to v5.20, however is has now been removed from the perl core...
63
65 <http://perl5.git.perl.org/perl.git/commitdiff/e9fa5a80>
66
67 If you upgrade to a new version of perl or if you rely on a system or
68 vendor perl and get an updated version of perl through a system update,
69 then you will have to install CGI.pm yourself with cpan/cpanm/a vendor
70 package/manually. To make this a little easier the CGI::Fast module has
71 been split into its own distribution, meaning you do not need access to
72 a compiler to install CGI.pm
73
74 The rationale for this decision is that CGI.pm is no longer considered
75 good practice for developing web applications, including quick
76 prototyping and small web scripts. There are far better, cleaner,
77 quicker, easier, safer, more scalable, more extensible, more modern
78 alternatives available at this point in time. These will be documented
79 with CGI::Alternatives.
80
81 For more discussion on the removal of CGI.pm from core please see:
82
83 <http://www.nntp.perl.org/group/perl.perl5.porters/2013/05/msg202130.html>
84
85 Note that the v4 releases of CGI.pm will retain back compatibility as
86 much as possible, however you may need to make some minor changes to
87 your code if you are using deprecated methods or some of the more
88 obscure features of the module. If you plan to upgrade to v4.00 and
89 beyond you should read the Changes file for more information and test
90 your code against CGI.pm before deploying it.
91
93 All HTML generation functions within CGI.pm are no longer being
94 maintained. Any issues, bugs, or patches will be rejected unless they
95 relate to fundamentally broken page rendering.
96
97 The rationale for this is that the HTML generation functions of CGI.pm
98 are an obfuscation at best and a maintenance nightmare at worst. You
99 should be using a template engine for better separation of concerns.
100 See CGI::Alternatives for an example of using CGI.pm with the
101 Template::Toolkit module.
102
103 These functions, and perldoc for them, are considered deprecated, they
104 are no longer being maintained and no fixes or features for them will
105 be accepted. They will, however, continue to exist in CGI.pm without
106 any deprecation warnings ("soft" deprecation) so you can continue to
107 use them if you really want to. All documentation for these functions
108 has been moved to CGI::HTML::Functions.
109
111 There are two styles of programming with CGI.pm, an object-oriented
112 (OO) style and a function-oriented style. You are recommended to use
113 the OO style as CGI.pm will create an internal default object when the
114 functions are called procedurally and you will not have to worry about
115 method names clashing with perl builtins.
116
117 In the object-oriented style you create one or more CGI objects and
118 then use object methods to create the various elements of the page.
119 Each CGI object starts out with the list of named parameters that were
120 passed to your CGI script by the server. You can modify the objects,
121 save them to a file or database and recreate them. Because each object
122 corresponds to the "state" of the CGI script, and because each object's
123 parameter list is independent of the others, this allows you to save
124 the state of the script and restore it later.
125
126 For example, using the object oriented style:
127
128 #!/usr/bin/env perl
129
130 use strict;
131 use warnings;
132
133 use CGI; # load CGI routines
134
135 my $q = CGI->new; # create new CGI object
136 print $q->header; # create the HTTP header
137
138 In the function-oriented style, there is one default CGI object that
139 you rarely deal with directly. Instead you just call functions to
140 retrieve CGI parameters, manage cookies, and so on. The following
141 example is identical to above, in terms of output, but uses the
142 function-oriented interface. The main differences are that we now need
143 to import a set of functions into our name space (usually the
144 "standard" functions), and we don't need to create the CGI object.
145
146 #!/usr/bin/env perl
147
148 use strict;
149 use warnings;
150
151 use CGI qw/:standard/; # load standard CGI routines
152 print header(); # create the HTTP header
153
154 The examples in this document mainly use the object-oriented style. See
155 HOW TO IMPORT FUNCTIONS for important information on function-oriented
156 programming in CGI.pm
157
158 Calling CGI.pm routines
159 Most CGI.pm routines accept several arguments, sometimes as many as 20
160 optional ones! To simplify this interface, all routines use a named
161 argument calling style that looks like this:
162
163 print $q->header(
164 -type => 'image/gif',
165 -expires => '+3d',
166 );
167
168 Each argument name is preceded by a dash. Neither case nor order
169 matters in the argument list: -type, -Type, and -TYPE are all
170 acceptable. In fact, only the first argument needs to begin with a
171 dash. If a dash is present in the first argument CGI.pm assumes dashes
172 for the subsequent ones.
173
174 Several routines are commonly called with just one argument. In the
175 case of these routines you can provide the single argument without an
176 argument name. header() happens to be one of these routines. In this
177 case, the single argument is the document type.
178
179 print $q->header('text/html');
180
181 Other such routines are documented below.
182
183 Sometimes named arguments expect a scalar, sometimes a reference to an
184 array, and sometimes a reference to a hash. Often, you can pass any
185 type of argument and the routine will do whatever is most appropriate.
186 For example, the param() routine is used to set a CGI parameter to a
187 single or a multi-valued value. The two cases are shown below:
188
189 $q->param(
190 -name => 'veggie',
191 -value => 'tomato',
192 );
193
194 $q->param(
195 -name => 'veggie',
196 -value => [ qw/tomato tomahto potato potahto/ ],
197 );
198
199 Many routines will do something useful with a named argument that it
200 doesn't recognize. For example, you can produce non-standard HTTP
201 header fields by providing them as named arguments:
202
203 print $q->header(
204 -type => 'text/html',
205 -cost => 'Three smackers',
206 -annoyance_level => 'high',
207 -complaints_to => 'bit bucket',
208 );
209
210 This will produce the following nonstandard HTTP header:
211
212 HTTP/1.0 200 OK
213 Cost: Three smackers
214 Annoyance-level: high
215 Complaints-to: bit bucket
216 Content-type: text/html
217
218 Notice the way that underscores are translated automatically into
219 hyphens.
220
221 Creating a new query object (object-oriented style)
222 my $q = CGI->new;
223
224 This will parse the input (from POST, GET and DELETE methods) and store
225 it into a perl5 object called $q. Note that because the input parsing
226 happens at object instantiation you have to set any CGI package
227 variables that control parsing before you call CGI->new.
228
229 Any filehandles from file uploads will have their position reset to the
230 beginning of the file.
231
232 Creating a new query object from an input file
233 my $q = CGI->new( $input_filehandle );
234
235 If you provide a file handle to the new() method, it will read
236 parameters from the file (or STDIN, or whatever). The file can be in
237 any of the forms describing below under debugging (i.e. a series of
238 newline delimited TAG=VALUE pairs will work). Conveniently, this type
239 of file is created by the save() method (see below). Multiple records
240 can be saved and restored.
241
242 Perl purists will be pleased to know that this syntax accepts
243 references to file handles, or even references to filehandle globs,
244 which is the "official" way to pass a filehandle. You can also
245 initialize the CGI object with a FileHandle or IO::File object.
246
247 If you are using the function-oriented interface and want to initialize
248 CGI state from a file handle, the way to do this is with
249 restore_parameters(). This will (re)initialize the default CGI object
250 from the indicated file handle.
251
252 open( my $in_fh,'<',"test.in") || die "Couldn't open test.in for read: $!";
253 restore_parameters( $in_fh );
254 close( $in_fh );
255
256 You can also initialize the query object from a hash reference:
257
258 my $q = CGI->new( {
259 'dinosaur' => 'barney',
260 'song' => 'I love you',
261 'friends' => [ qw/ Jessica George Nancy / ]
262 } );
263
264 or from a properly formatted, URL-escaped query string:
265
266 my $q = CGI->new('dinosaur=barney&color=purple');
267
268 or from a previously existing CGI object (currently this clones the
269 parameter list, but none of the other object-specific fields, such as
270 autoescaping):
271
272 my $old_query = CGI->new;
273 my $new_query = CGI->new($old_query);
274
275 To create an empty query, initialize it from an empty string or hash:
276
277 my $empty_query = CGI->new("");
278
279 -or-
280
281 my $empty_query = CGI->new({});
282
283 Fetching a list of keywords from the query
284 my @keywords = $q->keywords
285
286 If the script was invoked as the result of an ISINDEX search, the
287 parsed keywords can be obtained as an array using the keywords()
288 method.
289
290 Fetching the names of all the parameters passed to your script
291 my @names = $q->multi_param
292
293 my @names = $q->param
294
295 If the script was invoked with a parameter list (e.g.
296 "name1=value1&name2=value2&name3=value3"), the param() / multi_param()
297 methods will return the parameter names as a list. If the script was
298 invoked as an ISINDEX script and contains a string without ampersands
299 (e.g. "value1+value2+value3"), there will be a single parameter named
300 "keywords" containing the "+"-delimited keywords.
301
302 The array of parameter names returned will be in the same order as they
303 were submitted by the browser. Usually this order is the same as the
304 order in which the parameters are defined in the form (however, this
305 isn't part of the spec, and so isn't guaranteed).
306
307 Fetching the value or values of a single named parameter
308 my @values = $q->multi_param('foo');
309
310 -or-
311
312 my $value = $q->param('foo');
313
314 -or-
315
316 my @values = $q->param('foo'); # list context, discouraged and will raise
317 # a warning (use ->multi_param instead)
318
319 Pass the param() / multi_param() method a single argument to fetch the
320 value of the named parameter. When calling param() If the parameter is
321 multivalued (e.g. from multiple selections in a scrolling list), you
322 can ask to receive an array. Otherwise the method will return the first
323 value.
324
325 Warning - calling param() in list context can lead to vulnerabilities
326 if you do not sanitise user input as it is possible to inject other
327 param keys and values into your code. This is why the multi_param()
328 method exists, to make it clear that a list is being returned, note
329 that param() can still be called in list context and will return a list
330 for back compatibility.
331
332 The following code is an example of a vulnerability as the call to
333 param will be evaluated in list context and thus possibly inject extra
334 keys and values into the hash:
335
336 my %user_info = (
337 id => 1,
338 name => $q->param('name'),
339 );
340
341 The fix for the above is to force scalar context on the call to ->param
342 by prefixing it with "scalar"
343
344 name => scalar $q->param('name'),
345
346 If you call param() in list context with an argument a warning will be
347 raised by CGI.pm, you can disable this warning by setting
348 $CGI::LIST_CONTEXT_WARN to 0 or by using the multi_param() method
349 instead
350
351 If a value is not given in the query string, as in the queries
352 "name1=&name2=", it will be returned as an empty string.
353
354 If the parameter does not exist at all, then param() will return undef
355 in scalar context, and the empty list in a list context.
356
357 Setting the value(s) of a named parameter
358 $q->param('foo','an','array','of','values');
359
360 This sets the value for the named parameter 'foo' to an array of
361 values. This is one way to change the value of a field AFTER the script
362 has been invoked once before.
363
364 param() also recognizes a named parameter style of calling described in
365 more detail later:
366
367 $q->param(
368 -name => 'foo',
369 -values => ['an','array','of','values'],
370 );
371
372 -or-
373
374 $q->param(
375 -name => 'foo',
376 -value => 'the value',
377 );
378
379 Appending additional values to a named parameter
380 $q->append(
381 -name =>'foo',
382 -values =>['yet','more','values'],
383 );
384
385 This adds a value or list of values to the named parameter. The values
386 are appended to the end of the parameter if it already exists.
387 Otherwise the parameter is created. Note that this method only
388 recognizes the named argument calling syntax.
389
390 Importing all parameters into a namespace
391 $q->import_names('R');
392
393 This creates a series of variables in the 'R' namespace. For example,
394 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will
395 appear. If no namespace is given, this method will assume 'Q'. WARNING:
396 don't import anything into 'main'; this is a major security risk!
397
398 NOTE 1: Variable names are transformed as necessary into legal perl
399 variable names. All non-legal characters are transformed into
400 underscores. If you need to keep the original names, you should use the
401 param() method instead to access CGI variables by name.
402
403 In fact, you should probably not use this method at all given the above
404 caveats and security risks.
405
406 Deleting a parameter completely
407 $q->delete('foo','bar','baz');
408
409 This completely clears a list of parameters. It sometimes useful for
410 resetting parameters that you don't want passed down between script
411 invocations.
412
413 If you are using the function call interface, use "Delete()" instead to
414 avoid conflicts with perl's built-in delete operator.
415
416 Deleting all parameters
417 $q->delete_all();
418
419 This clears the CGI object completely. It might be useful to ensure
420 that all the defaults are taken when you create a fill-out form.
421
422 Use Delete_all() instead if you are using the function call interface.
423
424 Handling non-urlencoded arguments
425 If POSTed data is not of type application/x-www-form-urlencoded or
426 multipart/form-data, then the POSTed data will not be processed, but
427 instead be returned as-is in a parameter named POSTDATA. To retrieve
428 it, use code like this:
429
430 my $data = $q->param('POSTDATA');
431
432 Likewise if PUTed and PATCHed data can be retrieved with code like
433 this:
434
435 my $data = $q->param('PUTDATA');
436
437 my $data = $q->param('PATCHDATA');
438
439 (If you don't know what the preceding means, worry not. It only affects
440 people trying to use CGI for XML processing and other specialized
441 tasks)
442
443 PUTDATA/POSTDATA/PATCHDATA are also available via upload_hook, and as
444 file uploads via "-putdata_upload" option.
445
446 Direct access to the parameter list
447 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
448 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
449
450 If you need access to the parameter list in a way that isn't covered by
451 the methods given in the previous sections, you can obtain a direct
452 reference to it by calling the param_fetch() method with the name of
453 the parameter. This will return an array reference to the named
454 parameter, which you then can manipulate in any way you like.
455
456 You can also use a named argument style using the -name argument.
457
458 Fetching the parameter list as a hash
459 my $params = $q->Vars;
460 print $params->{'address'};
461 my @foo = split("\0",$params->{'foo'});
462 my %params = $q->Vars;
463
464 use CGI ':cgi-lib';
465 my $params = Vars();
466
467 Many people want to fetch the entire parameter list as a hash in which
468 the keys are the names of the CGI parameters, and the values are the
469 parameters' values. The Vars() method does this. Called in a scalar
470 context, it returns the parameter list as a tied hash reference.
471 Changing a key changes the value of the parameter in the underlying CGI
472 parameter list. Called in a list context, it returns the parameter list
473 as an ordinary hash. This allows you to read the contents of the
474 parameter list, but not to change it.
475
476 When using this, the thing you must watch out for are multivalued CGI
477 parameters. Because a hash cannot distinguish between scalar and list
478 context, multivalued parameters will be returned as a packed string,
479 separated by the "\0" (null) character. You must split this packed
480 string in order to get at the individual values. This is the convention
481 introduced long ago by Steve Brenner in his cgi-lib.pl module for perl
482 version 4, and may be replaced in future versions with array
483 references.
484
485 If you wish to use Vars() as a function, import the :cgi-lib set of
486 function calls (also see the section on CGI-LIB compatibility).
487
488 Saving the state of the script to a file
489 $q->save(\*FILEHANDLE)
490
491 This will write the current state of the form to the provided
492 filehandle. You can read it back in by providing a filehandle to the
493 new() method. Note that the filehandle can be a file, a pipe, or
494 whatever.
495
496 The format of the saved file is:
497
498 NAME1=VALUE1
499 NAME1=VALUE1'
500 NAME2=VALUE2
501 NAME3=VALUE3
502 =
503
504 Both name and value are URL escaped. Multi-valued CGI parameters are
505 represented as repeated names. A session record is delimited by a
506 single = symbol. You can write out multiple records and read them back
507 in with several calls to new. You can do this across several sessions
508 by opening the file in append mode, allowing you to create primitive
509 guest books, or to keep a history of users' queries. Here's a short
510 example of creating multiple session records:
511
512 use strict;
513 use warnings;
514 use CGI;
515
516 open (my $out_fh,'>>','test.out') || die "Can't open test.out: $!";
517 my $records = 5;
518 for ( 0 .. $records ) {
519 my $q = CGI->new;
520 $q->param( -name => 'counter',-value => $_ );
521 $q->save( $out_fh );
522 }
523 close( $out_fh );
524
525 # reopen for reading
526 open (my $in_fh,'<','test.out') || die "Can't open test.out: $!";
527 while (!eof($in_fh)) {
528 my $q = CGI->new($in_fh);
529 print $q->param('counter'),"\n";
530 }
531
532 The file format used for save/restore is identical to that used by the
533 Whitehead Genome Center's data exchange format "Boulderio", and can be
534 manipulated and even databased using Boulderio utilities. See Boulder
535 for further details.
536
537 If you wish to use this method from the function-oriented (non-OO)
538 interface, the exported name for this method is save_parameters().
539
540 Retrieving cgi errors
541 Errors can occur while processing user input, particularly when
542 processing uploaded files. When these errors occur, CGI will stop
543 processing and return an empty parameter list. You can test for the
544 existence and nature of errors using the cgi_error() function. The
545 error messages are formatted as HTTP status codes. You can either
546 incorporate the error text into a page, or use it as the value of the
547 HTTP status:
548
549 if ( my $error = $q->cgi_error ) {
550 print $q->header( -status => $error );
551 print "Error: $error";
552 exit 0;
553 }
554
555 When using the function-oriented interface (see the next section),
556 errors may only occur the first time you call param(). Be ready for
557 this!
558
559 Using the function-oriented interface
560 To use the function-oriented interface, you must specify which CGI.pm
561 routines or sets of routines to import into your script's namespace.
562 There is a small overhead associated with this importation, but it
563 isn't much.
564
565 use strict;
566 use warnings;
567
568 use CGI qw/ list of methods /;
569
570 The listed methods will be imported into the current package; you can
571 call them directly without creating a CGI object first. This example
572 shows how to import the param() and header() methods, and then use them
573 directly:
574
575 use strict;
576 use warnings;
577
578 use CGI qw/ param header /;
579 print header('text/plain');
580 my $zipcode = param('zipcode');
581
582 More frequently, you'll import common sets of functions by referring to
583 the groups by name. All function sets are preceded with a ":" character
584 as in ":cgi" (for CGI protocol handling methods).
585
586 Here is a list of the function sets you can import:
587
588 :cgi
589 Import all CGI-handling methods, such as param(), path_info() and
590 the like.
591
592 :all
593 Import all the available methods. For the full list, see the CGI.pm
594 code, where the variable %EXPORT_TAGS is defined. (N.B. the
595 :cgi-lib imports will not be included in the :all import, you will
596 have to import :cgi-lib to get those)
597
598 Note that in the interests of execution speed CGI.pm does not use the
599 standard Exporter syntax for specifying load symbols. This may change
600 in the future.
601
602 Pragmas
603 In addition to the function sets, there are a number of pragmas that
604 you can import. Pragmas, which are always preceded by a hyphen, change
605 the way that CGI.pm functions in various ways. Pragmas, function sets,
606 and individual functions can all be imported in the same use() line.
607 For example, the following use statement imports the cgi set of
608 functions and enables debugging mode (pragma -debug):
609
610 use strict;
611 use warninigs;
612 use CGI qw/ :cgi -debug /;
613
614 The current list of pragmas is as follows:
615
616 -no_undef_params
617 This keeps CGI.pm from including undef params in the parameter
618 list.
619
620 -utf8
621 This makes CGI.pm treat all parameters as text strings rather than
622 binary strings (see perlunitut for the distinction), assuming UTF-8
623 for the encoding.
624
625 CGI.pm does the decoding from the UTF-8 encoded input data,
626 restricting this decoding to input text as distinct from binary
627 upload data which are left untouched. Therefore, a ':utf8' layer
628 must not be used on STDIN.
629
630 If you do not use this option you can manually select which fields
631 are expected to return utf-8 strings and convert them using code
632 like this:
633
634 use strict;
635 use warnings;
636
637 use CGI;
638 use Encode qw/ decode /;
639
640 my $cgi = CGI->new;
641 my $param = $cgi->param('foo');
642 $param = decode( 'UTF-8',$param );
643
644 -putdata_upload / -postdata_upload / -patchdata_upload
645 Makes "$cgi->param('PUTDATA');", "$cgi->param('PATCHDATA');", and
646 "$cgi->param('POSTDATA');" act like file uploads named PUTDATA,
647 PATCHDATA, and POSTDATA. See "Handling non-urlencoded arguments"
648 and "Processing a file upload field" PUTDATA/POSTDATA/PATCHDATA are
649 also available via upload_hook.
650
651 -nph
652 This makes CGI.pm produce a header appropriate for an NPH (no
653 parsed header) script. You may need to do other things as well to
654 tell the server that the script is NPH. See the discussion of NPH
655 scripts below.
656
657 -newstyle_urls
658 Separate the name=value pairs in CGI parameter query strings with
659 semicolons rather than ampersands. For example:
660
661 ?name=fred;age=24;favorite_color=3
662
663 Semicolon-delimited query strings are always accepted, and will be
664 emitted by self_url() and query_string(). newstyle_urls became the
665 default in version 2.64.
666
667 -oldstyle_urls
668 Separate the name=value pairs in CGI parameter query strings with
669 ampersands rather than semicolons. This is no longer the default.
670
671 -no_debug
672 This turns off the command-line processing features. If you want to
673 run a CGI.pm script from the command line, and you don't want it to
674 read CGI parameters from the command line or STDIN, then use this
675 pragma:
676
677 use CGI qw/ -no_debug :standard /;
678
679 -debug
680 This turns on full debugging. In addition to reading CGI arguments
681 from the command-line processing, CGI.pm will pause and try to read
682 arguments from STDIN, producing the message "(offline mode: enter
683 name=value pairs on standard input)" features.
684
685 See the section on debugging for more details.
686
688 Most of CGI.pm's functions deal with creating documents on the fly.
689 Generally you will produce the HTTP header first, followed by the
690 document itself. CGI.pm provides functions for generating HTTP headers
691 of various types.
692
693 Each of these functions produces a fragment of HTTP which you can print
694 out directly so that it is processed by the browser, appended to a
695 string, or saved to a file for later use.
696
697 Creating a standard http header
698 Normally the first thing you will do in any CGI script is print out an
699 HTTP header. This tells the browser what type of document to expect,
700 and gives other optional information, such as the language, expiration
701 date, and whether to cache the document. The header can also be
702 manipulated for special purposes, such as server push and pay per view
703 pages.
704
705 use strict;
706 use warnings;
707
708 use CGI;
709
710 my $cgi = CGI->new;
711
712 print $cgi->header;
713
714 -or-
715
716 print $cgi->header('image/gif');
717
718 -or-
719
720 print $cgi->header('text/html','204 No response');
721
722 -or-
723
724 print $cgi->header(
725 -type => 'image/gif',
726 -nph => 1,
727 -status => '402 Payment required',
728 -expires => '+3d',
729 -cookie => $cookie,
730 -charset => 'utf-8',
731 -attachment => 'foo.gif',
732 -Cost => '$2.00'
733 );
734
735 header() returns the Content-type: header. You can provide your own
736 MIME type if you choose, otherwise it defaults to text/html. An
737 optional second parameter specifies the status code and a human-
738 readable message. For example, you can specify 204, "No response" to
739 create a script that tells the browser to do nothing at all. Note that
740 RFC 2616 expects the human-readable phase to be there as well as the
741 numeric status code.
742
743 The last example shows the named argument style for passing arguments
744 to the CGI methods using named parameters. Recognized parameters are
745 -type, -status, -expires, and -cookie. Any other named parameters will
746 be stripped of their initial hyphens and turned into header fields,
747 allowing you to specify any HTTP header you desire. Internal
748 underscores will be turned into hyphens:
749
750 print $cgi->header( -Content_length => 3002 );
751
752 Most browsers will not cache the output from CGI scripts. Every time
753 the browser reloads the page, the script is invoked anew. You can
754 change this behavior with the -expires parameter. When you specify an
755 absolute or relative expiration interval with this parameter, some
756 browsers and proxy servers will cache the script's output until the
757 indicated expiration date. The following forms are all valid for the
758 -expires field:
759
760 +30s 30 seconds from now
761 +10m ten minutes from now
762 +1h one hour from now
763 -1d yesterday (i.e. "ASAP!")
764 now immediately
765 +3M in three months
766 +10y in ten years time
767 Thursday, 25-Apr-2018 00:40:33 GMT at the indicated time & date
768
769 The -cookie parameter generates a header that tells the browser to
770 provide a "magic cookie" during all subsequent transactions with your
771 script. Some cookies have a special format that includes interesting
772 attributes such as expiration time. Use the cookie() method to create
773 and retrieve session cookies.
774
775 The -nph parameter, if set to a true value, will issue the correct
776 headers to work with a NPH (no-parse-header) script. This is important
777 to use with certain servers that expect all their scripts to be NPH.
778
779 The -charset parameter can be used to control the character set sent to
780 the browser. If not provided, defaults to ISO-8859-1. As a side effect,
781 this sets the charset() method as well. Note that the default being
782 ISO-8859-1 may not make sense for all content types, e.g.:
783
784 Content-Type: image/gif; charset=ISO-8859-1
785
786 In the above case you need to pass -charset => '' to prevent the
787 default being used.
788
789 The -attachment parameter can be used to turn the page into an
790 attachment. Instead of displaying the page, some browsers will prompt
791 the user to save it to disk. The value of the argument is the suggested
792 name for the saved file. In order for this to work, you may have to set
793 the -type to "application/octet-stream".
794
795 The -p3p parameter will add a P3P tag to the outgoing header. The
796 parameter can be an arrayref or a space-delimited string of P3P tags.
797 For example:
798
799 print $cgi->header( -p3p => [ qw/ CAO DSP LAW CURa / ] );
800 print $cgi->header( -p3p => 'CAO DSP LAW CURa' );
801
802 In either case, the outgoing header will be formatted as:
803
804 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
805
806 CGI.pm will accept valid multi-line headers when each line is separated
807 with a CRLF value ("\r\n" on most platforms) followed by at least one
808 space. For example:
809
810 print $cgi->header( -ingredients => "ham\r\n\seggs\r\n\sbacon" );
811
812 Invalid multi-line header input will trigger in an exception. When
813 multi-line headers are received, CGI.pm will always output them back as
814 a single line, according to the folding rules of RFC 2616: the newlines
815 will be removed, while the white space remains.
816
817 Generating a redirection header
818 print $q->redirect( 'http://somewhere.else/in/movie/land' );
819
820 Sometimes you don't want to produce a document yourself, but simply
821 redirect the browser elsewhere, perhaps choosing a URL based on the
822 time of day or the identity of the user.
823
824 The redirect() method redirects the browser to a different URL. If you
825 use redirection like this, you should not print out a header as well.
826
827 You are advised to use full URLs (absolute with respect to current URL
828 or even including the http: or ftp: part) in redirection requests as
829 relative URLs are resolved by the user agent of the client so may not
830 do what you want or expect them to do.
831
832 You can also use named arguments:
833
834 print $q->redirect(
835 -uri => 'http://somewhere.else/in/movie/land',
836 -nph => 1,
837 -status => '301 Moved Permanently'
838 );
839
840 All names arguments recognized by header() are also recognized by
841 redirect(). However, most HTTP headers, including those generated by
842 -cookie and -target, are ignored by the browser.
843
844 The -nph parameter, if set to a true value, will issue the correct
845 headers to work with a NPH (no-parse-header) script. This is important
846 to use with certain servers, such as Microsoft IIS, which expect all
847 their scripts to be NPH.
848
849 The -status parameter will set the status of the redirect. HTTP defines
850 several different possible redirection status codes, and the default if
851 not specified is 302, which means "moved temporarily." You may change
852 the status to another status code if you wish.
853
854 Note that the human-readable phrase is also expected to be present to
855 conform with RFC 2616, section 6.1.
856
857 Creating a self-referencing url that preserves state information
858 my $myself = $q->self_url;
859 print qq(<a href="$myself">I'm talking to myself.</a>);
860
861 self_url() will return a URL, that, when selected, will re-invoke this
862 script with all its state information intact. This is most useful when
863 you want to jump around within the document using internal anchors but
864 you don't want to disrupt the current contents of the form(s).
865 Something like this will do the trick:
866
867 my $myself = $q->self_url;
868 print "<a href=\"$myself#table1\">See table 1</a>";
869 print "<a href=\"$myself#table2\">See table 2</a>";
870 print "<a href=\"$myself#yourself\">See for yourself</a>";
871
872 If you want more control over what's returned, using the url() method
873 instead.
874
875 You can also retrieve a query string representation of the current
876 object state with query_string():
877
878 my $the_string = $q->query_string();
879
880 The behavior of calling query_string is currently undefined when the
881 HTTP method is something other than GET.
882
883 If you want to retrieved the query string as set in the webserver,
884 namely the environment variable, you can call env_query_string()
885
886 Obtaining the script's url
887 my $full_url = url();
888 my $full_url = url( -full =>1 ); # alternative syntax
889 my $relative_url = url( -relative => 1 );
890 my $absolute_url = url( -absolute =>1 );
891 my $url_with_path = url( -path_info => 1 );
892 my $url_path_qry = url( -path_info => 1, -query =>1 );
893 my $netloc = url( -base => 1 );
894
895 url() returns the script's URL in a variety of formats. Called without
896 any arguments, it returns the full form of the URL, including host name
897 and port number
898
899 http://your.host.com/path/to/script.cgi
900
901 You can modify this format with the following named arguments:
902
903 -absolute
904 If true, produce an absolute URL, e.g.
905
906 /path/to/script.cgi
907
908 -relative
909 Produce a relative URL. This is useful if you want to re-invoke
910 your script with different parameters. For example:
911
912 script.cgi
913
914 -full
915 Produce the full URL, exactly as if called without any arguments.
916 This overrides the -relative and -absolute arguments.
917
918 -path (-path_info)
919 Append the additional path information to the URL. This can be
920 combined with -full, -absolute or -relative. -path_info is provided
921 as a synonym.
922
923 -query (-query_string)
924 Append the query string to the URL. This can be combined with
925 -full, -absolute or -relative. -query_string is provided as a
926 synonym.
927
928 -base
929 Generate just the protocol and net location, as in
930 http://www.foo.com:8000
931
932 -rewrite
933 If Apache's mod_rewrite is turned on, then the script name and path
934 info probably won't match the request that the user sent. Set
935 -rewrite => 1 (default) to return URLs that match what the user
936 sent (the original request URI). Set -rewrite => 0 to return URLs
937 that match the URL after the mod_rewrite rules have run.
938
939 Mixing post and url parameters
940 my $color = url_param('color');
941
942 It is possible for a script to receive CGI parameters in the URL as
943 well as in the fill-out form by creating a form that POSTs to a URL
944 containing a query string (a "?" mark followed by arguments). The
945 param() method will always return the contents of the POSTed fill-out
946 form, ignoring the URL's query string. To retrieve URL parameters, call
947 the url_param() method. Use it in the same way as param(). The main
948 difference is that it allows you to read the parameters, but not set
949 them.
950
951 Under no circumstances will the contents of the URL query string
952 interfere with similarly-named CGI parameters in POSTed forms. If you
953 try to mix a URL query string with a form submitted with the GET
954 method, the results will not be what you expect.
955
956 If running from the command line, "url_param" will not pick up any
957 parameters given on the command line.
958
959 Processing a file upload field
960 Basics
961
962 When the form is processed, you can retrieve an IO::File compatible
963 handle for a file upload field like this:
964
965 use autodie;
966
967 # undef may be returned if it's not a valid file handle
968 if ( my $io_handle = $q->upload('field_name') ) {
969 open ( my $out_file,'>>','/usr/local/web/users/feedback' );
970 while ( my $bytesread = $io_handle->read($buffer,1024) ) {
971 print $out_file $buffer;
972 }
973 }
974
975 In a list context, upload() will return an array of filehandles. This
976 makes it possible to process forms that use the same name for multiple
977 upload fields.
978
979 If you want the entered file name for the file, you can just call
980 param():
981
982 my $filename = $q->param('field_name');
983
984 Different browsers will return slightly different things for the name.
985 Some browsers return the filename only. Others return the full path to
986 the file, using the path conventions of the user's machine. Regardless,
987 the name returned is always the name of the file on the user's machine,
988 and is unrelated to the name of the temporary file that CGI.pm creates
989 during upload spooling (see below).
990
991 When a file is uploaded the browser usually sends along some
992 information along with it in the format of headers. The information
993 usually includes the MIME content type. To retrieve this information,
994 call uploadInfo(). It returns a reference to a hash containing all the
995 document headers.
996
997 my $filehandle = $q->upload( 'uploaded_file' );
998 my $type = $q->uploadInfo( $filehandle )->{'Content-Type'};
999 if ( $type ne 'text/html' ) {
1000 die "HTML FILES ONLY!";
1001 }
1002
1003 Note that you must use ->upload or ->param to get the file-handle to
1004 pass into uploadInfo as internally this is represented as a File::Temp
1005 object (which is what will be returned by ->upload or ->param). When
1006 using ->Vars you will get the literal filename rather than the
1007 File::Temp object, which will not return anything when passed to
1008 uploadInfo. So don't use ->Vars.
1009
1010 If you are using a machine that recognizes "text" and "binary" data
1011 modes, be sure to understand when and how to use them (see the Camel
1012 book). Otherwise you may find that binary files are corrupted during
1013 file uploads.
1014
1015 Accessing the temp files directly
1016
1017 When processing an uploaded file, CGI.pm creates a temporary file on
1018 your hard disk and passes you a file handle to that file. After you are
1019 finished with the file handle, CGI.pm unlinks (deletes) the temporary
1020 file. If you need to you can access the temporary file directly. You
1021 can access the temp file for a file upload by passing the file name to
1022 the tmpFileName() method:
1023
1024 my $filehandle = $q->upload( 'uploaded_file' );
1025 my $tmpfilename = $q->tmpFileName( $filehandle );
1026
1027 As with ->uploadInfo, using the reference returned by ->upload or
1028 ->param is preferred, although unlike ->uploadInfo, plain filenames
1029 also work if possible for backwards compatibility.
1030
1031 The temporary file will be deleted automatically when your program
1032 exits unless you manually rename it or set $CGI::UNLINK_TMP_FILES to 0.
1033 On some operating systems (such as Windows NT), you will need to close
1034 the temporary file's filehandle before your program exits. Otherwise
1035 the attempt to delete the temporary file will fail.
1036
1037 Changes in temporary file handling (v4.05+)
1038
1039 CGI.pm had its temporary file handling significantly refactored, this
1040 logic is now all deferred to File::Temp (which is wrapped in a
1041 compatibility object, CGI::File::Temp - DO NOT USE THIS PACKAGE
1042 DIRECTLY). As a consequence the PRIVATE_TEMPFILES variable has been
1043 removed along with deprecation of the private_tempfiles routine and
1044 complete removal of the CGITempFile package. The
1045 $CGITempFile::TMPDIRECTORY is no longer used to set the temp directory,
1046 refer to the perldoc for File::Temp if you want to override the default
1047 settings in that package (the TMPDIR env variable is still available on
1048 some platforms). For Windows platforms the temporary directory order
1049 remains as before: TEMP > TMP > WINDIR ( > TMPDIR ) so if you have any
1050 of these in use in existing scripts they should still work.
1051
1052 The Fh package still exists but does nothing, the CGI::File::Temp class
1053 is a subclass of both File::Temp and the empty Fh package, so if you
1054 have any code that checks that the filehandle isa Fh this should still
1055 work.
1056
1057 When you get the internal file handle you will receive a File::Temp
1058 object, this should be transparent as File::Temp isa IO::Handle and isa
1059 IO::Seekable meaning it behaves as previously. If you are doing
1060 anything out of the ordinary with regards to temp files you should test
1061 your code before deploying this update and refer to the File::Temp
1062 documentation for more information.
1063
1064 Handling interrupted file uploads
1065
1066 There are occasionally problems involving parsing the uploaded file.
1067 This usually happens when the user presses "Stop" before the upload is
1068 finished. In this case, CGI.pm will return undef for the name of the
1069 uploaded file and set cgi_error() to the string "400 Bad request
1070 (malformed multipart POST)". This error message is designed so that you
1071 can incorporate it into a status code to be sent to the browser.
1072 Example:
1073
1074 my $file = $q->upload( 'uploaded_file' );
1075 if ( !$file && $q->cgi_error ) {
1076 print $q->header( -status => $q->cgi_error );
1077 exit 0;
1078 }
1079
1080 Progress bars for file uploads and avoiding temp files
1081
1082 CGI.pm gives you low-level access to file upload management through a
1083 file upload hook. You can use this feature to completely turn off the
1084 temp file storage of file uploads, or potentially write your own file
1085 upload progress meter.
1086
1087 This is much like the UPLOAD_HOOK facility available in
1088 Apache::Request, with the exception that the first argument to the
1089 callback is an Apache::Upload object, here it's the remote filename.
1090
1091 my $q = CGI->new( \&hook [,$data [,$use_tempfile]] );
1092
1093 sub hook {
1094 my ( $filename, $buffer, $bytes_read, $data ) = @_;
1095 print "Read $bytes_read bytes of $filename\n";
1096 }
1097
1098 The $data field is optional; it lets you pass configuration information
1099 (e.g. a database handle) to your hook callback.
1100
1101 The $use_tempfile field is a flag that lets you turn on and off
1102 CGI.pm's use of a temporary disk-based file during file upload. If you
1103 set this to a FALSE value (default true) then
1104 $q->param('uploaded_file') will no longer work, and the only way to get
1105 at the uploaded data is via the hook you provide.
1106
1107 If using the function-oriented interface, call the CGI::upload_hook()
1108 method before calling param() or any other CGI functions:
1109
1110 CGI::upload_hook( \&hook [,$data [,$use_tempfile]] );
1111
1112 This method is not exported by default. You will have to import it
1113 explicitly if you wish to use it without the CGI:: prefix.
1114
1115 Troubleshooting file uploads on Windows
1116
1117 If you are using CGI.pm on a Windows platform and find that binary
1118 files get slightly larger when uploaded but that text files remain the
1119 same, then you have forgotten to activate binary mode on the output
1120 filehandle. Be sure to call binmode() on any handle that you create to
1121 write the uploaded file to disk.
1122
1123 Older ways to process file uploads
1124
1125 This section is here for completeness. if you are building a new
1126 application with CGI.pm, you can skip it.
1127
1128 The original way to process file uploads with CGI.pm was to use
1129 param(). The value it returns has a dual nature as both a file name and
1130 a lightweight filehandle. This dual nature is problematic if you
1131 following the recommended practice of having "use strict" in your code.
1132 perl will complain when you try to use a string as a filehandle. More
1133 seriously, it is possible for the remote user to type garbage into the
1134 upload field, in which case what you get from param() is not a
1135 filehandle at all, but a string.
1136
1137 To solve this problem the upload() method was added, which always
1138 returns a lightweight filehandle. This generally works well, but will
1139 have trouble interoperating with some other modules because the file
1140 handle is not derived from IO::File. So that brings us to current
1141 recommendation given above, which is to call the handle() method on the
1142 file handle returned by upload(). That upgrades the handle to an
1143 IO::File. It's a big win for compatibility for a small penalty of
1144 loading IO::File the first time you call it.
1145
1147 CGI.pm has several methods that support cookies.
1148
1149 A cookie is a name=value pair much like the named parameters in a CGI
1150 query string. CGI scripts create one or more cookies and send them to
1151 the browser in the HTTP header. The browser maintains a list of cookies
1152 that belong to a particular Web server, and returns them to the CGI
1153 script during subsequent interactions.
1154
1155 In addition to the required name=value pair, each cookie has several
1156 optional attributes:
1157
1158 1. an expiration time
1159 This is a time/date string (in a special GMT format) that indicates
1160 when a cookie expires. The cookie will be saved and returned to
1161 your script until this expiration date is reached if the user exits
1162 the browser and restarts it. If an expiration date isn't specified,
1163 the cookie will remain active until the user quits the browser.
1164
1165 2. a domain
1166 This is a partial or complete domain name for which the cookie is
1167 valid. The browser will return the cookie to any host that matches
1168 the partial domain name. For example, if you specify a domain name
1169 of ".capricorn.com", then the browser will return the cookie to Web
1170 servers running on any of the machines "www.capricorn.com",
1171 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
1172 must contain at least two periods to prevent attempts to match on
1173 top level domains like ".edu". If no domain is specified, then the
1174 browser will only return the cookie to servers on the host the
1175 cookie originated from.
1176
1177 3. a path
1178 If you provide a cookie path attribute, the browser will check it
1179 against your script's URL before returning the cookie. For example,
1180 if you specify the path "/cgi-bin", then the cookie will be
1181 returned to each of the scripts "/cgi-bin/tally.pl",
1182 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
1183 but not to the script "/cgi-private/site_admin.pl". By default,
1184 path is set to "/", which causes the cookie to be sent to any CGI
1185 script on your site.
1186
1187 4. a "secure" flag
1188 If the "secure" attribute is set, the cookie will only be sent to
1189 your script if the CGI request is occurring on a secure channel,
1190 such as SSL.
1191
1192 The interface to HTTP cookies is the cookie() method:
1193
1194 my $cookie = $q->cookie(
1195 -name => 'sessionID',
1196 -value => 'xyzzy',
1197 -expires => '+1h',
1198 -path => '/cgi-bin/database',
1199 -domain => '.capricorn.org',
1200 -secure => 1
1201 );
1202
1203 print $q->header( -cookie => $cookie );
1204
1205 cookie() creates a new cookie. Its parameters include:
1206
1207 -name
1208 The name of the cookie (required). This can be any string at all.
1209 Although browsers limit their cookie names to non-whitespace
1210 alphanumeric characters, CGI.pm removes this restriction by
1211 escaping and unescaping cookies behind the scenes.
1212
1213 -value
1214 The value of the cookie. This can be any scalar value, array
1215 reference, or even hash reference. For example, you can store an
1216 entire hash into a cookie this way:
1217
1218 my $cookie = $q->cookie(
1219 -name => 'family information',
1220 -value => \%childrens_ages
1221 );
1222
1223 -path
1224 The optional partial path for which this cookie will be valid, as
1225 described above.
1226
1227 -domain
1228 The optional partial domain for which this cookie will be valid, as
1229 described above.
1230
1231 -expires
1232 The optional expiration date for this cookie. The format is as
1233 described in the section on the header() method:
1234
1235 "+1h" one hour from now
1236
1237 -secure
1238 If set to true, this cookie will only be used within a secure SSL
1239 session.
1240
1241 The cookie created by cookie() must be incorporated into the HTTP
1242 header within the string returned by the header() method:
1243
1244 use strict;
1245 use warnings;
1246
1247 use CGI;
1248
1249 my $q = CGI->new;
1250 my $cookie = ...
1251 print $q->header( -cookie => $cookie );
1252
1253 To create multiple cookies, give header() an array reference:
1254
1255 my $cookie1 = $q->cookie(
1256 -name => 'riddle_name',
1257 -value => "The Sphynx's Question"
1258 );
1259
1260 my $cookie2 = $q->cookie(
1261 -name => 'answers',
1262 -value => \%answers
1263 );
1264
1265 print $q->header( -cookie => [ $cookie1,$cookie2 ] );
1266
1267 To retrieve a cookie, request it by name by calling cookie() method
1268 without the -value parameter. This example uses the object-oriented
1269 form:
1270
1271 my $riddle = $q->cookie('riddle_name');
1272 my %answers = $q->cookie('answers');
1273
1274 Cookies created with a single scalar value, such as the "riddle_name"
1275 cookie, will be returned in that form. Cookies with array and hash
1276 values can also be retrieved.
1277
1278 The cookie and CGI namespaces are separate. If you have a parameter
1279 named 'answers' and a cookie named 'answers', the values retrieved by
1280 param() and cookie() are independent of each other. However, it's
1281 simple to turn a CGI parameter into a cookie, and vice-versa:
1282
1283 # turn a CGI parameter into a cookie
1284 my $c = cookie( -name => 'answers',-value => [$q->param('answers')] );
1285 # vice-versa
1286 $q->param( -name => 'answers',-value => [ $q->cookie('answers')] );
1287
1288 If you call cookie() without any parameters, it will return a list of
1289 the names of all cookies passed to your script:
1290
1291 my @cookies = $q->cookie();
1292
1293 See the cookie.cgi example script for some ideas on how to use cookies
1294 effectively.
1295
1297 If you are running the script from the command line or in the perl
1298 debugger, you can pass the script a list of keywords or parameter=value
1299 pairs on the command line or from standard input (you don't have to
1300 worry about tricking your script into reading from environment
1301 variables). You can pass keywords like this:
1302
1303 your_script.pl keyword1 keyword2 keyword3
1304
1305 or this:
1306
1307 your_script.pl keyword1+keyword2+keyword3
1308
1309 or this:
1310
1311 your_script.pl name1=value1 name2=value2
1312
1313 or this:
1314
1315 your_script.pl name1=value1&name2=value2
1316
1317 To turn off this feature, use the -no_debug pragma.
1318
1319 To test the POST method, you may enable full debugging with the -debug
1320 pragma. This will allow you to feed newline-delimited name=value pairs
1321 to the script on standard input.
1322
1323 When debugging, you can use quotes and backslashes to escape characters
1324 in the familiar shell manner, letting you place spaces and other funny
1325 characters in your parameter=value pairs:
1326
1327 your_script.pl "name1='I am a long value'" "name2=two\ words"
1328
1329 Finally, you can set the path info for the script by prefixing the
1330 first name/value parameter with the path followed by a question mark
1331 (?):
1332
1333 your_script.pl /your/path/here?name1=value1&name2=value2
1334
1336 Some of the more useful environment variables can be fetched through
1337 this interface. The methods are as follows:
1338
1339 Accept()
1340 Return a list of MIME types that the remote browser accepts. If you
1341 give this method a single argument corresponding to a MIME type, as
1342 in Accept('text/html'), it will return a floating point value
1343 corresponding to the browser's preference for this type from 0.0
1344 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's
1345 accept list are handled correctly.
1346
1347 Note that the capitalization changed between version 2.43 and 2.44
1348 in order to avoid conflict with perl's accept() function.
1349
1350 raw_cookie()
1351 Returns the HTTP_COOKIE variable. Cookies have a special format,
1352 and this method call just returns the raw form (?cookie dough). See
1353 cookie() for ways of setting and retrieving cooked cookies.
1354
1355 Called with no parameters, raw_cookie() returns the packed cookie
1356 structure. You can separate it into individual cookies by
1357 splitting on the character sequence "; ". Called with the name of a
1358 cookie, retrieves the unescaped form of the cookie. You can use the
1359 regular cookie() method to get the names, or use the raw_fetch()
1360 method from the CGI::Cookie module.
1361
1362 env_query_string()
1363 Returns the QUERY_STRING variable, note that this is the original
1364 value as set in the environment by the webserver and (possibly) not
1365 the same value as returned by query_string(), which represents the
1366 object state
1367
1368 user_agent()
1369 Returns the HTTP_USER_AGENT variable. If you give this method a
1370 single argument, it will attempt to pattern match on it, allowing
1371 you to do something like user_agent(Mozilla);
1372
1373 path_info()
1374 Returns additional path information from the script URL. E.G.
1375 fetching /cgi-bin/your_script/additional/stuff will result in
1376 path_info() returning "/additional/stuff".
1377
1378 NOTE: The Microsoft Internet Information Server is broken with
1379 respect to additional path information. If you use the perl DLL
1380 library, the IIS server will attempt to execute the additional path
1381 information as a perl script. If you use the ordinary file
1382 associations mapping, the path information will be present in the
1383 environment, but incorrect. The best thing to do is to avoid using
1384 additional path information in CGI scripts destined for use with
1385 IIS. A best attempt has been made to make CGI.pm do the right
1386 thing.
1387
1388 path_translated()
1389 As per path_info() but returns the additional path information
1390 translated into a physical path, e.g.
1391 "/usr/local/etc/httpd/htdocs/additional/stuff".
1392
1393 The Microsoft IIS is broken with respect to the translated path as
1394 well.
1395
1396 remote_host()
1397 Returns either the remote host name or IP address if the former is
1398 unavailable.
1399
1400 remote_ident()
1401 Returns the name of the remote user (as returned by identd) or
1402 undef if not set
1403
1404 remote_addr()
1405 Returns the remote host IP address, or 127.0.0.1 if the address is
1406 unavailable.
1407
1408 request_uri()
1409 Returns the interpreted pathname of the requested document or CGI
1410 (relative to the document root). Or undef if not set.
1411
1412 script_name()
1413 Return the script name as a partial URL, for self-referring
1414 scripts.
1415
1416 referer()
1417 Return the URL of the page the browser was viewing prior to
1418 fetching your script.
1419
1420 auth_type()
1421 Return the authorization/verification method in use for this
1422 script, if any.
1423
1424 server_name()
1425 Returns the name of the server, usually the machine's host name.
1426
1427 virtual_host()
1428 When using virtual hosts, returns the name of the host that the
1429 browser attempted to contact
1430
1431 server_port()
1432 Return the port that the server is listening on.
1433
1434 server_protocol()
1435 Returns the protocol and revision of the incoming request, or
1436 defaults to HTTP/1.0 if this is not set
1437
1438 virtual_port()
1439 Like server_port() except that it takes virtual hosts into account.
1440 Use this when running with virtual hosts.
1441
1442 server_software()
1443 Returns the server software and version number.
1444
1445 remote_user()
1446 Return the authorization/verification name used for user
1447 verification, if this script is protected.
1448
1449 user_name()
1450 Attempt to obtain the remote user's name, using a variety of
1451 different techniques. May not work in all browsers.
1452
1453 request_method()
1454 Returns the method used to access your script, usually one of
1455 'POST', 'GET' or 'HEAD'. If running from the command line it will
1456 be undef.
1457
1458 content_type()
1459 Returns the content_type of data submitted in a POST, generally
1460 multipart/form-data or application/x-www-form-urlencoded
1461
1462 http()
1463 Called with no arguments returns the list of HTTP environment
1464 variables, including such things as HTTP_USER_AGENT,
1465 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
1466 like-named HTTP header fields in the request. Called with the name
1467 of an HTTP header field, returns its value. Capitalization and the
1468 use of hyphens versus underscores are not significant.
1469
1470 For example, all three of these examples are equivalent:
1471
1472 my $requested_language = $q->http('Accept-language');
1473
1474 my $requested_language = $q->http('Accept_language');
1475
1476 my $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
1477
1478 https()
1479 The same as http(), but operates on the HTTPS environment variables
1480 present when the SSL protocol is in effect. Can be used to
1481 determine whether SSL is turned on.
1482
1484 NPH, or "no-parsed-header", scripts bypass the server completely by
1485 sending the complete HTTP header directly to the browser. This has
1486 slight performance benefits, but is of most use for taking advantage of
1487 HTTP extensions that are not directly supported by your server, such as
1488 server push and PICS headers.
1489
1490 Servers use a variety of conventions for designating CGI scripts as
1491 NPH. Many Unix servers look at the beginning of the script's name for
1492 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
1493 Internet Information Server, in contrast, try to decide whether a
1494 program is an NPH script by examining the first line of script output.
1495
1496 CGI.pm supports NPH scripts with a special NPH mode. When in this mode,
1497 CGI.pm will output the necessary extra header information when the
1498 header() and redirect() methods are called.
1499
1500 The Microsoft Internet Information Server requires NPH mode. As of
1501 version 2.30, CGI.pm will automatically detect when the script is
1502 running under IIS and put itself into this mode. You do not need to do
1503 this manually, although it won't hurt anything if you do.
1504
1505 In the use statement
1506 Simply add the "-nph" pragma to the list of symbols to be imported
1507 into your script:
1508
1509 use CGI qw(:standard -nph)
1510
1511 By calling the nph() method:
1512 Call nph() with a non-zero parameter at any point after using
1513 CGI.pm in your program.
1514
1515 CGI->nph(1)
1516
1517 By using -nph parameters
1518 in the header() and redirect() statements:
1519
1520 print header(-nph=>1);
1521
1523 CGI.pm provides four simple functions for producing multipart documents
1524 of the type needed to implement server push. These functions were
1525 graciously provided by Ed Jordan <ed@fidalgo.net>. To import these into
1526 your namespace, you must import the ":push" set. You are also advised
1527 to put the script into NPH mode and to set $| to 1 to avoid buffering
1528 problems.
1529
1530 Here is a simple script that demonstrates server push:
1531
1532 #!/usr/bin/env perl
1533
1534 use strict;
1535 use warnings;
1536
1537 use CGI qw/:push -nph/;
1538
1539 $| = 1;
1540 print multipart_init( -boundary=>'----here we go!' );
1541 for (0 .. 4) {
1542 print multipart_start( -type=>'text/plain' ),
1543 "The current time is ",scalar( localtime ),"\n";
1544 if ($_ < 4) {
1545 print multipart_end();
1546 } else {
1547 print multipart_final();
1548 }
1549 sleep 1;
1550 }
1551
1552 This script initializes server push by calling multipart_init(). It
1553 then enters a loop in which it begins a new multipart section by
1554 calling multipart_start(), prints the current local time, and ends a
1555 multipart section with multipart_end(). It then sleeps a second, and
1556 begins again. On the final iteration, it ends the multipart section
1557 with multipart_final() rather than with multipart_end().
1558
1559 multipart_init()
1560 multipart_init( -boundary => $boundary, -charset => $charset );
1561
1562 Initialize the multipart system. The -boundary argument specifies
1563 what MIME boundary string to use to separate parts of the document.
1564 If not provided, CGI.pm chooses a reasonable boundary for you.
1565
1566 The -charset provides the character set, if not provided this will
1567 default to ISO-8859-1
1568
1569 multipart_start()
1570 multipart_start( -type => $type, -charset => $charset );
1571
1572 Start a new part of the multipart document using the specified MIME
1573 type and charset. If not specified, text/html ISO-8859-1 is
1574 assumed.
1575
1576 multipart_end()
1577 multipart_end()
1578
1579 End a part. You must remember to call multipart_end() once for each
1580 multipart_start(), except at the end of the last part of the
1581 multipart document when multipart_final() should be called instead
1582 of multipart_end().
1583
1584 multipart_final()
1585 multipart_final()
1586
1587 End all parts. You should call multipart_final() rather than
1588 multipart_end() at the end of the last part of the multipart
1589 document.
1590
1591 Users interested in server push applications should also have a look at
1592 the CGI::Push module.
1593
1595 A potential problem with CGI.pm is that, by default, it attempts to
1596 process form POSTings no matter how large they are. A wily hacker could
1597 attack your site by sending a CGI script a huge POST of many gigabytes.
1598 CGI.pm will attempt to read the entire POST into a variable, growing
1599 hugely in size until it runs out of memory. While the script attempts
1600 to allocate the memory the system may slow down dramatically. This is a
1601 form of denial of service attack.
1602
1603 Another possible attack is for the remote user to force CGI.pm to
1604 accept a huge file upload. CGI.pm will accept the upload and store it
1605 in a temporary directory even if your script doesn't expect to receive
1606 an uploaded file. CGI.pm will delete the file automatically when it
1607 terminates, but in the meantime the remote user may have filled up the
1608 server's disk space, causing problems for other programs.
1609
1610 The best way to avoid denial of service attacks is to limit the amount
1611 of memory, CPU time and disk space that CGI scripts can use. Some Web
1612 servers come with built-in facilities to accomplish this. In other
1613 cases, you can use the shell limit or ulimit commands to put ceilings
1614 on CGI resource usage.
1615
1616 CGI.pm also has some simple built-in protections against denial of
1617 service attacks, but you must activate them before you can use them.
1618 These take the form of two global variables in the CGI name space:
1619
1620 $CGI::POST_MAX
1621 If set to a non-negative integer, this variable puts a ceiling on
1622 the size of POSTings, in bytes. If CGI.pm detects a POST that is
1623 greater than the ceiling, it will immediately exit with an error
1624 message. This value will affect both ordinary POSTs and multipart
1625 POSTs, meaning that it limits the maximum size of file uploads as
1626 well. You should set this to a reasonably high value, such as 10
1627 megabytes.
1628
1629 $CGI::DISABLE_UPLOADS
1630 If set to a non-zero value, this will disable file uploads
1631 completely. Other fill-out form values will work as usual.
1632
1633 To use these variables, set the variable at the top of the script,
1634 right after the "use" statement:
1635
1636 #!/usr/bin/env perl
1637
1638 use strict;
1639 use warnings;
1640
1641 use CGI;
1642
1643 $CGI::POST_MAX = 1024 * 1024 * 10; # max 10MB posts
1644 $CGI::DISABLE_UPLOADS = 1; # no uploads
1645
1646 An attempt to send a POST larger than $POST_MAX bytes will cause
1647 param() to return an empty CGI parameter list. You can test for this
1648 event by checking cgi_error(), either after you create the CGI object
1649 or, if you are using the function-oriented interface, call <param()>
1650 for the first time. If the POST was intercepted, then cgi_error() will
1651 return the message "413 POST too large".
1652
1653 This error message is actually defined by the HTTP protocol, and is
1654 designed to be returned to the browser as the CGI script's status code.
1655 For example:
1656
1657 my $uploaded_file = $q->param('upload');
1658 if ( !$uploaded_file && $q->cgi_error() ) {
1659 print $q->header( -status => $q->cgi_error() );
1660 exit 0;
1661 }
1662
1663 However it isn't clear that any browser currently knows what to do with
1664 this status code. It might be better just to create a page that warns
1665 the user of the problem.
1666
1668 There are a number of global module flags which affect how CGI.pm
1669 operates.
1670
1671 $CGI::APPEND_QUERY_STRING
1672 If set to a non-zero value, this will add query string parameters
1673 to a POST forms parameters hence allowing param() to return values
1674 from the query string as well as from the decoded POST request
1675 instead of having to use url_param instead. This makes it easier to
1676 get the value of a parameter when you don't know the source.
1677
1679 To make it easier to port existing programs that use cgi-lib.pl the
1680 compatibility routine "ReadParse" is provided. Porting is simple:
1681
1682 OLD VERSION
1683
1684 require "cgi-lib.pl";
1685 &ReadParse;
1686 print "The value of the antique is $in{antique}.\n";
1687
1688 NEW VERSION
1689
1690 use CGI;
1691 CGI::ReadParse();
1692 print "The value of the antique is $in{antique}.\n";
1693
1694 CGI.pm's ReadParse() routine creates a tied variable named %in, which
1695 can be accessed to obtain the query variables. Like ReadParse, you can
1696 also provide your own variable. Infrequently used features of
1697 ReadParse, such as the creation of @in and $in variables, are not
1698 supported.
1699
1700 Once you use ReadParse, you can retrieve the query object itself this
1701 way:
1702
1703 my $q = $in{CGI};
1704
1705 This allows you to start using the more interesting features of CGI.pm
1706 without rewriting your old scripts from scratch.
1707
1708 An even simpler way to mix cgi-lib calls with CGI.pm calls is to import
1709 both the ":cgi-lib" and ":standard" method:
1710
1711 use CGI qw(:cgi-lib :standard);
1712 &ReadParse;
1713 print "The price of your purchase is $in{price}.\n";
1714 print textfield(-name=>'price', -default=>'$1.99');
1715
1716 Cgi-lib functions that are available in CGI.pm
1717 In compatibility mode, the following cgi-lib.pl functions are available
1718 for your use:
1719
1720 ReadParse()
1721 PrintHeader()
1722 SplitParam()
1723 MethGet()
1724 MethPost()
1725
1727 The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is
1728 distributed under the Artistic License 2.0. It is currently maintained
1729 by Lee Johnson (LEEJO) with help from many contributors.
1730
1732 Thanks very much to:
1733
1734 Mark Stosberg (mark@stosberg.com)
1735 Matt Heffron (heffron@falstaff.css.beckman.com)
1736 James Taylor (james.taylor@srs.gov)
1737 Scott Anguish (sanguish@digifix.com)
1738 Mike Jewell (mlj3u@virginia.edu)
1739 Timothy Shimmin (tes@kbs.citri.edu.au)
1740 Joergen Haegg (jh@axis.se)
1741 Laurent Delfosse (delfosse@delfosse.com)
1742 Richard Resnick (applepi1@aol.com)
1743 Craig Bishop (csb@barwonwater.vic.gov.au)
1744 Tony Curtis (tc@vcpc.univie.ac.at)
1745 Tim Bunce (Tim.Bunce@ig.co.uk)
1746 Tom Christiansen (tchrist@convex.com)
1747 Andreas Koenig (k@franz.ww.TU-Berlin.DE)
1748 Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
1749 Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
1750 Stephen Dahmen (joyfire@inxpress.net)
1751 Ed Jordan (ed@fidalgo.net)
1752 David Alan Pisoni (david@cnation.com)
1753 Doug MacEachern (dougm@opengroup.org)
1754 Robin Houston (robin@oneworld.org)
1755 ...and many many more...
1756 for suggestions and bug fixes.
1757
1759 Address bug reports and comments to:
1760 <https://github.com/leejo/CGI.pm/issues>
1761
1762 See the <https://github.com/leejo/CGI.pm/blob/master/CONTRIBUTING.md>
1763 file for information on raising issues and contributing
1764
1765 The original bug tracker can be found at:
1766 <https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm>
1767
1769 CGI::Carp - provides Carp implementation tailored to the CGI
1770 environment.
1771
1772 CGI::Fast - supports running CGI applications under FastCGI
1773
1774
1775
1776perl v5.32.1 2021-05-04 CGI(3)