• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

examples/H03-May-2022-334263

lib/H03-Jun-2021-9,6875,946

t/H03-May-2022-4,6343,343

ChangesH A D03-Jun-202193.7 KiB2,3581,834

LICENSEH A D04-May-20218.4 KiB7544

MANIFESTH A D03-Jun-20211.7 KiB102101

META.jsonH A D03-Jun-20212 KiB8483

META.ymlH A D03-Jun-20211.1 KiB5251

Makefile.PLH A D04-May-20213.5 KiB8777

README.mdH A D04-May-202166.9 KiB1,7841,260

README.md

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