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 Content-Type (MIME type) and Content-
993 Disposition (filename) headers. To retrieve this information, call
994 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 When uploading multiple files, call ->param() in list context to
1011 retrieve a list of filehandles that you can use when calling
1012 ->uploadInfo.
1013
1014 my @filehandles = $q->param('uploaded_file');
1015
1016 for my $fh (@filehandles) {
1017 my $info = $q->uploadInfo($fh);
1018 ...
1019 }
1020
1021 If you are using a machine that recognizes "text" and "binary" data
1022 modes, be sure to understand when and how to use them (see the Camel
1023 book). Otherwise you may find that binary files are corrupted during
1024 file uploads.
1025
1026 Accessing the temp files directly
1027
1028 When processing an uploaded file, CGI.pm creates a temporary file on
1029 your hard disk and passes you a file handle to that file. After you are
1030 finished with the file handle, CGI.pm unlinks (deletes) the temporary
1031 file. If you need to you can access the temporary file directly. You
1032 can access the temp file for a file upload by passing the file name to
1033 the tmpFileName() method:
1034
1035 my $filehandle = $q->upload( 'uploaded_file' );
1036 my $tmpfilename = $q->tmpFileName( $filehandle );
1037
1038 As with ->uploadInfo, using the reference returned by ->upload or
1039 ->param is preferred, although unlike ->uploadInfo, plain filenames
1040 also work if possible for backwards compatibility.
1041
1042 The temporary file will be deleted automatically when your program
1043 exits unless you manually rename it or set $CGI::UNLINK_TMP_FILES to 0.
1044 On some operating systems (such as Windows NT), you will need to close
1045 the temporary file's filehandle before your program exits. Otherwise
1046 the attempt to delete the temporary file will fail.
1047
1048 Changes in temporary file handling (v4.05+)
1049
1050 CGI.pm had its temporary file handling significantly refactored, this
1051 logic is now all deferred to File::Temp (which is wrapped in a
1052 compatibility object, CGI::File::Temp - DO NOT USE THIS PACKAGE
1053 DIRECTLY). As a consequence the PRIVATE_TEMPFILES variable has been
1054 removed along with deprecation of the private_tempfiles routine and
1055 complete removal of the CGITempFile package. The
1056 $CGITempFile::TMPDIRECTORY is no longer used to set the temp directory,
1057 refer to the perldoc for File::Temp if you want to override the default
1058 settings in that package (the TMPDIR env variable is still available on
1059 some platforms). For Windows platforms the temporary directory order
1060 remains as before: TEMP > TMP > WINDIR ( > TMPDIR ) so if you have any
1061 of these in use in existing scripts they should still work.
1062
1063 The Fh package still exists but does nothing, the CGI::File::Temp class
1064 is a subclass of both File::Temp and the empty Fh package, so if you
1065 have any code that checks that the filehandle isa Fh this should still
1066 work.
1067
1068 When you get the internal file handle you will receive a File::Temp
1069 object, this should be transparent as File::Temp isa IO::Handle and isa
1070 IO::Seekable meaning it behaves as previously. If you are doing
1071 anything out of the ordinary with regards to temp files you should test
1072 your code before deploying this update and refer to the File::Temp
1073 documentation for more information.
1074
1075 Handling interrupted file uploads
1076
1077 There are occasionally problems involving parsing the uploaded file.
1078 This usually happens when the user presses "Stop" before the upload is
1079 finished. In this case, CGI.pm will return undef for the name of the
1080 uploaded file and set cgi_error() to the string "400 Bad request
1081 (malformed multipart POST)". This error message is designed so that you
1082 can incorporate it into a status code to be sent to the browser.
1083 Example:
1084
1085 my $file = $q->upload( 'uploaded_file' );
1086 if ( !$file && $q->cgi_error ) {
1087 print $q->header( -status => $q->cgi_error );
1088 exit 0;
1089 }
1090
1091 Progress bars for file uploads and avoiding temp files
1092
1093 CGI.pm gives you low-level access to file upload management through a
1094 file upload hook. You can use this feature to completely turn off the
1095 temp file storage of file uploads, or potentially write your own file
1096 upload progress meter.
1097
1098 This is much like the UPLOAD_HOOK facility available in
1099 Apache::Request, with the exception that the first argument to the
1100 callback is an Apache::Upload object, here it's the remote filename.
1101
1102 my $q = CGI->new( \&hook [,$data [,$use_tempfile]] );
1103
1104 sub hook {
1105 my ( $filename, $buffer, $bytes_read, $data ) = @_;
1106 print "Read $bytes_read bytes of $filename\n";
1107 }
1108
1109 The $data field is optional; it lets you pass configuration information
1110 (e.g. a database handle) to your hook callback.
1111
1112 The $use_tempfile field is a flag that lets you turn on and off
1113 CGI.pm's use of a temporary disk-based file during file upload. If you
1114 set this to a FALSE value (default true) then
1115 "$q->param('uploaded_file')" will still return a typeglob that can be
1116 used to access a filehandle and the filename of the uploaded file,
1117 however the filehandle will be a handle to an empty file. Existence of
1118 your hook causes CGI.pm to bypass writing to that filehandle (which is
1119 probably what you intended when you set $use_tempfile off).
1120
1121 The uploadInfo() method can be used on the typeglob returned to you
1122 when you called "$q->param('upload_file')" to return information about
1123 the uploaded file(s). For multiple file uploads, use the param()
1124 method in list context to retrieve all of the typeglobs.
1125
1126 my (@filehandles) = $cgi->param('upfile');
1127
1128 foreach my $fh (@filehandles) {
1129 my $info = $cgi->uploadInfo($fh);
1130 ...
1131 }
1132
1133 If using the function-oriented interface, call the CGI::upload_hook()
1134 method before calling param() or any other CGI functions:
1135
1136 CGI::upload_hook( \&hook [,$data [,$use_tempfile]] );
1137
1138 This method is not exported by default. You will have to import it
1139 explicitly if you wish to use it without the CGI:: prefix.
1140
1141 Troubleshooting file uploads on Windows
1142
1143 If you are using CGI.pm on a Windows platform and find that binary
1144 files get slightly larger when uploaded but that text files remain the
1145 same, then you have forgotten to activate binary mode on the output
1146 filehandle. Be sure to call binmode() on any handle that you create to
1147 write the uploaded file to disk.
1148
1149 Older ways to process file uploads
1150
1151 This section is here for completeness. if you are building a new
1152 application with CGI.pm, you can skip it.
1153
1154 The original way to process file uploads with CGI.pm was to use
1155 param(). The value it returns has a dual nature as both a file name and
1156 a lightweight filehandle. This dual nature is problematic if you
1157 following the recommended practice of having "use strict" in your code.
1158 perl will complain when you try to use a string as a filehandle. More
1159 seriously, it is possible for the remote user to type garbage into the
1160 upload field, in which case what you get from param() is not a
1161 filehandle at all, but a string.
1162
1163 To solve this problem the upload() method was added, which always
1164 returns a lightweight filehandle. This generally works well, but will
1165 have trouble interoperating with some other modules because the file
1166 handle is not derived from IO::File. So that brings us to current
1167 recommendation given above, which is to call the handle() method on the
1168 file handle returned by upload(). That upgrades the handle to an
1169 IO::File. It's a big win for compatibility for a small penalty of
1170 loading IO::File the first time you call it.
1171
1173 CGI.pm has several methods that support cookies.
1174
1175 A cookie is a name=value pair much like the named parameters in a CGI
1176 query string. CGI scripts create one or more cookies and send them to
1177 the browser in the HTTP header. The browser maintains a list of cookies
1178 that belong to a particular Web server, and returns them to the CGI
1179 script during subsequent interactions.
1180
1181 In addition to the required name=value pair, each cookie has several
1182 optional attributes:
1183
1184 1. an expiration time
1185 This is a time/date string (in a special GMT format) that indicates
1186 when a cookie expires. The cookie will be saved and returned to
1187 your script until this expiration date is reached if the user exits
1188 the browser and restarts it. If an expiration date isn't specified,
1189 the cookie will remain active until the user quits the browser.
1190
1191 2. a domain
1192 This is a partial or complete domain name for which the cookie is
1193 valid. The browser will return the cookie to any host that matches
1194 the partial domain name. For example, if you specify a domain name
1195 of ".capricorn.com", then the browser will return the cookie to Web
1196 servers running on any of the machines "www.capricorn.com",
1197 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
1198 must contain at least two periods to prevent attempts to match on
1199 top level domains like ".edu". If no domain is specified, then the
1200 browser will only return the cookie to servers on the host the
1201 cookie originated from.
1202
1203 3. a path
1204 If you provide a cookie path attribute, the browser will check it
1205 against your script's URL before returning the cookie. For example,
1206 if you specify the path "/cgi-bin", then the cookie will be
1207 returned to each of the scripts "/cgi-bin/tally.pl",
1208 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
1209 but not to the script "/cgi-private/site_admin.pl". By default,
1210 path is set to "/", which causes the cookie to be sent to any CGI
1211 script on your site.
1212
1213 4. a "secure" flag
1214 If the "secure" attribute is set, the cookie will only be sent to
1215 your script if the CGI request is occurring on a secure channel,
1216 such as SSL.
1217
1218 The interface to HTTP cookies is the cookie() method:
1219
1220 my $cookie = $q->cookie(
1221 -name => 'sessionID',
1222 -value => 'xyzzy',
1223 -expires => '+1h',
1224 -path => '/cgi-bin/database',
1225 -domain => '.capricorn.org',
1226 -secure => 1
1227 );
1228
1229 print $q->header( -cookie => $cookie );
1230
1231 cookie() creates a new cookie. Its parameters include:
1232
1233 -name
1234 The name of the cookie (required). This can be any string at all.
1235 Although browsers limit their cookie names to non-whitespace
1236 alphanumeric characters, CGI.pm removes this restriction by
1237 escaping and unescaping cookies behind the scenes.
1238
1239 -value
1240 The value of the cookie. This can be any scalar value, array
1241 reference, or even hash reference. For example, you can store an
1242 entire hash into a cookie this way:
1243
1244 my $cookie = $q->cookie(
1245 -name => 'family information',
1246 -value => \%childrens_ages
1247 );
1248
1249 -path
1250 The optional partial path for which this cookie will be valid, as
1251 described above.
1252
1253 -domain
1254 The optional partial domain for which this cookie will be valid, as
1255 described above.
1256
1257 -expires
1258 The optional expiration date for this cookie. The format is as
1259 described in the section on the header() method:
1260
1261 "+1h" one hour from now
1262
1263 -secure
1264 If set to true, this cookie will only be used within a secure SSL
1265 session.
1266
1267 The cookie created by cookie() must be incorporated into the HTTP
1268 header within the string returned by the header() method:
1269
1270 use strict;
1271 use warnings;
1272
1273 use CGI;
1274
1275 my $q = CGI->new;
1276 my $cookie = ...
1277 print $q->header( -cookie => $cookie );
1278
1279 To create multiple cookies, give header() an array reference:
1280
1281 my $cookie1 = $q->cookie(
1282 -name => 'riddle_name',
1283 -value => "The Sphynx's Question"
1284 );
1285
1286 my $cookie2 = $q->cookie(
1287 -name => 'answers',
1288 -value => \%answers
1289 );
1290
1291 print $q->header( -cookie => [ $cookie1,$cookie2 ] );
1292
1293 To retrieve a cookie, request it by name by calling cookie() method
1294 without the -value parameter. This example uses the object-oriented
1295 form:
1296
1297 my $riddle = $q->cookie('riddle_name');
1298 my %answers = $q->cookie('answers');
1299
1300 Cookies created with a single scalar value, such as the "riddle_name"
1301 cookie, will be returned in that form. Cookies with array and hash
1302 values can also be retrieved.
1303
1304 The cookie and CGI namespaces are separate. If you have a parameter
1305 named 'answers' and a cookie named 'answers', the values retrieved by
1306 param() and cookie() are independent of each other. However, it's
1307 simple to turn a CGI parameter into a cookie, and vice-versa:
1308
1309 # turn a CGI parameter into a cookie
1310 my $c = cookie( -name => 'answers',-value => [$q->param('answers')] );
1311 # vice-versa
1312 $q->param( -name => 'answers',-value => [ $q->cookie('answers')] );
1313
1314 If you call cookie() without any parameters, it will return a list of
1315 the names of all cookies passed to your script:
1316
1317 my @cookies = $q->cookie();
1318
1319 See the cookie.cgi example script for some ideas on how to use cookies
1320 effectively.
1321
1322 $CGI::COOKIE_CACHE
1323 If set to a non-negative integer, this variable will cause CGI.pm
1324 to use the cached cookie details from the previous call to
1325 cookie(). By default this cache is off to retain backwards
1326 compatibility.
1327
1329 If you are running the script from the command line or in the perl
1330 debugger, you can pass the script a list of keywords or parameter=value
1331 pairs on the command line or from standard input (you don't have to
1332 worry about tricking your script into reading from environment
1333 variables). You can pass keywords like this:
1334
1335 your_script.pl keyword1 keyword2 keyword3
1336
1337 or this:
1338
1339 your_script.pl keyword1+keyword2+keyword3
1340
1341 or this:
1342
1343 your_script.pl name1=value1 name2=value2
1344
1345 or this:
1346
1347 your_script.pl name1=value1&name2=value2
1348
1349 To turn off this feature, use the -no_debug pragma.
1350
1351 To test the POST method, you may enable full debugging with the -debug
1352 pragma. This will allow you to feed newline-delimited name=value pairs
1353 to the script on standard input.
1354
1355 When debugging, you can use quotes and backslashes to escape characters
1356 in the familiar shell manner, letting you place spaces and other funny
1357 characters in your parameter=value pairs:
1358
1359 your_script.pl "name1='I am a long value'" "name2=two\ words"
1360
1361 Finally, you can set the path info for the script by prefixing the
1362 first name/value parameter with the path followed by a question mark
1363 (?):
1364
1365 your_script.pl /your/path/here?name1=value1&name2=value2
1366
1368 Some of the more useful environment variables can be fetched through
1369 this interface. The methods are as follows:
1370
1371 Accept()
1372 Return a list of MIME types that the remote browser accepts. If you
1373 give this method a single argument corresponding to a MIME type, as
1374 in Accept('text/html'), it will return a floating point value
1375 corresponding to the browser's preference for this type from 0.0
1376 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's
1377 accept list are handled correctly.
1378
1379 Note that the capitalization changed between version 2.43 and 2.44
1380 in order to avoid conflict with perl's accept() function.
1381
1382 raw_cookie()
1383 Returns the HTTP_COOKIE variable. Cookies have a special format,
1384 and this method call just returns the raw form (?cookie dough). See
1385 cookie() for ways of setting and retrieving cooked cookies.
1386
1387 Called with no parameters, raw_cookie() returns the packed cookie
1388 structure. You can separate it into individual cookies by
1389 splitting on the character sequence "; ". Called with the name of a
1390 cookie, retrieves the unescaped form of the cookie. You can use the
1391 regular cookie() method to get the names, or use the raw_fetch()
1392 method from the CGI::Cookie module.
1393
1394 env_query_string()
1395 Returns the QUERY_STRING variable, note that this is the original
1396 value as set in the environment by the webserver and (possibly) not
1397 the same value as returned by query_string(), which represents the
1398 object state
1399
1400 user_agent()
1401 Returns the HTTP_USER_AGENT variable. If you give this method a
1402 single argument, it will attempt to pattern match on it, allowing
1403 you to do something like user_agent(Mozilla);
1404
1405 path_info()
1406 Returns additional path information from the script URL. E.G.
1407 fetching /cgi-bin/your_script/additional/stuff will result in
1408 path_info() returning "/additional/stuff".
1409
1410 NOTE: The Microsoft Internet Information Server is broken with
1411 respect to additional path information. If you use the perl DLL
1412 library, the IIS server will attempt to execute the additional path
1413 information as a perl script. If you use the ordinary file
1414 associations mapping, the path information will be present in the
1415 environment, but incorrect. The best thing to do is to avoid using
1416 additional path information in CGI scripts destined for use with
1417 IIS. A best attempt has been made to make CGI.pm do the right
1418 thing.
1419
1420 path_translated()
1421 As per path_info() but returns the additional path information
1422 translated into a physical path, e.g.
1423 "/usr/local/etc/httpd/htdocs/additional/stuff".
1424
1425 The Microsoft IIS is broken with respect to the translated path as
1426 well.
1427
1428 remote_host()
1429 Returns either the remote host name or IP address if the former is
1430 unavailable.
1431
1432 remote_ident()
1433 Returns the name of the remote user (as returned by identd) or
1434 undef if not set
1435
1436 remote_addr()
1437 Returns the remote host IP address, or 127.0.0.1 if the address is
1438 unavailable.
1439
1440 request_uri()
1441 Returns the interpreted pathname of the requested document or CGI
1442 (relative to the document root). Or undef if not set.
1443
1444 script_name()
1445 Return the script name as a partial URL, for self-referring
1446 scripts.
1447
1448 referer()
1449 Return the URL of the page the browser was viewing prior to
1450 fetching your script.
1451
1452 auth_type()
1453 Return the authorization/verification method in use for this
1454 script, if any.
1455
1456 server_name()
1457 Returns the name of the server, usually the machine's host name.
1458
1459 virtual_host()
1460 When using virtual hosts, returns the name of the host that the
1461 browser attempted to contact
1462
1463 server_port()
1464 Return the port that the server is listening on.
1465
1466 server_protocol()
1467 Returns the protocol and revision of the incoming request, or
1468 defaults to HTTP/1.0 if this is not set
1469
1470 virtual_port()
1471 Like server_port() except that it takes virtual hosts into account.
1472 Use this when running with virtual hosts.
1473
1474 server_software()
1475 Returns the server software and version number.
1476
1477 remote_user()
1478 Return the authorization/verification name used for user
1479 verification, if this script is protected.
1480
1481 user_name()
1482 Attempt to obtain the remote user's name, using a variety of
1483 different techniques. May not work in all browsers.
1484
1485 request_method()
1486 Returns the method used to access your script, usually one of
1487 'POST', 'GET' or 'HEAD'. If running from the command line it will
1488 be undef.
1489
1490 content_type()
1491 Returns the content_type of data submitted in a POST, generally
1492 multipart/form-data or application/x-www-form-urlencoded
1493
1494 http()
1495 Called with no arguments returns the list of HTTP environment
1496 variables, including such things as HTTP_USER_AGENT,
1497 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
1498 like-named HTTP header fields in the request. Called with the name
1499 of an HTTP header field, returns its value. Capitalization and the
1500 use of hyphens versus underscores are not significant.
1501
1502 For example, all three of these examples are equivalent:
1503
1504 my $requested_language = $q->http('Accept-language');
1505
1506 my $requested_language = $q->http('Accept_language');
1507
1508 my $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
1509
1510 https()
1511 The same as http(), but operates on the HTTPS environment variables
1512 present when the SSL protocol is in effect. Can be used to
1513 determine whether SSL is turned on.
1514
1516 NPH, or "no-parsed-header", scripts bypass the server completely by
1517 sending the complete HTTP header directly to the browser. This has
1518 slight performance benefits, but is of most use for taking advantage of
1519 HTTP extensions that are not directly supported by your server, such as
1520 server push and PICS headers.
1521
1522 Servers use a variety of conventions for designating CGI scripts as
1523 NPH. Many Unix servers look at the beginning of the script's name for
1524 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
1525 Internet Information Server, in contrast, try to decide whether a
1526 program is an NPH script by examining the first line of script output.
1527
1528 CGI.pm supports NPH scripts with a special NPH mode. When in this mode,
1529 CGI.pm will output the necessary extra header information when the
1530 header() and redirect() methods are called.
1531
1532 The Microsoft Internet Information Server requires NPH mode. As of
1533 version 2.30, CGI.pm will automatically detect when the script is
1534 running under IIS and put itself into this mode. You do not need to do
1535 this manually, although it won't hurt anything if you do.
1536
1537 In the use statement
1538 Simply add the "-nph" pragma to the list of symbols to be imported
1539 into your script:
1540
1541 use CGI qw(:standard -nph)
1542
1543 By calling the nph() method:
1544 Call nph() with a non-zero parameter at any point after using
1545 CGI.pm in your program.
1546
1547 CGI->nph(1)
1548
1549 By using -nph parameters
1550 in the header() and redirect() statements:
1551
1552 print header(-nph=>1);
1553
1555 CGI.pm provides four simple functions for producing multipart documents
1556 of the type needed to implement server push. These functions were
1557 graciously provided by Ed Jordan <ed@fidalgo.net>. To import these into
1558 your namespace, you must import the ":push" set. You are also advised
1559 to put the script into NPH mode and to set $| to 1 to avoid buffering
1560 problems.
1561
1562 Here is a simple script that demonstrates server push:
1563
1564 #!/usr/bin/env perl
1565
1566 use strict;
1567 use warnings;
1568
1569 use CGI qw/:push -nph/;
1570
1571 $| = 1;
1572 print multipart_init( -boundary=>'----here we go!' );
1573 for (0 .. 4) {
1574 print multipart_start( -type=>'text/plain' ),
1575 "The current time is ",scalar( localtime ),"\n";
1576 if ($_ < 4) {
1577 print multipart_end();
1578 } else {
1579 print multipart_final();
1580 }
1581 sleep 1;
1582 }
1583
1584 This script initializes server push by calling multipart_init(). It
1585 then enters a loop in which it begins a new multipart section by
1586 calling multipart_start(), prints the current local time, and ends a
1587 multipart section with multipart_end(). It then sleeps a second, and
1588 begins again. On the final iteration, it ends the multipart section
1589 with multipart_final() rather than with multipart_end().
1590
1591 multipart_init()
1592 multipart_init( -boundary => $boundary, -charset => $charset );
1593
1594 Initialize the multipart system. The -boundary argument specifies
1595 what MIME boundary string to use to separate parts of the document.
1596 If not provided, CGI.pm chooses a reasonable boundary for you.
1597
1598 The -charset provides the character set, if not provided this will
1599 default to ISO-8859-1
1600
1601 multipart_start()
1602 multipart_start( -type => $type, -charset => $charset );
1603
1604 Start a new part of the multipart document using the specified MIME
1605 type and charset. If not specified, text/html ISO-8859-1 is
1606 assumed.
1607
1608 multipart_end()
1609 multipart_end()
1610
1611 End a part. You must remember to call multipart_end() once for each
1612 multipart_start(), except at the end of the last part of the
1613 multipart document when multipart_final() should be called instead
1614 of multipart_end().
1615
1616 multipart_final()
1617 multipart_final()
1618
1619 End all parts. You should call multipart_final() rather than
1620 multipart_end() at the end of the last part of the multipart
1621 document.
1622
1623 Users interested in server push applications should also have a look at
1624 the CGI::Push module.
1625
1627 A potential problem with CGI.pm is that, by default, it attempts to
1628 process form POSTings no matter how large they are. A wily hacker could
1629 attack your site by sending a CGI script a huge POST of many gigabytes.
1630 CGI.pm will attempt to read the entire POST into a variable, growing
1631 hugely in size until it runs out of memory. While the script attempts
1632 to allocate the memory the system may slow down dramatically. This is a
1633 form of denial of service attack.
1634
1635 Another possible attack is for the remote user to force CGI.pm to
1636 accept a huge file upload. CGI.pm will accept the upload and store it
1637 in a temporary directory even if your script doesn't expect to receive
1638 an uploaded file. CGI.pm will delete the file automatically when it
1639 terminates, but in the meantime the remote user may have filled up the
1640 server's disk space, causing problems for other programs.
1641
1642 The best way to avoid denial of service attacks is to limit the amount
1643 of memory, CPU time and disk space that CGI scripts can use. Some Web
1644 servers come with built-in facilities to accomplish this. In other
1645 cases, you can use the shell limit or ulimit commands to put ceilings
1646 on CGI resource usage.
1647
1648 CGI.pm also has some simple built-in protections against denial of
1649 service attacks, but you must activate them before you can use them.
1650 These take the form of two global variables in the CGI name space:
1651
1652 $CGI::POST_MAX
1653 If set to a non-negative integer, this variable puts a ceiling on
1654 the size of POSTings, in bytes. If CGI.pm detects a POST that is
1655 greater than the ceiling, it will immediately exit with an error
1656 message. This value will affect both ordinary POSTs and multipart
1657 POSTs, meaning that it limits the maximum size of file uploads as
1658 well. You should set this to a reasonably high value, such as 10
1659 megabytes.
1660
1661 $CGI::DISABLE_UPLOADS
1662 If set to a non-zero value, this will disable file uploads
1663 completely. Other fill-out form values will work as usual.
1664
1665 To use these variables, set the variable at the top of the script,
1666 right after the "use" statement:
1667
1668 #!/usr/bin/env perl
1669
1670 use strict;
1671 use warnings;
1672
1673 use CGI;
1674
1675 $CGI::POST_MAX = 1024 * 1024 * 10; # max 10MB posts
1676 $CGI::DISABLE_UPLOADS = 1; # no uploads
1677
1678 An attempt to send a POST larger than $POST_MAX bytes will cause
1679 param() to return an empty CGI parameter list. You can test for this
1680 event by checking cgi_error(), either after you create the CGI object
1681 or, if you are using the function-oriented interface, call <param()>
1682 for the first time. If the POST was intercepted, then cgi_error() will
1683 return the message "413 POST too large".
1684
1685 This error message is actually defined by the HTTP protocol, and is
1686 designed to be returned to the browser as the CGI script's status code.
1687 For example:
1688
1689 my $uploaded_file = $q->param('upload');
1690 if ( !$uploaded_file && $q->cgi_error() ) {
1691 print $q->header( -status => $q->cgi_error() );
1692 exit 0;
1693 }
1694
1695 However it isn't clear that any browser currently knows what to do with
1696 this status code. It might be better just to create a page that warns
1697 the user of the problem.
1698
1700 There are a number of global module flags which affect how CGI.pm
1701 operates.
1702
1703 $CGI::APPEND_QUERY_STRING
1704 If set to a non-zero value, this will add query string parameters
1705 to a POST forms parameters hence allowing param() to return values
1706 from the query string as well as from the decoded POST request
1707 instead of having to use url_param instead. This makes it easier to
1708 get the value of a parameter when you don't know the source.
1709
1711 To make it easier to port existing programs that use cgi-lib.pl the
1712 compatibility routine "ReadParse" is provided. Porting is simple:
1713
1714 OLD VERSION
1715
1716 require "cgi-lib.pl";
1717 &ReadParse;
1718 print "The value of the antique is $in{antique}.\n";
1719
1720 NEW VERSION
1721
1722 use CGI;
1723 CGI::ReadParse();
1724 print "The value of the antique is $in{antique}.\n";
1725
1726 CGI.pm's ReadParse() routine creates a tied variable named %in, which
1727 can be accessed to obtain the query variables. Like ReadParse, you can
1728 also provide your own variable. Infrequently used features of
1729 ReadParse, such as the creation of @in and $in variables, are not
1730 supported.
1731
1732 Once you use ReadParse, you can retrieve the query object itself this
1733 way:
1734
1735 my $q = $in{CGI};
1736
1737 This allows you to start using the more interesting features of CGI.pm
1738 without rewriting your old scripts from scratch.
1739
1740 An even simpler way to mix cgi-lib calls with CGI.pm calls is to import
1741 both the ":cgi-lib" and ":standard" method:
1742
1743 use CGI qw(:cgi-lib :standard);
1744 &ReadParse;
1745 print "The price of your purchase is $in{price}.\n";
1746 print textfield(-name=>'price', -default=>'$1.99');
1747
1748 Cgi-lib functions that are available in CGI.pm
1749 In compatibility mode, the following cgi-lib.pl functions are available
1750 for your use:
1751
1752 ReadParse()
1753 PrintHeader()
1754 SplitParam()
1755 MethGet()
1756 MethPost()
1757
1759 The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is
1760 distributed under the Artistic License 2.0. It is currently maintained
1761 by Lee Johnson (LEEJO) with help from many contributors.
1762
1764 Thanks very much to:
1765
1766 Mark Stosberg (mark@stosberg.com)
1767 Matt Heffron (heffron@falstaff.css.beckman.com)
1768 James Taylor (james.taylor@srs.gov)
1769 Scott Anguish (sanguish@digifix.com)
1770 Mike Jewell (mlj3u@virginia.edu)
1771 Timothy Shimmin (tes@kbs.citri.edu.au)
1772 Joergen Haegg (jh@axis.se)
1773 Laurent Delfosse (delfosse@delfosse.com)
1774 Richard Resnick (applepi1@aol.com)
1775 Craig Bishop (csb@barwonwater.vic.gov.au)
1776 Tony Curtis (tc@vcpc.univie.ac.at)
1777 Tim Bunce (Tim.Bunce@ig.co.uk)
1778 Tom Christiansen (tchrist@convex.com)
1779 Andreas Koenig (k@franz.ww.TU-Berlin.DE)
1780 Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
1781 Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
1782 Stephen Dahmen (joyfire@inxpress.net)
1783 Ed Jordan (ed@fidalgo.net)
1784 David Alan Pisoni (david@cnation.com)
1785 Doug MacEachern (dougm@opengroup.org)
1786 Robin Houston (robin@oneworld.org)
1787 ...and many many more...
1788 for suggestions and bug fixes.
1789
1791 Address bug reports and comments to:
1792 <https://github.com/leejo/CGI.pm/issues>
1793
1794 See the <https://github.com/leejo/CGI.pm/blob/master/CONTRIBUTING.md>
1795 file for information on raising issues and contributing
1796
1797 The original bug tracker can be found at:
1798 <https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm>
1799
1801 CGI::Carp - provides Carp implementation tailored to the CGI
1802 environment.
1803
1804 CGI::Fast - supports running CGI applications under FastCGI
1805
1806
1807
1808perl v5.38.0 2023-10-03 CGI(3)