[HOME]

Path : /proc/self/root/usr/local/share/man/man3/
Upload :
Current File : //proc/self/root/usr/local/share/man/man3/CGI.3pm

.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  \*(C+ will
.\" give a nicer C++.  Capital omega is used to do unbreakable dashes and
.\" therefore won't be available.  \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
.    ds C`
.    ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{
.    if \nF \{
.        de IX
.        tm Index:\\$1\t\\n%\t"\\$2"
..
.        if !\nF==2 \{
.            nr % 0
.            nr F 2
.        \}
.    \}
.\}
.rr rF
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "CGI 3"
.TH CGI 3 "2019-03-26" "perl v5.16.3" "User Contributed Perl Documentation"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
CGI \- Handle Common Gateway Interface requests and responses
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI;
\&
\&        # create a CGI object (query) for use
\&    my $q = CGI\->new;
\&
\&    # Process an HTTP request
\&    my @values  = $q\->multi_param(\*(Aqform_field\*(Aq);
\&    my $value   = $q\->param(\*(Aqparam_name\*(Aq);
\&
\&    my $fh      = $q\->upload(\*(Aqfile_field\*(Aq);
\&
\&    my $riddle  = $q\->cookie(\*(Aqriddle_name\*(Aq);
\&    my %answers = $q\->cookie(\*(Aqanswers\*(Aq);
\&
\&    # Prepare various HTTP responses
\&    print $q\->header();
\&    print $q\->header(\*(Aqapplication/json\*(Aq);
\&
\&    my $cookie1 = $q\->cookie(
\&        \-name  => \*(Aqriddle_name\*(Aq,
\&        \-value => "The Sphynx\*(Aqs Question"
\&    );
\&
\&    my $cookie2 = $q\->cookie(
\&        \-name  => \*(Aqanswers\*(Aq,
\&        \-value => \e%answers
\&    );
\&
\&    print $q\->header(
\&        \-type    => \*(Aqimage/gif\*(Aq,
\&        \-expires => \*(Aq+3d\*(Aq,
\&        \-cookie  => [ $cookie1,$cookie2 ]
\&    );
\&
\&    print $q\->redirect(\*(Aqhttp://somewhere.else/in/movie/land\*(Aq);
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
\&\s-1CGI\s0.pm is a stable, complete and mature solution for processing and preparing
\&\s-1HTTP\s0 requests and responses. Major features including processing form
submissions, file uploads, reading and writing cookies, query string generation
and manipulation, and processing and preparing \s-1HTTP\s0 headers.
.PP
\&\s-1CGI\s0.pm performs very well in a vanilla \s-1CGI\s0.pm environment and also comes
with built-in support for mod_perl and mod_perl2 as well as FastCGI.
.PP
It has the benefit of having developed and refined over 20 years with input
from dozens of contributors and being deployed on thousands of websites.
\&\s-1CGI\s0.pm was included in the perl distribution from perl v5.4 to v5.20, however
is has now been removed from the perl core...
.SH "CGI.pm HAS BEEN REMOVED FROM THE PERL CORE"
.IX Header "CGI.pm HAS BEEN REMOVED FROM THE PERL CORE"
<http://perl5.git.perl.org/perl.git/commitdiff/e9fa5a80>
.PP
If you upgrade to a new version of perl or if you rely on a
system or vendor perl and get an updated version of perl through a system
update, then you will have to install \s-1CGI\s0.pm yourself with cpan/cpanm/a vendor
package/manually. To make this a little easier the CGI::Fast module has been
split into its own distribution, meaning you do not need access to a compiler
to install \s-1CGI\s0.pm
.PP
The rationale for this decision is that \s-1CGI\s0.pm is no longer considered good
practice for developing web applications, \fBincluding\fR quick prototyping and
small web scripts. There are far better, cleaner, quicker, easier, safer,
more scalable, more extensible, more modern alternatives available at this point
in time. These will be documented with CGI::Alternatives.
.PP
For more discussion on the removal of \s-1CGI\s0.pm from core please see:
.PP
<http://www.nntp.perl.org/group/perl.perl5.porters/2013/05/msg202130.html>
.PP
Note that the v4 releases of \s-1CGI\s0.pm will retain back compatibility \fBas much\fR
\&\fBas possible\fR, however you may need to make some minor changes to your code
if you are using deprecated methods or some of the more obscure features of the
module. If you plan to upgrade to v4.00 and beyond you should read the Changes
file for more information and \fBtest your code\fR against \s-1CGI\s0.pm before deploying
it.
.SH "HTML Generation functions should no longer be used"
.IX Header "HTML Generation functions should no longer be used"
\&\fBAll\fR \s-1HTML\s0 generation functions within \s-1CGI\s0.pm are no longer being
maintained. Any issues, bugs, or patches will be rejected unless
they relate to fundamentally broken page rendering.
.PP
The rationale for this is that the \s-1HTML\s0 generation functions of \s-1CGI\s0.pm
are an obfuscation at best and a maintenance nightmare at worst. You
should be using a template engine for better separation of concerns.
See CGI::Alternatives for an example of using \s-1CGI\s0.pm with the
Template::Toolkit module.
.PP
These functions, and perldoc for them, are considered deprecated, they
are no longer being maintained and no fixes or features for them will be
accepted. They will, however, continue to exist in \s-1CGI\s0.pm without any
deprecation warnings (\*(L"soft\*(R" deprecation) so you can continue to use
them if you really want to. All documentation for these functions has
been moved to CGI::HTML::Functions.
.SH "Programming style"
.IX Header "Programming style"
There are two styles of programming with \s-1CGI\s0.pm, an object-oriented (\s-1OO\s0)
style and a function-oriented style. You are recommended to use the \s-1OO\s0
style as \s-1CGI\s0.pm will create an internal default object when the functions
are called procedurally and you will not have to worry about method names
clashing with perl builtins.
.PP
In the object-oriented style you create one or more \s-1CGI\s0 objects and then
use object methods to create the various elements of the page. Each \s-1CGI\s0
object starts out with the list of named parameters that were passed to
your \s-1CGI\s0 script by the server. You can modify the objects, save them to a
file or database and recreate them. Because each object corresponds to the
\&\*(L"state\*(R" of the \s-1CGI\s0 script, and because each object's parameter list is
independent of the others, this allows you to save the state of the
script and restore it later.
.PP
For example, using the object oriented style:
.PP
.Vb 1
\&    #!/usr/bin/env perl
\&
\&    use strict;
\&    use warnings;
\&
\&    use CGI;                             # load CGI routines
\&
\&    my $q = CGI\->new;                    # create new CGI object
\&    print $q\->header;                    # create the HTTP header
.Ve
.PP
In the function-oriented style, there is one default \s-1CGI\s0 object that
you rarely deal with directly. Instead you just call functions to
retrieve \s-1CGI\s0 parameters, manage cookies, and so on. The following example
is identical to above, in terms of output, but uses the function-oriented
interface. The main differences are that we now need to import a set of
functions into our name space (usually the \*(L"standard\*(R" functions), and we don't
need to create the \s-1CGI\s0 object.
.PP
.Vb 1
\&    #!/usr/bin/env perl
\&
\&    use strict;
\&    use warnings;
\&
\&    use CGI qw/:standard/;           # load standard CGI routines
\&    print header();                  # create the HTTP header
.Ve
.PP
The examples in this document mainly use the object-oriented style. See \s-1HOW
TO IMPORT FUNCTIONS\s0 for important information on function-oriented programming
in \s-1CGI\s0.pm
.SS "Calling \s-1CGI\s0.pm routines"
.IX Subsection "Calling CGI.pm routines"
Most \s-1CGI\s0.pm routines accept several arguments, sometimes as many as 20
optional ones! To simplify this interface, all routines use a named
argument calling style that looks like this:
.PP
.Vb 4
\&    print $q\->header(
\&        \-type    => \*(Aqimage/gif\*(Aq,
\&        \-expires => \*(Aq+3d\*(Aq,
\&    );
.Ve
.PP
Each argument name is preceded by a dash. Neither case nor order matters in
the argument list: \-type, \-Type, and \-TYPE are all acceptable. In fact, only
the first argument needs to begin with a dash. If a dash is present in the
first argument \s-1CGI\s0.pm assumes dashes for the subsequent ones.
.PP
Several routines are commonly called with just one argument. In the case
of these routines you can provide the single argument without an argument
name. \fIheader()\fR happens to be one of these routines. In this case, the single
argument is the document type.
.PP
.Vb 1
\&    print $q\->header(\*(Aqtext/html\*(Aq);
.Ve
.PP
Other such routines are documented below.
.PP
Sometimes named arguments expect a scalar, sometimes a reference to an array,
and sometimes a reference to a hash. Often, you can pass any type of argument
and the routine will do whatever is most appropriate. For example, the \fIparam()\fR
routine is used to set a \s-1CGI\s0 parameter to a single or a multi-valued value.
The two cases are shown below:
.PP
.Vb 4
\&    $q\->param(
\&        \-name  => \*(Aqveggie\*(Aq,
\&        \-value => \*(Aqtomato\*(Aq,
\&    );
\&
\&    $q\->param(
\&        \-name  => \*(Aqveggie\*(Aq,
\&        \-value => [ qw/tomato tomahto potato potahto/ ],
\&    );
.Ve
.PP
Many routines will do something useful with a named argument that it doesn't
recognize. For example, you can produce non-standard \s-1HTTP\s0 header fields by
providing them as named arguments:
.PP
.Vb 6
\&    print $q\->header(
\&        \-type            => \*(Aqtext/html\*(Aq,
\&        \-cost            => \*(AqThree smackers\*(Aq,
\&        \-annoyance_level => \*(Aqhigh\*(Aq,
\&        \-complaints_to   => \*(Aqbit bucket\*(Aq,
\&    );
.Ve
.PP
This will produce the following nonstandard \s-1HTTP\s0 header:
.PP
.Vb 5
\&    HTTP/1.0 200 OK
\&    Cost: Three smackers
\&    Annoyance\-level: high
\&    Complaints\-to: bit bucket
\&    Content\-type: text/html
.Ve
.PP
Notice the way that underscores are translated automatically into hyphens.
.SS "Creating a new query object (object-oriented style)"
.IX Subsection "Creating a new query object (object-oriented style)"
.Vb 1
\&    my $q = CGI\->new;
.Ve
.PP
This will parse the input (from \s-1POST, GET\s0 and \s-1DELETE\s0 methods) and store
it into a perl5 object called \f(CW$q\fR. Note that because the input parsing
happens at object instantiation you have to set any \s-1CGI\s0 package variables
that control parsing \fBbefore\fR you call \s-1CGI\-\s0>new.
.PP
Any filehandles from file uploads will have their position reset to the
beginning of the file.
.SS "Creating a new query object from an input file"
.IX Subsection "Creating a new query object from an input file"
.Vb 1
\&    my $q = CGI\->new( $input_filehandle );
.Ve
.PP
If you provide a file handle to the \fInew()\fR method, it will read parameters
from the file (or \s-1STDIN,\s0 or whatever). The file can be in any of the forms
describing below under debugging (i.e. a series of newline delimited
TAG=VALUE pairs will work). Conveniently, this type of file is created by
the \fIsave()\fR method (see below). Multiple records can be saved and restored.
.PP
Perl purists will be pleased to know that this syntax accepts references to
file handles, or even references to filehandle globs, which is the \*(L"official\*(R"
way to pass a filehandle. You can also initialize the \s-1CGI\s0 object with a
FileHandle or IO::File object.
.PP
If you are using the function-oriented interface and want to initialize \s-1CGI\s0
state from a file handle, the way to do this is with \fB\f(BIrestore_parameters()\fB\fR.
This will (re)initialize the default \s-1CGI\s0 object from the indicated file handle.
.PP
.Vb 3
\&    open( my $in_fh,\*(Aq<\*(Aq,"test.in") || die "Couldn\*(Aqt open test.in for read: $!";
\&    restore_parameters( $in_fh );
\&    close( $in_fh );
.Ve
.PP
You can also initialize the query object from a hash reference:
.PP
.Vb 5
\&    my $q = CGI\->new( {
\&        \*(Aqdinosaur\*(Aq => \*(Aqbarney\*(Aq,
\&        \*(Aqsong\*(Aq     => \*(AqI love you\*(Aq,
\&        \*(Aqfriends\*(Aq  => [ qw/ Jessica George Nancy / ]
\&    } );
.Ve
.PP
or from a properly formatted, URL-escaped query string:
.PP
.Vb 1
\&    my $q = CGI\->new(\*(Aqdinosaur=barney&color=purple\*(Aq);
.Ve
.PP
or from a previously existing \s-1CGI\s0 object (currently this clones the parameter
list, but none of the other object-specific fields, such as autoescaping):
.PP
.Vb 2
\&    my $old_query = CGI\->new;
\&    my $new_query = CGI\->new($old_query);
.Ve
.PP
To create an empty query, initialize it from an empty string or hash:
.PP
.Vb 1
\&    my $empty_query = CGI\->new("");
\&
\&       \-or\-
\&
\&    my $empty_query = CGI\->new({});
.Ve
.SS "Fetching a list of keywords from the query"
.IX Subsection "Fetching a list of keywords from the query"
.Vb 1
\&    my @keywords = $q\->keywords
.Ve
.PP
If the script was invoked as the result of an \s-1ISINDEX\s0 search, the parsed
keywords can be obtained as an array using the \fIkeywords()\fR method.
.SS "Fetching the names of all the parameters passed to your script"
.IX Subsection "Fetching the names of all the parameters passed to your script"
.Vb 1
\&    my @names = $q\->multi_param
\&
\&    my @names = $q\->param
.Ve
.PP
If the script was invoked with a parameter list
(e.g. \*(L"name1=value1&name2=value2&name3=value3\*(R"), the \fIparam()\fR / \fImulti_param()\fR
methods will return the parameter names as a list. If the script was invoked
as an \s-1ISINDEX\s0 script and contains a string without ampersands
(e.g. \*(L"value1+value2+value3\*(R"), there will be a single parameter named
\&\*(L"keywords\*(R" containing the \*(L"+\*(R"\-delimited keywords.
.PP
The array of parameter names returned will be in the same order as they were
submitted by the browser. Usually this order is the same as the order in which
the parameters are defined in the form (however, this isn't part of the spec,
and so isn't guaranteed).
.SS "Fetching the value or values of a single named parameter"
.IX Subsection "Fetching the value or values of a single named parameter"
.Vb 1
\&    my @values = $q\->multi_param(\*(Aqfoo\*(Aq);
\&
\&        \-or\-
\&
\&    my $value = $q\->param(\*(Aqfoo\*(Aq);
\&
\&        \-or\-
\&
\&    my @values = $q\->param(\*(Aqfoo\*(Aq); # list context, discouraged and will raise
\&                                   # a warning (use \->multi_param instead)
.Ve
.PP
Pass the \fIparam()\fR / \fImulti_param()\fR method a single argument to fetch the value
of the named parameter. When calling \fIparam()\fR If the parameter is multivalued
(e.g. from multiple selections in a scrolling list), you can ask to receive
an array. Otherwise the method will return the \fBfirst\fR value.
.PP
\&\fBWarning\fR \- calling \fIparam()\fR in list context can lead to vulnerabilities if
you do not sanitise user input as it is possible to inject other param
keys and values into your code. This is why the \fImulti_param()\fR method exists,
to make it clear that a list is being returned, note that \fIparam()\fR can still
be called in list context and will return a list for back compatibility.
.PP
The following code is an example of a vulnerability as the call to param will
be evaluated in list context and thus possibly inject extra keys and values
into the hash:
.PP
.Vb 4
\&    my %user_info = (
\&        id   => 1,
\&        name => $q\->param(\*(Aqname\*(Aq),
\&    );
.Ve
.PP
The fix for the above is to force scalar context on the call to \->param by
prefixing it with \*(L"scalar\*(R"
.PP
.Vb 1
\&    name => scalar $q\->param(\*(Aqname\*(Aq),
.Ve
.PP
If you call \fIparam()\fR in list context with an argument a warning will be raised
by \s-1CGI\s0.pm, you can disable this warning by setting \f(CW$CGI::LIST_CONTEXT_WARN\fR to 0
or by using the \fImulti_param()\fR method instead
.PP
If a value is not given in the query string, as in the queries \*(L"name1=&name2=\*(R",
it will be returned as an empty string.
.PP
If the parameter does not exist at all, then \fIparam()\fR will return undef in scalar
context, and the empty list in a list context.
.SS "Setting the value(s) of a named parameter"
.IX Subsection "Setting the value(s) of a named parameter"
.Vb 1
\&    $q\->param(\*(Aqfoo\*(Aq,\*(Aqan\*(Aq,\*(Aqarray\*(Aq,\*(Aqof\*(Aq,\*(Aqvalues\*(Aq);
.Ve
.PP
This sets the value for the named parameter 'foo' to an array of values. This
is one way to change the value of a field \s-1AFTER\s0 the script has been invoked
once before.
.PP
\&\fIparam()\fR also recognizes a named parameter style of calling described in more
detail later:
.PP
.Vb 4
\&    $q\->param(
\&        \-name   => \*(Aqfoo\*(Aq,
\&        \-values => [\*(Aqan\*(Aq,\*(Aqarray\*(Aq,\*(Aqof\*(Aq,\*(Aqvalues\*(Aq],
\&    );
\&
\&                \-or\-
\&
\&    $q\->param(
\&        \-name  => \*(Aqfoo\*(Aq,
\&        \-value => \*(Aqthe value\*(Aq,
\&    );
.Ve
.SS "Appending additional values to a named parameter"
.IX Subsection "Appending additional values to a named parameter"
.Vb 4
\&    $q\->append(
\&        \-name   =>\*(Aqfoo\*(Aq,
\&        \-values =>[\*(Aqyet\*(Aq,\*(Aqmore\*(Aq,\*(Aqvalues\*(Aq],
\&    );
.Ve
.PP
This adds a value or list of values to the named parameter. The values are
appended to the end of the parameter if it already exists. Otherwise the
parameter is created. Note that this method only recognizes the named argument
calling syntax.
.SS "Importing all parameters into a namespace"
.IX Subsection "Importing all parameters into a namespace"
.Vb 1
\&    $q\->import_names(\*(AqR\*(Aq);
.Ve
.PP
This creates a series of variables in the 'R' namespace. For example, \f(CW$R::foo\fR,
\&\f(CW@R:foo\fR. For keyword lists, a variable \f(CW@R::keywords\fR will appear. If no namespace
is given, this method will assume 'Q'. \fB\s-1WARNING\s0\fR: don't import anything into
\&'main'; this is a major security risk!
.PP
\&\s-1NOTE 1:\s0 Variable names are transformed as necessary into legal perl variable
names. All non-legal characters are transformed into underscores. If you need
to keep the original names, you should use the \fIparam()\fR method instead to access
\&\s-1CGI\s0 variables by name.
.PP
In fact, you should probably not use this method at all given the above caveats
and security risks.
.SS "Deleting a parameter completely"
.IX Subsection "Deleting a parameter completely"
.Vb 1
\&    $q\->delete(\*(Aqfoo\*(Aq,\*(Aqbar\*(Aq,\*(Aqbaz\*(Aq);
.Ve
.PP
This completely clears a list of parameters. It sometimes useful for resetting
parameters that you don't want passed down between script invocations.
.PP
If you are using the function call interface, use \*(L"\fIDelete()\fR\*(R" instead to avoid
conflicts with perl's built-in delete operator.
.SS "Deleting all parameters"
.IX Subsection "Deleting all parameters"
.Vb 1
\&    $q\->delete_all();
.Ve
.PP
This clears the \s-1CGI\s0 object completely. It might be useful to ensure that all
the defaults are taken when you create a fill-out form.
.PP
Use \fIDelete_all()\fR instead if you are using the function call interface.
.SS "Handling non-urlencoded arguments"
.IX Subsection "Handling non-urlencoded arguments"
If POSTed data is not of type application/x\-www\-form\-urlencoded or
multipart/form\-data, then the POSTed data will not be processed, but instead
be returned as-is in a parameter named \s-1POSTDATA.\s0 To retrieve it, use code like
this:
.PP
.Vb 1
\&    my $data = $q\->param(\*(AqPOSTDATA\*(Aq);
.Ve
.PP
Likewise if PUTed and PATCHed data can be retrieved with code like this:
.PP
.Vb 1
\&    my $data = $q\->param(\*(AqPUTDATA\*(Aq);
\&
\&    my $data = $q\->param(\*(AqPATCHDATA\*(Aq);
.Ve
.PP
(If you don't know what the preceding means, worry not. It only affects people
trying to use \s-1CGI\s0 for \s-1XML\s0 processing and other specialized tasks)
.PP
\&\s-1PUTDATA/POSTDATA/PATCHDATA\s0 are also available via
upload_hook,
and as file uploads via \*(L"\-putdata_upload\*(R"
option.
.SS "Direct access to the parameter list"
.IX Subsection "Direct access to the parameter list"
.Vb 2
\&    $q\->param_fetch(\*(Aqaddress\*(Aq)\->[1] = \*(Aq1313 Mockingbird Lane\*(Aq;
\&    unshift @{$q\->param_fetch(\-name=>\*(Aqaddress\*(Aq)},\*(AqGeorge Munster\*(Aq;
.Ve
.PP
If you need access to the parameter list in a way that isn't covered by the
methods given in the previous sections, you can obtain a direct reference to
it by calling the \fB\f(BIparam_fetch()\fB\fR method with the name of the parameter. This
will return an array reference to the named parameter, which you then can
manipulate in any way you like.
.PP
You can also use a named argument style using the \fB\-name\fR argument.
.SS "Fetching the parameter list as a hash"
.IX Subsection "Fetching the parameter list as a hash"
.Vb 4
\&    my $params = $q\->Vars;
\&    print $params\->{\*(Aqaddress\*(Aq};
\&    my @foo = split("\e0",$params\->{\*(Aqfoo\*(Aq});
\&    my %params = $q\->Vars;
\&
\&    use CGI \*(Aq:cgi\-lib\*(Aq;
\&    my $params = Vars();
.Ve
.PP
Many people want to fetch the entire parameter list as a hash in which the keys
are the names of the \s-1CGI\s0 parameters, and the values are the parameters' values.
The \fIVars()\fR method does this. Called in a scalar context, it returns the
parameter list as a tied hash reference. Changing a key changes the value of
the parameter in the underlying \s-1CGI\s0 parameter list. Called in a list context,
it returns the parameter list as an ordinary hash. This allows you to read the
contents of the parameter list, but not to change it.
.PP
When using this, the thing you must watch out for are multivalued \s-1CGI\s0
parameters. Because a hash cannot distinguish between scalar and list context,
multivalued parameters will be returned as a packed string, separated by the
\&\*(L"\e0\*(R" (null) character. You must split this packed string in order to get at the
individual values. This is the convention introduced long ago by Steve Brenner
in his cgi\-lib.pl module for perl version 4, and may be replaced in future
versions with array references.
.PP
If you wish to use \fIVars()\fR as a function, import the \fI:cgi\-lib\fR set of function
calls (also see the section on CGI-LIB compatibility).
.SS "Saving the state of the script to a file"
.IX Subsection "Saving the state of the script to a file"
.Vb 1
\&    $q\->save(\e*FILEHANDLE)
.Ve
.PP
This will write the current state of the form to the provided filehandle. You
can read it back in by providing a filehandle to the \fInew()\fR method. Note that
the filehandle can be a file, a pipe, or whatever.
.PP
The format of the saved file is:
.PP
.Vb 5
\&    NAME1=VALUE1
\&    NAME1=VALUE1\*(Aq
\&    NAME2=VALUE2
\&    NAME3=VALUE3
\&    =
.Ve
.PP
Both name and value are \s-1URL\s0 escaped. Multi-valued \s-1CGI\s0 parameters are represented
as repeated names. A session record is delimited by a single = symbol. You can
write out multiple records and read them back in with several calls to \fBnew\fR.
You can do this across several sessions by opening the file in append mode,
allowing you to create primitive guest books, or to keep a history of users'
queries. Here's a short example of creating multiple session records:
.PP
.Vb 3
\&    use strict;
\&    use warnings;
\&    use CGI;
\&
\&    open (my $out_fh,\*(Aq>>\*(Aq,\*(Aqtest.out\*(Aq) || die "Can\*(Aqt open test.out: $!";
\&    my $records = 5;
\&    for ( 0 .. $records ) {
\&        my $q = CGI\->new;
\&        $q\->param( \-name => \*(Aqcounter\*(Aq,\-value => $_ );
\&        $q\->save( $out_fh );
\&    }
\&    close( $out_fh );
\&
\&    # reopen for reading
\&    open (my $in_fh,\*(Aq<\*(Aq,\*(Aqtest.out\*(Aq) || die "Can\*(Aqt open test.out: $!";
\&    while (!eof($in_fh)) {
\&        my $q = CGI\->new($in_fh);
\&        print $q\->param(\*(Aqcounter\*(Aq),"\en";
\&    }
.Ve
.PP
The file format used for save/restore is identical to that used by the Whitehead
Genome Center's data exchange format \*(L"Boulderio\*(R", and can be manipulated and
even databased using Boulderio utilities. See Boulder for further details.
.PP
If you wish to use this method from the function-oriented (non-OO) interface,
the exported name for this method is \fB\f(BIsave_parameters()\fB\fR.
.SS "Retrieving cgi errors"
.IX Subsection "Retrieving cgi errors"
Errors can occur while processing user input, particularly when processing
uploaded files. When these errors occur, \s-1CGI\s0 will stop processing and return
an empty parameter list. You can test for the existence and nature of errors
using the \fI\fIcgi_error()\fI\fR function. The error messages are formatted as \s-1HTTP\s0
status codes. You can either incorporate the error text into a page, or use
it as the value of the \s-1HTTP\s0 status:
.PP
.Vb 5
\&    if ( my $error = $q\->cgi_error ) {
\&        print $q\->header( \-status => $error );
\&        print "Error: $error";
\&        exit 0;
\&    }
.Ve
.PP
When using the function-oriented interface (see the next section), errors may
only occur the first time you call \fI\fIparam()\fI\fR. Be ready for this!
.SS "Using the function-oriented interface"
.IX Subsection "Using the function-oriented interface"
To use the function-oriented interface, you must specify which \s-1CGI\s0.pm
routines or sets of routines to import into your script's namespace.
There is a small overhead associated with this importation, but it
isn't much.
.PP
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI qw/ list of methods /;
.Ve
.PP
The listed methods will be imported into the current package; you can
call them directly without creating a \s-1CGI\s0 object first. This example
shows how to import the \fB\f(BIparam()\fB\fR and \fB\f(BIheader()\fB\fR
methods, and then use them directly:
.PP
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI qw/ param header /;
\&    print header(\*(Aqtext/plain\*(Aq);
\&    my $zipcode = param(\*(Aqzipcode\*(Aq);
.Ve
.PP
More frequently, you'll import common sets of functions by referring
to the groups by name. All function sets are preceded with a \*(L":\*(R"
character as in \*(L":cgi\*(R" (for \s-1CGI\s0 protocol handling methods).
.PP
Here is a list of the function sets you can import:
.IP "\fB:cgi\fR" 4
.IX Item ":cgi"
Import all CGI-handling methods, such as \fB\f(BIparam()\fB\fR, \fB\f(BIpath_info()\fB\fR
and the like.
.IP "\fB:all\fR" 4
.IX Item ":all"
Import all the available methods. For the full list, see the \s-1CGI\s0.pm
code, where the variable \f(CW%EXPORT_TAGS\fR is defined. (N.B. the :cgi\-lib
imports will \fBnot\fR be included in the :all import, you will have to
import :cgi\-lib to get those)
.PP
Note that in the interests of execution speed \s-1CGI\s0.pm does \fBnot\fR use
the standard Exporter syntax for specifying load symbols. This may
change in the future.
.SS "Pragmas"
.IX Subsection "Pragmas"
In addition to the function sets, there are a number of pragmas that you can
import. Pragmas, which are always preceded by a hyphen, change the way that
\&\s-1CGI\s0.pm functions in various ways. Pragmas, function sets, and individual
functions can all be imported in the same \fIuse()\fR line. For example, the
following use statement imports the cgi set of functions and enables
debugging mode (pragma \-debug):
.PP
.Vb 3
\&    use strict;
\&    use warninigs;
\&    use CGI qw/ :cgi \-debug /;
.Ve
.PP
The current list of pragmas is as follows:
.IP "\-no_undef_params" 4
.IX Item "-no_undef_params"
This keeps \s-1CGI\s0.pm from including undef params in the parameter list.
.IP "\-utf8" 4
.IX Item "-utf8"
This makes \s-1CGI\s0.pm treat all parameters as text strings rather than binary
strings (see perlunitut for the distinction), assuming \s-1UTF\-8\s0 for the
encoding.
.Sp
\&\s-1CGI\s0.pm does the decoding from the \s-1UTF\-8\s0 encoded input data, restricting this
decoding to input text as distinct from binary upload data which are left
untouched. Therefore, a ':utf8' layer must \fBnot\fR be used on \s-1STDIN.\s0
.Sp
If you do not use this option you can manually select which fields are
expected to return utf\-8 strings and convert them using code like this:
.Sp
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI;
\&    use Encode qw/ decode /;
\&
\&    my $cgi   = CGI\->new;
\&    my $param = $cgi\->param(\*(Aqfoo\*(Aq);
\&    $param    = decode( \*(AqUTF\-8\*(Aq,$param );
.Ve
.IP "\-putdata_upload / \-postdata_upload / \-patchdata_upload" 4
.IX Item "-putdata_upload / -postdata_upload / -patchdata_upload"
Makes \f(CW\*(C`$cgi\->param(\*(AqPUTDATA\*(Aq);\*(C'\fR, \f(CW\*(C`$cgi\->param(\*(AqPATCHDATA\*(Aq);\*(C'\fR,
and \f(CW\*(C`$cgi\->param(\*(AqPOSTDATA\*(Aq);\*(C'\fR act like file uploads named \s-1PUTDATA,
PATCHDATA,\s0 and \s-1POSTDATA.\s0 See \*(L"Handling non-urlencoded arguments\*(R" and
\&\*(L"Processing a file upload field\*(R" \s-1PUTDATA/POSTDATA/PATCHDATA\s0 are also available
via upload_hook.
.IP "\-nph" 4
.IX Item "-nph"
This makes \s-1CGI\s0.pm produce a header appropriate for an \s-1NPH \s0(no parsed header)
script. You may need to do other things as well to tell the server that the
script is \s-1NPH.\s0 See the discussion of \s-1NPH\s0 scripts below.
.IP "\-newstyle_urls" 4
.IX Item "-newstyle_urls"
Separate the name=value pairs in \s-1CGI\s0 parameter query strings with semicolons
rather than ampersands. For example:
.Sp
.Vb 1
\&    ?name=fred;age=24;favorite_color=3
.Ve
.Sp
Semicolon-delimited query strings are always accepted, and will be emitted by
\&\fIself_url()\fR and \fIquery_string()\fR. newstyle_urls became the default in version
2.64.
.IP "\-oldstyle_urls" 4
.IX Item "-oldstyle_urls"
Separate the name=value pairs in \s-1CGI\s0 parameter query strings with ampersands
rather than semicolons. This is no longer the default.
.IP "\-no_debug" 4
.IX Item "-no_debug"
This turns off the command-line processing features. If you want to run a \s-1CGI\s0.pm
script from the command line, and you don't want it to read \s-1CGI\s0 parameters from
the command line or \s-1STDIN,\s0 then use this pragma:
.Sp
.Vb 1
\&   use CGI qw/ \-no_debug :standard /;
.Ve
.IP "\-debug" 4
.IX Item "-debug"
This turns on full debugging. In addition to reading \s-1CGI\s0 arguments from the
command-line processing, \s-1CGI\s0.pm will pause and try to read arguments from \s-1STDIN,\s0
producing the message \*(L"(offline mode: enter name=value pairs on standard input)\*(R"
features.
.Sp
See the section on debugging for more details.
.SH "GENERATING DYNAMIC DOCUMENTS"
.IX Header "GENERATING DYNAMIC DOCUMENTS"
Most of \s-1CGI\s0.pm's functions deal with creating documents on the fly. Generally
you will produce the \s-1HTTP\s0 header first, followed by the document itself. \s-1CGI\s0.pm
provides functions for generating \s-1HTTP\s0 headers of various types.
.PP
Each of these functions produces a fragment of \s-1HTTP\s0 which you can print out
directly so that it is processed by the browser, appended to a string, or saved
to a file for later use.
.SS "Creating a standard http header"
.IX Subsection "Creating a standard http header"
Normally the first thing you will do in any \s-1CGI\s0 script is print out an \s-1HTTP\s0
header. This tells the browser what type of document to expect, and gives other
optional information, such as the language, expiration date, and whether to
cache the document. The header can also be manipulated for special purposes,
such as server push and pay per view pages.
.PP
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI;
\&
\&    my $cgi = CGI\->new;
\&
\&    print $cgi\->header;
\&
\&        \-or\-
\&
\&    print $cgi\->header(\*(Aqimage/gif\*(Aq);
\&
\&        \-or\-
\&
\&    print $cgi\->header(\*(Aqtext/html\*(Aq,\*(Aq204 No response\*(Aq);
\&
\&        \-or\-
\&
\&    print $cgi\->header(
\&        \-type       => \*(Aqimage/gif\*(Aq,
\&        \-nph        => 1,
\&        \-status     => \*(Aq402 Payment required\*(Aq,
\&        \-expires    => \*(Aq+3d\*(Aq,
\&        \-cookie     => $cookie,
\&        \-charset    => \*(Aqutf\-8\*(Aq,
\&        \-attachment => \*(Aqfoo.gif\*(Aq,
\&        \-Cost       => \*(Aq$2.00\*(Aq
\&    );
.Ve
.PP
\&\fIheader()\fR returns the Content-type: header. You can provide your own \s-1MIME\s0 type
if you choose, otherwise it defaults to text/html. An optional second parameter
specifies the status code and a human-readable message. For example, you can
specify 204, \*(L"No response\*(R" to create a script that tells the browser to do
nothing at all. Note that \s-1RFC 2616\s0 expects the human-readable phase to be there
as well as the numeric status code.
.PP
The last example shows the named argument style for passing arguments to the \s-1CGI\s0
methods using named parameters. Recognized parameters are \fB\-type\fR, \fB\-status\fR,
\&\fB\-expires\fR, and \fB\-cookie\fR. Any other named parameters will be stripped of
their initial hyphens and turned into header fields, allowing you to specify
any \s-1HTTP\s0 header you desire. Internal underscores will be turned into hyphens:
.PP
.Vb 1
\&    print $cgi\->header( \-Content_length => 3002 );
.Ve
.PP
Most browsers will not cache the output from \s-1CGI\s0 scripts. Every time the browser
reloads the page, the script is invoked anew. You can change this behavior with
the \fB\-expires\fR parameter. When you specify an absolute or relative expiration
interval with this parameter, some browsers and proxy servers will cache the
script's output until the indicated expiration date. The following forms are all
valid for the \-expires field:
.PP
.Vb 8
\&    +30s                                  30 seconds from now
\&    +10m                                  ten minutes from now
\&    +1h                                   one hour from now
\&    \-1d                                   yesterday (i.e. "ASAP!")
\&    now                                   immediately
\&    +3M                                   in three months
\&    +10y                                  in ten years time
\&    Thursday, 25\-Apr\-2018 00:40:33 GMT    at the indicated time & date
.Ve
.PP
The \fB\-cookie\fR parameter generates a header that tells the browser to provide
a \*(L"magic cookie\*(R" during all subsequent transactions with your script. Some
cookies have a special format that includes interesting attributes such as
expiration time. Use the \fIcookie()\fR method to create and retrieve session cookies.
.PP
The \fB\-nph\fR parameter, if set to a true value, will issue the correct headers
to work with a \s-1NPH \s0(no-parse-header) script. This is important to use with
certain servers that expect all their scripts to be \s-1NPH.\s0
.PP
The \fB\-charset\fR parameter can be used to control the character set sent to the
browser. If not provided, defaults to \s-1ISO\-8859\-1.\s0 As a side effect, this sets
the \fIcharset()\fR method as well. \fBNote\fR that the default being \s-1ISO\-8859\-1\s0 may not
make sense for all content types, e.g.:
.PP
.Vb 1
\&    Content\-Type: image/gif; charset=ISO\-8859\-1
.Ve
.PP
In the above case you need to pass \-charset => '' to prevent the default being
used.
.PP
The \fB\-attachment\fR parameter can be used to turn the page into an attachment.
Instead of displaying the page, some browsers will prompt the user to save it
to disk. The value of the argument is the suggested name for the saved file. In
order for this to work, you may have to set the \fB\-type\fR to
\&\*(L"application/octet\-stream\*(R".
.PP
The \fB\-p3p\fR parameter will add a P3P tag to the outgoing header. The parameter
can be an arrayref or a space-delimited string of P3P tags. For example:
.PP
.Vb 2
\&    print $cgi\->header( \-p3p => [ qw/ CAO DSP LAW CURa / ] );
\&    print $cgi\->header( \-p3p => \*(AqCAO DSP LAW CURa\*(Aq );
.Ve
.PP
In either case, the outgoing header will be formatted as:
.PP
.Vb 1
\&    P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
.Ve
.PP
\&\s-1CGI\s0.pm will accept valid multi-line headers when each line is separated with a
\&\s-1CRLF\s0 value (\*(L"\er\en\*(R" on most platforms) followed by at least one space. For
example:
.PP
.Vb 1
\&    print $cgi\->header( \-ingredients => "ham\er\en\eseggs\er\en\esbacon" );
.Ve
.PP
Invalid multi-line header input will trigger in an exception. When multi-line
headers are received, \s-1CGI\s0.pm will always output them back as a single line,
according to the folding rules of \s-1RFC 2616:\s0 the newlines will be removed, while
the white space remains.
.SS "Generating a redirection header"
.IX Subsection "Generating a redirection header"
.Vb 1
\&    print $q\->redirect( \*(Aqhttp://somewhere.else/in/movie/land\*(Aq );
.Ve
.PP
Sometimes you don't want to produce a document yourself, but simply redirect
the browser elsewhere, perhaps choosing a \s-1URL\s0 based on the time of day or the
identity of the user.
.PP
The \fIredirect()\fR method redirects the browser to a different \s-1URL.\s0 If you use
redirection like this, you should \fBnot\fR print out a header as well.
.PP
You are advised to use full URLs (absolute with respect to current \s-1URL\s0 or even
including the http: or ftp: part) in redirection requests as relative URLs
are resolved by the user agent of the client so may not do what you want or
expect them to do.
.PP
You can also use named arguments:
.PP
.Vb 5
\&    print $q\->redirect(
\&        \-uri    => \*(Aqhttp://somewhere.else/in/movie/land\*(Aq,
\&        \-nph    => 1,
\&        \-status => \*(Aq301 Moved Permanently\*(Aq
\&    );
.Ve
.PP
All names arguments recognized by \fIheader()\fR are also recognized by \fIredirect()\fR.
However, most \s-1HTTP\s0 headers, including those generated by \-cookie and \-target,
are ignored by the browser.
.PP
The \fB\-nph\fR parameter, if set to a true value, will issue the correct headers
to work with a \s-1NPH \s0(no-parse-header) script. This is important to use with
certain servers, such as Microsoft \s-1IIS,\s0 which expect all their scripts to be
\&\s-1NPH.\s0
.PP
The \fB\-status\fR parameter will set the status of the redirect. \s-1HTTP\s0 defines
several different possible redirection status codes, and the default if not
specified is 302, which means \*(L"moved temporarily.\*(R" You may change the status
to another status code if you wish.
.PP
Note that the human-readable phrase is also expected to be present to conform
with \s-1RFC 2616,\s0 section 6.1.
.SS "Creating a self-referencing url that preserves state information"
.IX Subsection "Creating a self-referencing url that preserves state information"
.Vb 2
\&    my $myself = $q\->self_url;
\&    print qq(<a href="$myself">I\*(Aqm talking to myself.</a>);
.Ve
.PP
\&\fIself_url()\fR will return a \s-1URL,\s0 that, when selected, will re-invoke this script
with all its state information intact. This is most useful when you want to
jump around within the document using internal anchors but you don't want to
disrupt the current contents of the form(s). Something like this will do the
trick:
.PP
.Vb 4
\&     my $myself = $q\->self_url;
\&     print "<a href=\e"$myself#table1\e">See table 1</a>";
\&     print "<a href=\e"$myself#table2\e">See table 2</a>";
\&     print "<a href=\e"$myself#yourself\e">See for yourself</a>";
.Ve
.PP
If you want more control over what's returned, using the \fB\f(BIurl()\fB\fR method
instead.
.PP
You can also retrieve a query string representation of the current object
state with \fIquery_string()\fR:
.PP
.Vb 1
\&    my $the_string = $q\->query_string();
.Ve
.PP
The behavior of calling query_string is currently undefined when the \s-1HTTP\s0 method
is something other than \s-1GET.\s0
.PP
If you want to retrieved the query string as set in the webserver, namely the
environment variable, you can call \fIenv_query_string()\fR
.SS "Obtaining the script's url"
.IX Subsection "Obtaining the script's url"
.Vb 7
\&    my $full_url      = url();
\&    my $full_url      = url( \-full =>1 );  # alternative syntax
\&    my $relative_url  = url( \-relative => 1 );
\&    my $absolute_url  = url( \-absolute =>1 );
\&    my $url_with_path = url( \-path_info => 1 );
\&    my $url_path_qry  = url( \-path_info => 1, \-query =>1 );
\&    my $netloc        = url( \-base => 1 );
.Ve
.PP
\&\fB\f(BIurl()\fB\fR returns the script's \s-1URL\s0 in a variety of formats. Called without any
arguments, it returns the full form of the \s-1URL,\s0 including host name and port
number
.PP
.Vb 1
\&    http://your.host.com/path/to/script.cgi
.Ve
.PP
You can modify this format with the following named arguments:
.IP "\fB\-absolute\fR" 4
.IX Item "-absolute"
If true, produce an absolute \s-1URL,\s0 e.g.
.Sp
.Vb 1
\&    /path/to/script.cgi
.Ve
.IP "\fB\-relative\fR" 4
.IX Item "-relative"
Produce a relative \s-1URL.\s0 This is useful if you want to re-invoke your
script with different parameters. For example:
.Sp
.Vb 1
\&    script.cgi
.Ve
.IP "\fB\-full\fR" 4
.IX Item "-full"
Produce the full \s-1URL,\s0 exactly as if called without any arguments. This overrides
the \-relative and \-absolute arguments.
.IP "\fB\-path\fR (\fB\-path_info\fR)" 4
.IX Item "-path (-path_info)"
Append the additional path information to the \s-1URL.\s0 This can be combined with
\&\fB\-full\fR, \fB\-absolute\fR or \fB\-relative\fR. \fB\-path_info\fR is provided as a synonym.
.IP "\fB\-query\fR (\fB\-query_string\fR)" 4
.IX Item "-query (-query_string)"
Append the query string to the \s-1URL.\s0 This can be combined with \fB\-full\fR,
\&\fB\-absolute\fR or \fB\-relative\fR. \fB\-query_string\fR is provided as a synonym.
.IP "\fB\-base\fR" 4
.IX Item "-base"
Generate just the protocol and net location, as in http://www.foo.com:8000
.IP "\fB\-rewrite\fR" 4
.IX Item "-rewrite"
If Apache's mod_rewrite is turned on, then the script name and path info
probably won't match the request that the user sent. Set \-rewrite => 1 (default)
to return URLs that match what the user sent (the original request \s-1URI\s0). Set
\&\-rewrite => 0 to return URLs that match the \s-1URL\s0 after the mod_rewrite rules have
run.
.SS "Mixing post and url parameters"
.IX Subsection "Mixing post and url parameters"
.Vb 1
\&    my $color = url_param(\*(Aqcolor\*(Aq);
.Ve
.PP
It is possible for a script to receive \s-1CGI\s0 parameters in the \s-1URL\s0 as well as in
the fill-out form by creating a form that POSTs to a \s-1URL\s0 containing a query
string (a \*(L"?\*(R" mark followed by arguments). The \fB\f(BIparam()\fB\fR method will always
return the contents of the POSTed fill-out form, ignoring the \s-1URL\s0's query
string. To retrieve \s-1URL\s0 parameters, call the \fB\f(BIurl_param()\fB\fR method. Use it in
the same way as \fB\f(BIparam()\fB\fR. The main difference is that it allows you to read
the parameters, but not set them.
.PP
Under no circumstances will the contents of the \s-1URL\s0 query string interfere with
similarly-named \s-1CGI\s0 parameters in POSTed forms. If you try to mix a \s-1URL\s0 query
string with a form submitted with the \s-1GET\s0 method, the results will not be what
you expect.
.PP
If running from the command line, \f(CW\*(C`url_param\*(C'\fR will not pick up any
parameters given on the command line.
.SS "Processing a file upload field"
.IX Subsection "Processing a file upload field"
\fIBasics\fR
.IX Subsection "Basics"
.PP
When the form is processed, you can retrieve an IO::File compatible handle
for a file upload field like this:
.PP
.Vb 1
\&    use autodie;
\&
\&    # undef may be returned if it\*(Aqs not a valid file handle
\&    if ( my $io_handle = $q\->upload(\*(Aqfield_name\*(Aq) ) {
\&        open ( my $out_file,\*(Aq>>\*(Aq,\*(Aq/usr/local/web/users/feedback\*(Aq );
\&        while ( my $bytesread = $io_handle\->read($buffer,1024) ) {
\&            print $out_file $buffer;
\&        }
\&    }
.Ve
.PP
In a list context, \fIupload()\fR will return an array of filehandles. This makes it
possible to process forms that use the same name for multiple upload fields.
.PP
If you want the entered file name for the file, you can just call \fIparam()\fR:
.PP
.Vb 1
\&    my $filename = $q\->param(\*(Aqfield_name\*(Aq);
.Ve
.PP
Different browsers will return slightly different things for the name. Some
browsers return the filename only. Others return the full path to the file,
using the path conventions of the user's machine. Regardless, the name returned
is always the name of the file on the \fIuser's\fR machine, and is unrelated to
the name of the temporary file that \s-1CGI\s0.pm creates during upload spooling
(see below).
.PP
When a file is uploaded the browser usually sends along some information along
with it in the format of headers. The information usually includes the \s-1MIME\s0
content type. To retrieve this information, call \fIuploadInfo()\fR. It returns a
reference to a hash containing all the document headers.
.PP
.Vb 5
\&    my $filehandle = $q\->upload( \*(Aquploaded_file\*(Aq );
\&    my $type       = $q\->uploadInfo( $filehandle )\->{\*(AqContent\-Type\*(Aq};
\&    if ( $type ne \*(Aqtext/html\*(Aq ) {
\&        die "HTML FILES ONLY!";
\&    }
.Ve
.PP
Note that you must use \->upload or \->param to get the file-handle to pass into
uploadInfo as internally this is represented as a File::Temp object (which is
what will be returned by \->upload or \->param). When using \->Vars you will get
the literal filename rather than the File::Temp object, which will not return
anything when passed to uploadInfo. So don't use \->Vars.
.PP
If you are using a machine that recognizes \*(L"text\*(R" and \*(L"binary\*(R" data modes, be
sure to understand when and how to use them (see the Camel book). Otherwise
you may find that binary files are corrupted during file uploads.
.PP
\fIAccessing the temp files directly\fR
.IX Subsection "Accessing the temp files directly"
.PP
When processing an uploaded file, \s-1CGI\s0.pm creates a temporary file on your hard
disk and passes you a file handle to that file. After you are finished with the
file handle, \s-1CGI\s0.pm unlinks (deletes) the temporary file. If you need to you
can access the temporary file directly. You can access the temp file for a file
upload by passing the file name to the \fItmpFileName()\fR method:
.PP
.Vb 2
\&    my $filehandle  = $q\->upload( \*(Aquploaded_file\*(Aq );
\&    my $tmpfilename = $q\->tmpFileName( $filehandle );
.Ve
.PP
As with \->uploadInfo, using the reference returned by \->upload or \->param is
preferred, although unlike \->uploadInfo, plain filenames also work if possible
for backwards compatibility.
.PP
The temporary file will be deleted automatically when your program exits unless
you manually rename it or set \f(CW$CGI::UNLINK_TMP_FILES\fR to 0. On some operating
systems (such as Windows \s-1NT\s0), you will need to close the temporary file's
filehandle before your program exits. Otherwise the attempt to delete the
temporary file will fail.
.PP
\fIChanges in temporary file handling (v4.05+)\fR
.IX Subsection "Changes in temporary file handling (v4.05+)"
.PP
\&\s-1CGI\s0.pm had its temporary file handling significantly refactored, this logic is
now all deferred to File::Temp (which is wrapped in a compatibility object,
CGI::File::Temp \- \fB\s-1DO NOT USE THIS PACKAGE DIRECTLY\s0\fR). As a consequence the
\&\s-1PRIVATE_TEMPFILES\s0 variable has been removed along with deprecation of the
private_tempfiles routine and \fBcomplete\fR removal of the CGITempFile package.
The \f(CW$CGITempFile::TMPDIRECTORY\fR is no longer used to set the temp directory,
refer to the perldoc for File::Temp if you want to override the default
settings in that package (the \s-1TMPDIR\s0 env variable is still available on some
platforms). For Windows platforms the temporary directory order remains
as before: \s-1TEMP \s0> \s-1TMP \s0> \s-1WINDIR \s0( > \s-1TMPDIR \s0) so if you have any of these in
use in existing scripts they should still work.
.PP
The Fh package still exists but does nothing, the CGI::File::Temp class is
a subclass of both File::Temp and the empty Fh package, so if you have any
code that checks that the filehandle isa Fh this should still work.
.PP
When you get the internal file handle you will receive a File::Temp object,
this should be transparent as File::Temp isa IO::Handle and isa IO::Seekable
meaning it behaves as previously. If you are doing anything out of the ordinary
with regards to temp files you should test your code before deploying this
update and refer to the File::Temp documentation for more information.
.PP
\fIHandling interrupted file uploads\fR
.IX Subsection "Handling interrupted file uploads"
.PP
There are occasionally problems involving parsing the uploaded file. This
usually happens when the user presses \*(L"Stop\*(R" before the upload is finished. In
this case, \s-1CGI\s0.pm will return undef for the name of the uploaded file and set
\&\fI\fIcgi_error()\fI\fR to the string \*(L"400 Bad request (malformed multipart \s-1POST\s0)\*(R". This
error message is designed so that you can incorporate it into a status code to
be sent to the browser. Example:
.PP
.Vb 5
\&    my $file = $q\->upload( \*(Aquploaded_file\*(Aq );
\&    if ( !$file && $q\->cgi_error ) {
\&        print $q\->header( \-status => $q\->cgi_error );
\&        exit 0;
\&    }
.Ve
.PP
\fIProgress bars for file uploads and avoiding temp files\fR
.IX Subsection "Progress bars for file uploads and avoiding temp files"
.PP
\&\s-1CGI\s0.pm gives you low-level access to file upload management through a file
upload hook. You can use this feature to completely turn off the temp file
storage of file uploads, or potentially write your own file upload progress
meter.
.PP
This is much like the \s-1UPLOAD_HOOK\s0 facility available in Apache::Request,
with the exception that the first argument to the callback is an
Apache::Upload object, here it's the remote filename.
.PP
.Vb 1
\&    my $q = CGI\->new( \e&hook [,$data [,$use_tempfile]] );
\&
\&    sub hook {
\&        my ( $filename, $buffer, $bytes_read, $data ) = @_;
\&        print "Read $bytes_read bytes of $filename\en";
\&    }
.Ve
.PP
The \f(CW$data\fR field is optional; it lets you pass configuration information
(e.g. a database handle) to your hook callback.
.PP
The \f(CW$use_tempfile\fR field is a flag that lets you turn on and off \s-1CGI\s0.pm's
use of a temporary disk-based file during file upload. If you set this to a
\&\s-1FALSE\s0 value (default true) then \f(CW$q\fR\->param('uploaded_file') will no longer work,
and the only way to get at the uploaded data is via the hook you provide.
.PP
If using the function-oriented interface, call the \fICGI::upload_hook()\fR method
before calling \fIparam()\fR or any other \s-1CGI\s0 functions:
.PP
.Vb 1
\&    CGI::upload_hook( \e&hook [,$data [,$use_tempfile]] );
.Ve
.PP
This method is not exported by default. You will have to import it explicitly
if you wish to use it without the \s-1CGI::\s0 prefix.
.PP
\fITroubleshooting file uploads on Windows\fR
.IX Subsection "Troubleshooting file uploads on Windows"
.PP
If you are using \s-1CGI\s0.pm on a Windows platform and find that binary files get
slightly larger when uploaded but that text files remain the same, then you
have forgotten to activate binary mode on the output filehandle. Be sure to call
\&\fIbinmode()\fR on any handle that you create to write the uploaded file to disk.
.PP
\fIOlder ways to process file uploads\fR
.IX Subsection "Older ways to process file uploads"
.PP
This section is here for completeness. if you are building a new application
with \s-1CGI\s0.pm, you can skip it.
.PP
The original way to process file uploads with \s-1CGI\s0.pm was to use \fIparam()\fR. The
value it returns has a dual nature as both a file name and a lightweight
filehandle. This dual nature is problematic if you following the recommended
practice of having \f(CW\*(C`use strict\*(C'\fR in your code. perl will complain when you try
to use a string as a filehandle. More seriously, it is possible for the remote
user to type garbage into the upload field, in which case what you get from
\&\fIparam()\fR is not a filehandle at all, but a string.
.PP
To solve this problem the \fIupload()\fR method was added, which always returns a
lightweight filehandle. This generally works well, but will have trouble
interoperating with some other modules because the file handle is not derived
from IO::File. So that brings us to current recommendation given above,
which is to call the \fIhandle()\fR method on the file handle returned by \fIupload()\fR.
That upgrades the handle to an IO::File. It's a big win for compatibility for
a small penalty of loading IO::File the first time you call it.
.SH "HTTP COOKIES"
.IX Header "HTTP COOKIES"
\&\s-1CGI\s0.pm has several methods that support cookies.
.PP
A cookie is a name=value pair much like the named parameters in a \s-1CGI\s0 query
string. \s-1CGI\s0 scripts create one or more cookies and send them to the browser
in the \s-1HTTP\s0 header. The browser maintains a list of cookies that belong to a
particular Web server, and returns them to the \s-1CGI\s0 script during subsequent
interactions.
.PP
In addition to the required name=value pair, each cookie has several optional
attributes:
.IP "1. an expiration time" 4
.IX Item "1. an expiration time"
This is a time/date string (in a special \s-1GMT\s0 format) that indicates when a
cookie expires. The cookie will be saved and returned to your script until this
expiration date is reached if the user exits the browser and restarts it. If an
expiration date isn't specified, the cookie will remain active until the user
quits the browser.
.IP "2. a domain" 4
.IX Item "2. a domain"
This is a partial or complete domain name for which the cookie is valid. The
browser will return the cookie to any host that matches the partial domain name.
For example, if you specify a domain name of \*(L".capricorn.com\*(R", then the browser
will return the cookie to Web servers running on any of the machines
\&\*(L"www.capricorn.com\*(R", \*(L"www2.capricorn.com\*(R", \*(L"feckless.capricorn.com\*(R", etc. Domain
names must contain at least two periods to prevent attempts to match on top
level domains like \*(L".edu\*(R". If no domain is specified, then the browser will
only return the cookie to servers on the host the cookie originated from.
.IP "3. a path" 4
.IX Item "3. a path"
If you provide a cookie path attribute, the browser will check it against your
script's \s-1URL\s0 before returning the cookie. For example, if you specify the path
\&\*(L"/cgi\-bin\*(R", then the cookie will be returned to each of the scripts
\&\*(L"/cgi\-bin/tally.pl\*(R", \*(L"/cgi\-bin/order.pl\*(R", and
\&\*(L"/cgi\-bin/customer_service/complain.pl\*(R", but not to the script
\&\*(L"/cgi\-private/site_admin.pl\*(R". By default, path is set to \*(L"/\*(R", which causes the
cookie to be sent to any \s-1CGI\s0 script on your site.
.ie n .IP "4. a ""secure"" flag" 4
.el .IP "4. a ``secure'' flag" 4
.IX Item "4. a secure flag"
If the \*(L"secure\*(R" attribute is set, the cookie will only be sent to your script
if the \s-1CGI\s0 request is occurring on a secure channel, such as \s-1SSL.\s0
.PP
The interface to \s-1HTTP\s0 cookies is the \fB\f(BIcookie()\fB\fR method:
.PP
.Vb 8
\&    my $cookie = $q\->cookie(
\&        \-name    => \*(AqsessionID\*(Aq,
\&        \-value   => \*(Aqxyzzy\*(Aq,
\&        \-expires => \*(Aq+1h\*(Aq,
\&        \-path    => \*(Aq/cgi\-bin/database\*(Aq,
\&        \-domain  => \*(Aq.capricorn.org\*(Aq,
\&        \-secure  => 1
\&    );
\&
\&    print $q\->header( \-cookie => $cookie );
.Ve
.PP
\&\fB\f(BIcookie()\fB\fR creates a new cookie. Its parameters include:
.IP "\fB\-name\fR" 4
.IX Item "-name"
The name of the cookie (required). This can be any string at all. Although
browsers limit their cookie names to non-whitespace alphanumeric characters,
\&\s-1CGI\s0.pm removes this restriction by escaping and unescaping cookies behind the
scenes.
.IP "\fB\-value\fR" 4
.IX Item "-value"
The value of the cookie. This can be any scalar value, array reference, or even
hash reference. For example, you can store an entire hash into a cookie this
way:
.Sp
.Vb 4
\&    my $cookie = $q\->cookie(
\&        \-name  => \*(Aqfamily information\*(Aq,
\&        \-value => \e%childrens_ages
\&    );
.Ve
.IP "\fB\-path\fR" 4
.IX Item "-path"
The optional partial path for which this cookie will be valid, as described
above.
.IP "\fB\-domain\fR" 4
.IX Item "-domain"
The optional partial domain for which this cookie will be valid, as described
above.
.IP "\fB\-expires\fR" 4
.IX Item "-expires"
The optional expiration date for this cookie. The format is as described in the
section on the \fB\f(BIheader()\fB\fR method:
.Sp
.Vb 1
\&    "+1h"  one hour from now
.Ve
.IP "\fB\-secure\fR" 4
.IX Item "-secure"
If set to true, this cookie will only be used within a secure \s-1SSL\s0 session.
.PP
The cookie created by \fIcookie()\fR must be incorporated into the \s-1HTTP\s0 header within
the string returned by the \fIheader()\fR method:
.PP
.Vb 2
\&    use strict;
\&    use warnings;
\&
\&    use CGI;
\&
\&    my $q      = CGI\->new;
\&    my $cookie = ...
\&    print $q\->header( \-cookie => $cookie );
.Ve
.PP
To create multiple cookies, give \fIheader()\fR an array reference:
.PP
.Vb 4
\&    my $cookie1 = $q\->cookie(
\&        \-name  => \*(Aqriddle_name\*(Aq,
\&        \-value => "The Sphynx\*(Aqs Question"
\&    );
\&
\&    my $cookie2 = $q\->cookie(
\&        \-name  => \*(Aqanswers\*(Aq,
\&        \-value => \e%answers
\&    );
\&
\&    print $q\->header( \-cookie => [ $cookie1,$cookie2 ] );
.Ve
.PP
To retrieve a cookie, request it by name by calling \fIcookie()\fR method without the
\&\fB\-value\fR parameter. This example uses the object-oriented form:
.PP
.Vb 2
\&    my $riddle  = $q\->cookie(\*(Aqriddle_name\*(Aq);
\&    my %answers = $q\->cookie(\*(Aqanswers\*(Aq);
.Ve
.PP
Cookies created with a single scalar value, such as the \*(L"riddle_name\*(R" cookie,
will be returned in that form. Cookies with array and hash values can also be
retrieved.
.PP
The cookie and \s-1CGI\s0 namespaces are separate. If you have a parameter named
\&'answers' and a cookie named 'answers', the values retrieved by \fIparam()\fR and
\&\fIcookie()\fR are independent of each other. However, it's simple to turn a \s-1CGI\s0
parameter into a cookie, and vice-versa:
.PP
.Vb 4
\&    # turn a CGI parameter into a cookie
\&    my $c = cookie( \-name => \*(Aqanswers\*(Aq,\-value => [$q\->param(\*(Aqanswers\*(Aq)] );
\&    # vice\-versa
\&    $q\->param( \-name => \*(Aqanswers\*(Aq,\-value => [ $q\->cookie(\*(Aqanswers\*(Aq)] );
.Ve
.PP
If you call \fIcookie()\fR without any parameters, it will return a list of
the names of all cookies passed to your script:
.PP
.Vb 1
\&    my @cookies = $q\->cookie();
.Ve
.PP
See the \fBcookie.cgi\fR example script for some ideas on how to use cookies
effectively.
.SH "DEBUGGING"
.IX Header "DEBUGGING"
If you are running the script from the command line or in the perl debugger,
you can pass the script a list of keywords or parameter=value pairs on the
command line or from standard input (you don't have to worry about tricking
your script into reading from environment variables). You can pass keywords
like this:
.PP
.Vb 1
\&    your_script.pl keyword1 keyword2 keyword3
.Ve
.PP
or this:
.PP
.Vb 1
\&   your_script.pl keyword1+keyword2+keyword3
.Ve
.PP
or this:
.PP
.Vb 1
\&    your_script.pl name1=value1 name2=value2
.Ve
.PP
or this:
.PP
.Vb 1
\&    your_script.pl name1=value1&name2=value2
.Ve
.PP
To turn off this feature, use the \-no_debug pragma.
.PP
To test the \s-1POST\s0 method, you may enable full debugging with the \-debug pragma.
This will allow you to feed newline-delimited name=value pairs to the script on
standard input.
.PP
When debugging, you can use quotes and backslashes to escape characters in the
familiar shell manner, letting you place spaces and other funny characters in
your parameter=value pairs:
.PP
.Vb 1
\&    your_script.pl "name1=\*(AqI am a long value\*(Aq" "name2=two\e words"
.Ve
.PP
Finally, you can set the path info for the script by prefixing the first
name/value parameter with the path followed by a question mark (?):
.PP
.Vb 1
\&    your_script.pl /your/path/here?name1=value1&name2=value2
.Ve
.SH "FETCHING ENVIRONMENT VARIABLES"
.IX Header "FETCHING ENVIRONMENT VARIABLES"
Some of the more useful environment variables can be fetched through this
interface. The methods are as follows:
.IP "\fB\f(BIAccept()\fB\fR" 4
.IX Item "Accept()"
Return a list of \s-1MIME\s0 types that the remote browser accepts. If you give this
method a single argument corresponding to a \s-1MIME\s0 type, as in
Accept('text/html'), it will return a floating point value corresponding to the
browser's preference for this type from 0.0 (don't want) to 1.0. Glob types
(e.g. text/*) in the browser's accept list are handled correctly.
.Sp
Note that the capitalization changed between version 2.43 and 2.44 in order to
avoid conflict with perl's \fIaccept()\fR function.
.IP "\fB\f(BIraw_cookie()\fB\fR" 4
.IX Item "raw_cookie()"
Returns the \s-1HTTP_COOKIE\s0 variable. Cookies have a special format, and this
method call just returns the raw form (?cookie dough). See \fIcookie()\fR for ways
of setting and retrieving cooked cookies.
.Sp
Called with no parameters, \fIraw_cookie()\fR returns the packed cookie structure.
You can separate it into individual cookies by splitting on the character
sequence \*(L"; \*(R". Called with the name of a cookie, retrieves the \fBunescaped\fR
form of the cookie. You can use the regular \fIcookie()\fR method to get the names,
or use the \fIraw_fetch()\fR method from the CGI::Cookie module.
.IP "\fB\f(BIenv_query_string()\fB\fR" 4
.IX Item "env_query_string()"
Returns the \s-1QUERY_STRING\s0 variable, note that this is the original value as set
in the environment by the webserver and (possibly) not the same value as
returned by \fIquery_string()\fR, which represents the object state
.IP "\fB\f(BIuser_agent()\fB\fR" 4
.IX Item "user_agent()"
Returns the \s-1HTTP_USER_AGENT\s0 variable. If you give this method a single
argument, it will attempt to pattern match on it, allowing you to do something
like user_agent(Mozilla);
.IP "\fB\f(BIpath_info()\fB\fR" 4
.IX Item "path_info()"
Returns additional path information from the script \s-1URL. E.G.\s0 fetching
/cgi\-bin/your_script/additional/stuff will result in \fIpath_info()\fR returning
\&\*(L"/additional/stuff\*(R".
.Sp
\&\s-1NOTE:\s0 The Microsoft Internet Information Server is broken with respect to
additional path information. If you use the perl \s-1DLL\s0 library, the \s-1IIS\s0 server
will attempt to execute the additional path information as a perl script. If
you use the ordinary file associations mapping, the path information will be
present in the environment, but incorrect. The best thing to do is to avoid
using additional path information in \s-1CGI\s0 scripts destined for use with \s-1IIS. A\s0
best attempt has been made to make \s-1CGI\s0.pm do the right thing.
.IP "\fB\f(BIpath_translated()\fB\fR" 4
.IX Item "path_translated()"
As per \fIpath_info()\fR but returns the additional path information translated into
a physical path, e.g. \*(L"/usr/local/etc/httpd/htdocs/additional/stuff\*(R".
.Sp
The Microsoft \s-1IIS\s0 is broken with respect to the translated path as well.
.IP "\fB\f(BIremote_host()\fB\fR" 4
.IX Item "remote_host()"
Returns either the remote host name or \s-1IP\s0 address if the former is unavailable.
.IP "\fB\f(BIremote_ident()\fB\fR" 4
.IX Item "remote_ident()"
Returns the name of the remote user (as returned by identd) or undef if not set
.IP "\fB\f(BIremote_addr()\fB\fR" 4
.IX Item "remote_addr()"
Returns the remote host \s-1IP\s0 address, or 127.0.0.1 if the address is unavailable.
.IP "\fB\f(BIrequest_uri()\fB\fR" 4
.IX Item "request_uri()"
Returns the interpreted pathname of the requested document or \s-1CGI \s0(relative to
the document root). Or undef if not set.
.IP "\fB\f(BIscript_name()\fB\fR" 4
.IX Item "script_name()"
Return the script name as a partial \s-1URL,\s0 for self-referring scripts.
.IP "\fB\f(BIreferer()\fB\fR" 4
.IX Item "referer()"
Return the \s-1URL\s0 of the page the browser was viewing prior to fetching your
script.
.IP "\fB\f(BIauth_type()\fB\fR" 4
.IX Item "auth_type()"
Return the authorization/verification method in use for this script, if any.
.IP "\fB\f(BIserver_name()\fB\fR" 4
.IX Item "server_name()"
Returns the name of the server, usually the machine's host name.
.IP "\fB\f(BIvirtual_host()\fB\fR" 4
.IX Item "virtual_host()"
When using virtual hosts, returns the name of the host that the browser
attempted to contact
.IP "\fB\f(BIserver_port()\fB\fR" 4
.IX Item "server_port()"
Return the port that the server is listening on.
.IP "\fB\f(BIserver_protocol()\fB\fR" 4
.IX Item "server_protocol()"
Returns the protocol and revision of the incoming request, or defaults to
\&\s-1HTTP/1.0\s0 if this is not set
.IP "\fB\f(BIvirtual_port()\fB\fR" 4
.IX Item "virtual_port()"
Like \fIserver_port()\fR except that it takes virtual hosts into account. Use this
when running with virtual hosts.
.IP "\fB\f(BIserver_software()\fB\fR" 4
.IX Item "server_software()"
Returns the server software and version number.
.IP "\fB\f(BIremote_user()\fB\fR" 4
.IX Item "remote_user()"
Return the authorization/verification name used for user verification, if this
script is protected.
.IP "\fB\f(BIuser_name()\fB\fR" 4
.IX Item "user_name()"
Attempt to obtain the remote user's name, using a variety of different
techniques. May not work in all browsers.
.IP "\fB\f(BIrequest_method()\fB\fR" 4
.IX Item "request_method()"
Returns the method used to access your script, usually one of '\s-1POST\s0', '\s-1GET\s0'
or '\s-1HEAD\s0'.  If running from the command line it will be undef.
.IP "\fB\f(BIcontent_type()\fB\fR" 4
.IX Item "content_type()"
Returns the content_type of data submitted in a \s-1POST,\s0 generally
multipart/form\-data or application/x\-www\-form\-urlencoded
.IP "\fB\f(BIhttp()\fB\fR" 4
.IX Item "http()"
Called with no arguments returns the list of \s-1HTTP\s0 environment variables,
including such things as \s-1HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE,\s0 and
\&\s-1HTTP_ACCEPT_CHARSET,\s0 corresponding to the like-named \s-1HTTP\s0 header fields in the
request. Called with the name of an \s-1HTTP\s0 header field, returns its value.
Capitalization and the use of hyphens versus underscores are not significant.
.Sp
For example, all three of these examples are equivalent:
.Sp
.Vb 1
\&    my $requested_language = $q\->http(\*(AqAccept\-language\*(Aq);
\&
\&    my $requested_language = $q\->http(\*(AqAccept_language\*(Aq);
\&
\&    my $requested_language = $q\->http(\*(AqHTTP_ACCEPT_LANGUAGE\*(Aq);
.Ve
.IP "\fB\f(BIhttps()\fB\fR" 4
.IX Item "https()"
The same as \fI\fIhttp()\fI\fR, but operates on the \s-1HTTPS\s0 environment variables present
when the \s-1SSL\s0 protocol is in effect. Can be used to determine whether \s-1SSL\s0 is
turned on.
.SH "USING NPH SCRIPTS"
.IX Header "USING NPH SCRIPTS"
\&\s-1NPH,\s0 or \*(L"no-parsed-header\*(R", scripts bypass the server completely by sending the
complete \s-1HTTP\s0 header directly to the browser. This has slight performance
benefits, but is of most use for taking advantage of \s-1HTTP\s0 extensions that are
not directly supported by your server, such as server push and \s-1PICS\s0 headers.
.PP
Servers use a variety of conventions for designating \s-1CGI\s0 scripts as \s-1NPH.\s0 Many
Unix servers look at the beginning of the script's name for the prefix \*(L"nph\-\*(R".
The Macintosh WebSTAR server and Microsoft's Internet Information Server, in
contrast, try to decide whether a program is an \s-1NPH\s0 script by examining the
first line of script output.
.PP
\&\s-1CGI\s0.pm supports \s-1NPH\s0 scripts with a special \s-1NPH\s0 mode. When in this mode, \s-1CGI\s0.pm
will output the necessary extra header information when the \fIheader()\fR and
\&\fIredirect()\fR methods are called.
.PP
The Microsoft Internet Information Server requires \s-1NPH\s0 mode. As of version 2.30,
\&\s-1CGI\s0.pm will automatically detect when the script is running under \s-1IIS\s0 and put
itself into this mode. You do not need to do this manually, although it won't
hurt anything if you do.
.IP "In the \fBuse\fR statement" 4
.IX Item "In the use statement"
Simply add the \*(L"\-nph\*(R" pragma to the list of symbols to be imported into
your script:
.Sp
.Vb 1
\&    use CGI qw(:standard \-nph)
.Ve
.IP "By calling the \fB\f(BInph()\fB\fR method:" 4
.IX Item "By calling the nph() method:"
Call \fB\f(BInph()\fB\fR with a non-zero parameter at any point after using \s-1CGI\s0.pm in your
program.
.Sp
.Vb 1
\&    CGI\->nph(1)
.Ve
.IP "By using \fB\-nph\fR parameters" 4
.IX Item "By using -nph parameters"
in the \fB\f(BIheader()\fB\fR and \fB\f(BIredirect()\fB\fR  statements:
.Sp
.Vb 1
\&    print header(\-nph=>1);
.Ve
.SH "SERVER PUSH"
.IX Header "SERVER PUSH"
\&\s-1CGI\s0.pm provides four simple functions for producing multipart documents of the
type needed to implement server push. These functions were graciously provided
by Ed Jordan <ed@fidalgo.net>. To import these into your namespace, you must
import the \*(L":push\*(R" set. You are also advised to put the script into \s-1NPH\s0 mode
and to set $| to 1 to avoid buffering problems.
.PP
Here is a simple script that demonstrates server push:
.PP
.Vb 1
\&    #!/usr/bin/env perl
\&
\&    use strict;
\&    use warnings;
\&
\&    use CGI qw/:push \-nph/;
\&
\&    $| = 1;
\&    print multipart_init( \-boundary=>\*(Aq\-\-\-\-here we go!\*(Aq );
\&    for (0 .. 4) {
\&        print multipart_start( \-type=>\*(Aqtext/plain\*(Aq ),
\&            "The current time is ",scalar( localtime ),"\en";
\&        if ($_ < 4) {
\&            print multipart_end();
\&        } else {
\&            print multipart_final();
\&        }
\&        sleep 1;
\&    }
.Ve
.PP
This script initializes server push by calling \fB\f(BImultipart_init()\fB\fR. It then
enters a loop in which it begins a new multipart section by calling
\&\fB\f(BImultipart_start()\fB\fR, prints the current local time, and ends a multipart
section with \fB\f(BImultipart_end()\fB\fR. It then sleeps a second, and begins again.
On the final iteration, it ends the multipart section with
\&\fB\f(BImultipart_final()\fB\fR rather than with \fB\f(BImultipart_end()\fB\fR.
.IP "\fImultipart_init()\fR" 4
.IX Item "multipart_init()"
.Vb 1
\&    multipart_init( \-boundary => $boundary, \-charset => $charset );
.Ve
.Sp
Initialize the multipart system. The \-boundary argument specifies what \s-1MIME\s0
boundary string to use to separate parts of the document. If not provided,
\&\s-1CGI\s0.pm chooses a reasonable boundary for you.
.Sp
The \-charset provides the character set, if not provided this will default to
\&\s-1ISO\-8859\-1\s0
.IP "\fImultipart_start()\fR" 4
.IX Item "multipart_start()"
.Vb 1
\&    multipart_start( \-type => $type, \-charset => $charset );
.Ve
.Sp
Start a new part of the multipart document using the specified \s-1MIME\s0 type and
charset. If not specified, text/html \s-1ISO\-8859\-1\s0 is assumed.
.IP "\fImultipart_end()\fR" 4
.IX Item "multipart_end()"
.Vb 1
\&    multipart_end()
.Ve
.Sp
End a part. You must remember to call \fImultipart_end()\fR once for each
\&\fImultipart_start()\fR, except at the end of the last part of the multipart document
when \fImultipart_final()\fR should be called instead of \fImultipart_end()\fR.
.IP "\fImultipart_final()\fR" 4
.IX Item "multipart_final()"
.Vb 1
\&    multipart_final()
.Ve
.Sp
End all parts. You should call \fImultipart_final()\fR rather than \fImultipart_end()\fR
at the end of the last part of the multipart document.
.PP
Users interested in server push applications should also have a look at the
CGI::Push module.
.SH "AVOIDING DENIAL OF SERVICE ATTACKS"
.IX Header "AVOIDING DENIAL OF SERVICE ATTACKS"
A potential problem with \s-1CGI\s0.pm is that, by default, it attempts to process
form POSTings no matter how large they are. A wily hacker could attack your
site by sending a \s-1CGI\s0 script a huge \s-1POST\s0 of many gigabytes. \s-1CGI\s0.pm will attempt
to read the entire \s-1POST\s0 into a variable, growing hugely in size until it runs
out of memory. While the script attempts to allocate the memory the system may
slow down dramatically. This is a form of denial of service attack.
.PP
Another possible attack is for the remote user to force \s-1CGI\s0.pm to accept a huge
file upload. \s-1CGI\s0.pm will accept the upload and store it in a temporary directory
even if your script doesn't expect to receive an uploaded file. \s-1CGI\s0.pm will
delete the file automatically when it terminates, but in the meantime the remote
user may have filled up the server's disk space, causing problems for other
programs.
.PP
The best way to avoid denial of service attacks is to limit the amount of
memory, \s-1CPU\s0 time and disk space that \s-1CGI\s0 scripts can use. Some Web servers come
with built-in facilities to accomplish this. In other cases, you can use the
shell \fIlimit\fR or \fIulimit\fR commands to put ceilings on \s-1CGI\s0 resource usage.
.PP
\&\s-1CGI\s0.pm also has some simple built-in protections against denial of service
attacks, but you must activate them before you can use them. These take the
form of two global variables in the \s-1CGI\s0 name space:
.ie n .IP "\fB\fB$CGI::POST_MAX\fB\fR" 4
.el .IP "\fB\f(CB$CGI::POST_MAX\fB\fR" 4
.IX Item "$CGI::POST_MAX"
If set to a non-negative integer, this variable puts a ceiling on the size of
POSTings, in bytes. If \s-1CGI\s0.pm detects a \s-1POST\s0 that is greater than the ceiling,
it will immediately exit with an error message. This value will affect both
ordinary POSTs and multipart POSTs, meaning that it limits the maximum size of
file uploads as well. You should set this to a reasonably high
value, such as 10 megabytes.
.ie n .IP "\fB\fB$CGI::DISABLE_UPLOADS\fB\fR" 4
.el .IP "\fB\f(CB$CGI::DISABLE_UPLOADS\fB\fR" 4
.IX Item "$CGI::DISABLE_UPLOADS"
If set to a non-zero value, this will disable file uploads completely. Other
fill-out form values will work as usual.
.PP
To use these variables, set the variable at the top of the script, right after
the \*(L"use\*(R" statement:
.PP
.Vb 1
\&    #!/usr/bin/env perl
\&
\&    use strict;
\&    use warnings;
\&
\&    use CGI;
\&
\&    $CGI::POST_MAX = 1024 * 1024 * 10;  # max 10MB posts
\&    $CGI::DISABLE_UPLOADS = 1;          # no uploads
.Ve
.PP
An attempt to send a \s-1POST\s0 larger than \f(CW$POST_MAX\fR bytes will cause \fI\fIparam()\fI\fR to
return an empty \s-1CGI\s0 parameter list. You can test for this event by checking
\&\fI\fIcgi_error()\fI\fR, either after you create the \s-1CGI\s0 object or, if you are using the
function-oriented interface, call <\fIparam()\fR> for the first time. If the \s-1POST\s0 was
intercepted, then \fIcgi_error()\fR will return the message \*(L"413 \s-1POST\s0 too large\*(R".
.PP
This error message is actually defined by the \s-1HTTP\s0 protocol, and is designed to
be returned to the browser as the \s-1CGI\s0 script's status code. For example:
.PP
.Vb 5
\&    my $uploaded_file = $q\->param(\*(Aqupload\*(Aq);
\&    if ( !$uploaded_file && $q\->cgi_error() ) {
\&        print $q\->header( \-status => $q\->cgi_error() );
\&        exit 0;
\&   }
.Ve
.PP
However it isn't clear that any browser currently knows what to do with this
status code. It might be better just to create a page that warns the user of
the problem.
.SH "COMPATIBILITY WITH CGI\-LIB.PL"
.IX Header "COMPATIBILITY WITH CGI-LIB.PL"
To make it easier to port existing programs that use cgi\-lib.pl the
compatibility routine \*(L"ReadParse\*(R" is provided. Porting is simple:
.PP
\&\s-1OLD VERSION\s0
.PP
.Vb 3
\&    require "cgi\-lib.pl";
\&    &ReadParse;
\&    print "The value of the antique is $in{antique}.\en";
.Ve
.PP
\&\s-1NEW VERSION\s0
.PP
.Vb 3
\&    use CGI;
\&    CGI::ReadParse();
\&    print "The value of the antique is $in{antique}.\en";
.Ve
.PP
\&\s-1CGI\s0.pm's \fIReadParse()\fR routine creates a tied variable named \f(CW%in\fR, which can be
accessed to obtain the query variables. Like ReadParse, you can also provide
your own variable. Infrequently used features of ReadParse, such as the creation
of \f(CW@in\fR and \f(CW$in\fR variables, are not supported.
.PP
Once you use ReadParse, you can retrieve the query object itself this way:
.PP
.Vb 1
\&    my $q = $in{CGI};
.Ve
.PP
This allows you to start using the more interesting features of \s-1CGI\s0.pm without
rewriting your old scripts from scratch.
.PP
An even simpler way to mix cgi-lib calls with \s-1CGI\s0.pm calls is to import both the
\&\f(CW\*(C`:cgi\-lib\*(C'\fR and \f(CW\*(C`:standard\*(C'\fR method:
.PP
.Vb 4
\&    use CGI qw(:cgi\-lib :standard);
\&    &ReadParse;
\&    print "The price of your purchase is $in{price}.\en";
\&    print textfield(\-name=>\*(Aqprice\*(Aq, \-default=>\*(Aq$1.99\*(Aq);
.Ve
.SS "Cgi-lib functions that are available in \s-1CGI\s0.pm"
.IX Subsection "Cgi-lib functions that are available in CGI.pm"
In compatibility mode, the following cgi\-lib.pl functions are
available for your use:
.PP
.Vb 5
\&    ReadParse()
\&    PrintHeader()
\&    SplitParam()
\&    MethGet()
\&    MethPost()
.Ve
.SH "LICENSE"
.IX Header "LICENSE"
The \s-1CGI\s0.pm distribution is copyright 1995\-2007, Lincoln D. Stein. It is
distributed under the Artistic License 2.0. It is currently maintained
by Lee Johnson (\s-1LEEJO\s0) with help from many contributors.
.SH "CREDITS"
.IX Header "CREDITS"
Thanks very much to:
.IP "Mark Stosberg (mark@stosberg.com)" 4
.IX Item "Mark Stosberg (mark@stosberg.com)"
.PD 0
.IP "Matt Heffron (heffron@falstaff.css.beckman.com)" 4
.IX Item "Matt Heffron (heffron@falstaff.css.beckman.com)"
.IP "James Taylor (james.taylor@srs.gov)" 4
.IX Item "James Taylor (james.taylor@srs.gov)"
.IP "Scott Anguish (sanguish@digifix.com)" 4
.IX Item "Scott Anguish (sanguish@digifix.com)"
.IP "Mike Jewell (mlj3u@virginia.edu)" 4
.IX Item "Mike Jewell (mlj3u@virginia.edu)"
.IP "Timothy Shimmin (tes@kbs.citri.edu.au)" 4
.IX Item "Timothy Shimmin (tes@kbs.citri.edu.au)"
.IP "Joergen Haegg (jh@axis.se)" 4
.IX Item "Joergen Haegg (jh@axis.se)"
.IP "Laurent Delfosse (delfosse@delfosse.com)" 4
.IX Item "Laurent Delfosse (delfosse@delfosse.com)"
.IP "Richard Resnick (applepi1@aol.com)" 4
.IX Item "Richard Resnick (applepi1@aol.com)"
.IP "Craig Bishop (csb@barwonwater.vic.gov.au)" 4
.IX Item "Craig Bishop (csb@barwonwater.vic.gov.au)"
.IP "Tony Curtis (tc@vcpc.univie.ac.at)" 4
.IX Item "Tony Curtis (tc@vcpc.univie.ac.at)"
.IP "Tim Bunce (Tim.Bunce@ig.co.uk)" 4
.IX Item "Tim Bunce (Tim.Bunce@ig.co.uk)"
.IP "Tom Christiansen (tchrist@convex.com)" 4
.IX Item "Tom Christiansen (tchrist@convex.com)"
.IP "Andreas Koenig (k@franz.ww.TU\-Berlin.DE)" 4
.IX Item "Andreas Koenig (k@franz.ww.TU-Berlin.DE)"
.IP "Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)" 4
.IX Item "Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)"
.IP "Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)" 4
.IX Item "Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)"
.IP "Stephen Dahmen (joyfire@inxpress.net)" 4
.IX Item "Stephen Dahmen (joyfire@inxpress.net)"
.IP "Ed Jordan (ed@fidalgo.net)" 4
.IX Item "Ed Jordan (ed@fidalgo.net)"
.IP "David Alan Pisoni (david@cnation.com)" 4
.IX Item "David Alan Pisoni (david@cnation.com)"
.IP "Doug MacEachern (dougm@opengroup.org)" 4
.IX Item "Doug MacEachern (dougm@opengroup.org)"
.IP "Robin Houston (robin@oneworld.org)" 4
.IX Item "Robin Houston (robin@oneworld.org)"
.IP "...and many many more..." 4
.IX Item "...and many many more..."
.PD
for suggestions and bug fixes.
.SH "BUGS"
.IX Header "BUGS"
Address bug reports and comments to: <https://github.com/leejo/CGI.pm/issues>
.PP
See the <https://github.com/leejo/CGI.pm/blob/master/CONTRIBUTING.md> file for information
on raising issues and contributing
.PP
The original bug tracker can be found at:
<https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm>
.SH "SEE ALSO"
.IX Header "SEE ALSO"
CGI::Carp \- provides Carp implementation tailored to the \s-1CGI\s0 environment.
.PP
CGI::Fast \- supports running \s-1CGI\s0 applications under FastCGI