{
    "mode": "perldoc",
    "parameter": "CGI",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/CGI/json",
    "generated": "2026-06-09T15:09:48Z",
    "synopsis": "use strict;\nuse warnings;\nuse CGI;\n# create a CGI object (query) for use\nmy $q = CGI->new;\n# Process an HTTP request\nmy @values  = $q->multiparam('formfield');\nmy $value   = $q->param('paramname');\nmy $fh      = $q->upload('filefield');\nmy $riddle  = $q->cookie('riddlename');\nmy %answers = $q->cookie('answers');\n# Prepare various HTTP responses\nprint $q->header();\nprint $q->header('application/json');\nmy $cookie1 = $q->cookie(\n-name  => 'riddlename',\n-value => \"The Sphynx's Question\"\n);\nmy $cookie2 = $q->cookie(\n-name  => 'answers',\n-value => \\%answers\n);\nprint $q->header(\n-type    => 'image/gif',\n-expires => '+3d',\n-cookie  => [ $cookie1,$cookie2 ]\n);\nprint $q->redirect('http://somewhere.else/in/movie/land');",
    "sections": {
        "NAME": {
            "content": "CGI - Handle Common Gateway Interface requests and responses\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use strict;\nuse warnings;\n\nuse CGI;\n\n# create a CGI object (query) for use\nmy $q = CGI->new;\n\n# Process an HTTP request\nmy @values  = $q->multiparam('formfield');\nmy $value   = $q->param('paramname');\n\nmy $fh      = $q->upload('filefield');\n\nmy $riddle  = $q->cookie('riddlename');\nmy %answers = $q->cookie('answers');\n\n# Prepare various HTTP responses\nprint $q->header();\nprint $q->header('application/json');\n\nmy $cookie1 = $q->cookie(\n-name  => 'riddlename',\n-value => \"The Sphynx's Question\"\n);\n\nmy $cookie2 = $q->cookie(\n-name  => 'answers',\n-value => \\%answers\n);\n\nprint $q->header(\n-type    => 'image/gif',\n-expires => '+3d',\n-cookie  => [ $cookie1,$cookie2 ]\n);\n\nprint $q->redirect('http://somewhere.else/in/movie/land');\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "CGI.pm is a stable, complete and mature solution for processing and preparing HTTP requests and\nresponses. Major features including processing form submissions, file uploads, reading and\nwriting cookies, query string generation and manipulation, and processing and preparing HTTP\nheaders.\n\nCGI.pm performs very well in a vanilla CGI.pm environment and also comes with built-in support\nfor modperl and modperl2 as well as FastCGI.\n\nIt has the benefit of having developed and refined over 20 years with input from dozens of\ncontributors and being deployed on thousands of websites. CGI.pm was included in the perl\ndistribution from perl v5.4 to v5.20, however is has now been removed from the perl core...\n\nCGI.pm HAS BEEN REMOVED FROM THE PERL CORE\n<http://perl5.git.perl.org/perl.git/commitdiff/e9fa5a80>\n\nIf you upgrade to a new version of perl or if you rely on a system or vendor perl and get an\nupdated version of perl through a system update, then you will have to install CGI.pm yourself\nwith cpan/cpanm/a vendor package/manually. To make this a little easier the CGI::Fast module has\nbeen split into its own distribution, meaning you do not need access to a compiler to install\nCGI.pm\n\nThe rationale for this decision is that CGI.pm is no longer considered good practice for\ndeveloping web applications, including quick prototyping and small web scripts. There are far\nbetter, cleaner, quicker, easier, safer, more scalable, more extensible, more modern\nalternatives available at this point in time. These will be documented with CGI::Alternatives.\n\nFor more discussion on the removal of CGI.pm from core please see:\n\n<http://www.nntp.perl.org/group/perl.perl5.porters/2013/05/msg202130.html>\n\nNote that the v4 releases of CGI.pm will retain back compatibility as much as possible, however\nyou may need to make some minor changes to your code if you are using deprecated methods or some\nof the more obscure features of the module. If you plan to upgrade to v4.00 and beyond you\nshould read the Changes file for more information and test your code against CGI.pm before\ndeploying it.\n\nHTML Generation functions should no longer be used\nAll HTML generation functions within CGI.pm are no longer being maintained. Any issues, bugs, or\npatches will be rejected unless they relate to fundamentally broken page rendering.\n\nThe rationale for this is that the HTML generation functions of CGI.pm are an obfuscation at\nbest and a maintenance nightmare at worst. You should be using a template engine for better\nseparation of concerns. See CGI::Alternatives for an example of using CGI.pm with the\nTemplate::Toolkit module.\n\nThese functions, and perldoc for them, are considered deprecated, they are no longer being\nmaintained and no fixes or features for them will be accepted. They will, however, continue to\nexist in CGI.pm without any deprecation warnings (\"soft\" deprecation) so you can continue to use\nthem if you really want to. All documentation for these functions has been moved to\nCGI::HTML::Functions.\n",
            "subsections": []
        },
        "Programming style": {
            "content": "There are two styles of programming with CGI.pm, an object-oriented (OO) style and a\nfunction-oriented style. You are recommended to use the OO style as CGI.pm will create an\ninternal default object when the functions are called procedurally and you will not have to\nworry about method names clashing with perl builtins.\n\nIn the object-oriented style you create one or more CGI objects and then use object methods to\ncreate the various elements of the page. Each CGI object starts out with the list of named\nparameters that were passed to your CGI script by the server. You can modify the objects, save\nthem to a file or database and recreate them. Because each object corresponds to the \"state\" of\nthe CGI script, and because each object's parameter list is independent of the others, this\nallows you to save the state of the script and restore it later.\n\nFor example, using the object oriented style:\n\n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nuse CGI;                             # load CGI routines\n\nmy $q = CGI->new;                    # create new CGI object\nprint $q->header;                    # create the HTTP header\n\nIn the function-oriented style, there is one default CGI object that you rarely deal with\ndirectly. Instead you just call functions to retrieve CGI parameters, manage cookies, and so on.\nThe following example is identical to above, in terms of output, but uses the function-oriented\ninterface. The main differences are that we now need to import a set of functions into our name\nspace (usually the \"standard\" functions), and we don't need to create the CGI object.\n\n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nuse CGI qw/:standard/;           # load standard CGI routines\nprint header();                  # create the HTTP header\n\nThe examples in this document mainly use the object-oriented style. See HOW TO IMPORT FUNCTIONS\nfor important information on function-oriented programming in CGI.pm\n",
            "subsections": [
                {
                    "name": "Calling CGI.pm routines",
                    "content": "Most CGI.pm routines accept several arguments, sometimes as many as 20 optional ones! To\nsimplify this interface, all routines use a named argument calling style that looks like this:\n\nprint $q->header(\n-type    => 'image/gif',\n-expires => '+3d',\n);\n\nEach argument name is preceded by a dash. Neither case nor order matters in the argument list:\n-type, -Type, and -TYPE are all acceptable. In fact, only the first argument needs to begin with\na dash. If a dash is present in the first argument CGI.pm assumes dashes for the subsequent\nones.\n\nSeveral routines are commonly called with just one argument. In the case of these routines you\ncan provide the single argument without an argument name. header() happens to be one of these\nroutines. In this case, the single argument is the document type.\n\nprint $q->header('text/html');\n\nOther such routines are documented below.\n\nSometimes named arguments expect a scalar, sometimes a reference to an array, and sometimes a\nreference to a hash. Often, you can pass any type of argument and the routine will do whatever\nis most appropriate. For example, the param() routine is used to set a CGI parameter to a single\nor a multi-valued value. The two cases are shown below:\n\n$q->param(\n-name  => 'veggie',\n-value => 'tomato',\n);\n\n$q->param(\n-name  => 'veggie',\n-value => [ qw/tomato tomahto potato potahto/ ],\n);\n\nMany routines will do something useful with a named argument that it doesn't recognize. For\nexample, you can produce non-standard HTTP header fields by providing them as named arguments:\n\nprint $q->header(\n-type            => 'text/html',\n-cost            => 'Three smackers',\n-annoyancelevel => 'high',\n-complaintsto   => 'bit bucket',\n);\n\nThis will produce the following nonstandard HTTP header:\n\nHTTP/1.0 200 OK\nCost: Three smackers\nAnnoyance-level: high\nComplaints-to: bit bucket\nContent-type: text/html\n\nNotice the way that underscores are translated automatically into hyphens.\n\nCreating a new query object (object-oriented style)\nmy $q = CGI->new;\n\nThis will parse the input (from POST, GET and DELETE methods) and store it into a perl5 object\ncalled $q. Note that because the input parsing happens at object instantiation you have to set\nany CGI package variables that control parsing before you call CGI->new.\n\nAny filehandles from file uploads will have their position reset to the beginning of the file.\n"
                },
                {
                    "name": "Creating a new query object from an input file",
                    "content": "my $q = CGI->new( $inputfilehandle );\n\nIf you provide a file handle to the new() method, it will read parameters from the file (or\nSTDIN, or whatever). The file can be in any of the forms describing below under debugging (i.e.\na series of newline delimited TAG=VALUE pairs will work). Conveniently, this type of file is\ncreated by the save() method (see below). Multiple records can be saved and restored.\n\nPerl purists will be pleased to know that this syntax accepts references to file handles, or\neven references to filehandle globs, which is the \"official\" way to pass a filehandle. You can\nalso initialize the CGI object with a FileHandle or IO::File object.\n\nIf you are using the function-oriented interface and want to initialize CGI state from a file\nhandle, the way to do this is with restoreparameters(). This will (re)initialize the default\nCGI object from the indicated file handle.\n\nopen( my $infh,'<',\"test.in\") || die \"Couldn't open test.in for read: $!\";\nrestoreparameters( $infh );\nclose( $infh );\n\nYou can also initialize the query object from a hash reference:\n\nmy $q = CGI->new( {\n'dinosaur' => 'barney',\n'song'     => 'I love you',\n'friends'  => [ qw/ Jessica George Nancy / ]\n} );\n\nor from a properly formatted, URL-escaped query string:\n\nmy $q = CGI->new('dinosaur=barney&color=purple');\n\nor from a previously existing CGI object (currently this clones the parameter list, but none of\nthe other object-specific fields, such as autoescaping):\n\nmy $oldquery = CGI->new;\nmy $newquery = CGI->new($oldquery);\n\nTo create an empty query, initialize it from an empty string or hash:\n\nmy $emptyquery = CGI->new(\"\");\n\n-or-\n\nmy $emptyquery = CGI->new({});\n"
                },
                {
                    "name": "Fetching a list of keywords from the query",
                    "content": "my @keywords = $q->keywords\n\nIf the script was invoked as the result of an ISINDEX search, the parsed keywords can be\nobtained as an array using the keywords() method.\n"
                },
                {
                    "name": "Fetching the names of all the parameters passed to your script",
                    "content": "my @names = $q->multiparam\n\nmy @names = $q->param\n\nIf the script was invoked with a parameter list (e.g. \"name1=value1&name2=value2&name3=value3\"),\nthe param() / multiparam() methods will return the parameter names as a list. If the script was\ninvoked as an ISINDEX script and contains a string without ampersands (e.g.\n\"value1+value2+value3\"), there will be a single parameter named \"keywords\" containing the\n\"+\"-delimited keywords.\n\nThe array of parameter names returned will be in the same order as they were submitted by the\nbrowser. Usually this order is the same as the order in which the parameters are defined in the\nform (however, this isn't part of the spec, and so isn't guaranteed).\n"
                },
                {
                    "name": "Fetching the value or values of a single named parameter",
                    "content": "my @values = $q->multiparam('foo');\n\n-or-\n\nmy $value = $q->param('foo');\n\n-or-\n\nmy @values = $q->param('foo'); # list context, discouraged and will raise\n# a warning (use ->multiparam instead)\n\nPass the param() / multiparam() method a single argument to fetch the value of the named\nparameter. When calling param() If the parameter is multivalued (e.g. from multiple selections\nin a scrolling list), you can ask to receive an array. Otherwise the method will return the\nfirst value.\n\nWarning - calling param() in list context can lead to vulnerabilities if you do not sanitise\nuser input as it is possible to inject other param keys and values into your code. This is why\nthe multiparam() method exists, to make it clear that a list is being returned, note that"
                },
                {
                    "name": "param",
                    "content": "The following code is an example of a vulnerability as the call to param will be evaluated in\nlist context and thus possibly inject extra keys and values into the hash:\n\nmy %userinfo = (\nid   => 1,\nname => $q->param('name'),\n);\n\nThe fix for the above is to force scalar context on the call to ->param by prefixing it with\n\"scalar\"\n\nname => scalar $q->param('name'),\n\nIf you call param() in list context with an argument a warning will be raised by CGI.pm, you can\ndisable this warning by setting $CGI::LISTCONTEXTWARN to 0 or by using the multiparam()\nmethod instead\n\nIf a value is not given in the query string, as in the queries \"name1=&name2=\", it will be\nreturned as an empty string.\n\nIf the parameter does not exist at all, then param() will return undef in scalar context, and\nthe empty list in a list context.\n\nSetting the value(s) of a named parameter\n$q->param('foo','an','array','of','values');\n\nThis sets the value for the named parameter 'foo' to an array of values. This is one way to\nchange the value of a field AFTER the script has been invoked once before.\n"
                },
                {
                    "name": "param",
                    "content": "$q->param(\n-name   => 'foo',\n-values => ['an','array','of','values'],\n);\n\n-or-\n\n$q->param(\n-name  => 'foo',\n-value => 'the value',\n);\n"
                },
                {
                    "name": "Appending additional values to a named parameter",
                    "content": "$q->append(\n-name   =>'foo',\n-values =>['yet','more','values'],\n);\n\nThis adds a value or list of values to the named parameter. The values are appended to the end\nof the parameter if it already exists. Otherwise the parameter is created. Note that this method\nonly recognizes the named argument calling syntax.\n"
                },
                {
                    "name": "Importing all parameters into a namespace",
                    "content": "$q->importnames('R');\n\nThis creates a series of variables in the 'R' namespace. For example, $R::foo, @R:foo. For\nkeyword lists, a variable @R::keywords will appear. If no namespace is given, this method will\nassume 'Q'. WARNING: don't import anything into 'main'; this is a major security risk!\n\nNOTE 1: Variable names are transformed as necessary into legal perl variable names. All\nnon-legal characters are transformed into underscores. If you need to keep the original names,\nyou should use the param() method instead to access CGI variables by name.\n\nIn fact, you should probably not use this method at all given the above caveats and security\nrisks.\n"
                },
                {
                    "name": "Deleting a parameter completely",
                    "content": "$q->delete('foo','bar','baz');\n\nThis completely clears a list of parameters. It sometimes useful for resetting parameters that\nyou don't want passed down between script invocations.\n\nIf you are using the function call interface, use \"Delete()\" instead to avoid conflicts with\nperl's built-in delete operator.\n"
                },
                {
                    "name": "Deleting all parameters",
                    "content": "$q->deleteall();\n\nThis clears the CGI object completely. It might be useful to ensure that all the defaults are\ntaken when you create a fill-out form.\n\nUse Deleteall() instead if you are using the function call interface.\n"
                },
                {
                    "name": "Handling non-urlencoded arguments",
                    "content": "If POSTed data is not of type application/x-www-form-urlencoded or multipart/form-data, then the\nPOSTed data will not be processed, but instead be returned as-is in a parameter named POSTDATA.\nTo retrieve it, use code like this:\n\nmy $data = $q->param('POSTDATA');\n\nLikewise if PUTed and PATCHed data can be retrieved with code like this:\n\nmy $data = $q->param('PUTDATA');\n\nmy $data = $q->param('PATCHDATA');\n\n(If you don't know what the preceding means, worry not. It only affects people trying to use CGI\nfor XML processing and other specialized tasks)\n\nPUTDATA/POSTDATA/PATCHDATA are also available via uploadhook, and as file uploads via\n\"-putdataupload\" option.\n"
                },
                {
                    "name": "Direct access to the parameter list",
                    "content": "$q->paramfetch('address')->[1] = '1313 Mockingbird Lane';\nunshift @{$q->paramfetch(-name=>'address')},'George Munster';\n\nIf you need access to the parameter list in a way that isn't covered by the methods given in the\nprevious sections, you can obtain a direct reference to it by calling the paramfetch() method\nwith the name of the parameter. This will return an array reference to the named parameter,\nwhich you then can manipulate in any way you like.\n\nYou can also use a named argument style using the -name argument.\n"
                },
                {
                    "name": "Fetching the parameter list as a hash",
                    "content": "my $params = $q->Vars;\nprint $params->{'address'};\nmy @foo = split(\"\\0\",$params->{'foo'});\nmy %params = $q->Vars;\n\nuse CGI ':cgi-lib';\nmy $params = Vars();\n\nMany people want to fetch the entire parameter list as a hash in which the keys are the names of\nthe CGI parameters, and the values are the parameters' values. The Vars() method does this.\nCalled in a scalar context, it returns the parameter list as a tied hash reference. Changing a\nkey changes the value of the parameter in the underlying CGI parameter list. Called in a list\ncontext, it returns the parameter list as an ordinary hash. This allows you to read the contents\nof the parameter list, but not to change it.\n\nWhen using this, the thing you must watch out for are multivalued CGI parameters. Because a hash\ncannot distinguish between scalar and list context, multivalued parameters will be returned as a\npacked string, separated by the \"\\0\" (null) character. You must split this packed string in\norder to get at the individual values. This is the convention introduced long ago by Steve\nBrenner in his cgi-lib.pl module for perl version 4, and may be replaced in future versions with\narray references.\n\nIf you wish to use Vars() as a function, import the *:cgi-lib* set of function calls (also see\nthe section on CGI-LIB compatibility).\n"
                },
                {
                    "name": "Saving the state of the script to a file",
                    "content": "$q->save(\\*FILEHANDLE)\n\nThis will write the current state of the form to the provided filehandle. You can read it back\nin by providing a filehandle to the new() method. Note that the filehandle can be a file, a\npipe, or whatever.\n\nThe format of the saved file is:\n\nNAME1=VALUE1\nNAME1=VALUE1'\nNAME2=VALUE2\nNAME3=VALUE3\n=\n\nBoth name and value are URL escaped. Multi-valued CGI parameters are represented as repeated\nnames. A session record is delimited by a single = symbol. You can write out multiple records\nand read them back in with several calls to new. You can do this across several sessions by\nopening the file in append mode, allowing you to create primitive guest books, or to keep a\nhistory of users' queries. Here's a short example of creating multiple session records:\n\nuse strict;\nuse warnings;\nuse CGI;\n\nopen (my $outfh,'>>','test.out') || die \"Can't open test.out: $!\";\nmy $records = 5;\nfor ( 0 .. $records ) {\nmy $q = CGI->new;\n$q->param( -name => 'counter',-value => $ );\n$q->save( $outfh );\n}\nclose( $outfh );\n\n# reopen for reading\nopen (my $infh,'<','test.out') || die \"Can't open test.out: $!\";\nwhile (!eof($infh)) {\nmy $q = CGI->new($infh);\nprint $q->param('counter'),\"\\n\";\n}\n\nThe file format used for save/restore is identical to that used by the Whitehead Genome Center's\ndata exchange format \"Boulderio\", and can be manipulated and even databased using Boulderio\nutilities. See Boulder for further details.\n\nIf you wish to use this method from the function-oriented (non-OO) interface, the exported name\nfor this method is saveparameters().\n"
                },
                {
                    "name": "Retrieving cgi errors",
                    "content": "Errors can occur while processing user input, particularly when processing uploaded files. When\nthese errors occur, CGI will stop processing and return an empty parameter list. You can test\nfor the existence and nature of errors using the *cgierror()* function. The error messages are\nformatted as HTTP status codes. You can either incorporate the error text into a page, or use it\nas the value of the HTTP status:\n\nif ( my $error = $q->cgierror ) {\nprint $q->header( -status => $error );\nprint \"Error: $error\";\nexit 0;\n}\n\nWhen using the function-oriented interface (see the next section), errors may only occur the\nfirst time you call *param()*. Be ready for this!\n"
                },
                {
                    "name": "Using the function-oriented interface",
                    "content": "To use the function-oriented interface, you must specify which CGI.pm routines or sets of\nroutines to import into your script's namespace. There is a small overhead associated with this\nimportation, but it isn't much.\n\nuse strict;\nuse warnings;\n\nuse CGI qw/ list of methods /;\n\nThe listed methods will be imported into the current package; you can call them directly without\ncreating a CGI object first. This example shows how to import the param() and header() methods,\nand then use them directly:\n\nuse strict;\nuse warnings;\n\nuse CGI qw/ param header /;\nprint header('text/plain');\nmy $zipcode = param('zipcode');\n\nMore frequently, you'll import common sets of functions by referring to the groups by name. All\nfunction sets are preceded with a \":\" character as in \":cgi\" (for CGI protocol handling\nmethods).\n\nHere is a list of the function sets you can import:\n\n:cgi\nImport all CGI-handling methods, such as param(), pathinfo() and the like.\n\n:all\nImport all the available methods. For the full list, see the CGI.pm code, where the variable\n%EXPORTTAGS is defined. (N.B. the :cgi-lib imports will not be included in the :all import,\nyou will have to import :cgi-lib to get those)\n\nNote that in the interests of execution speed CGI.pm does not use the standard Exporter syntax\nfor specifying load symbols. This may change in the future.\n"
                },
                {
                    "name": "Pragmas",
                    "content": "In addition to the function sets, there are a number of pragmas that you can import. Pragmas,\nwhich are always preceded by a hyphen, change the way that CGI.pm functions in various ways.\nPragmas, function sets, and individual functions can all be imported in the same use() line. For\nexample, the following use statement imports the cgi set of functions and enables debugging mode\n(pragma -debug):\n\nuse strict;\nuse warninigs;\nuse CGI qw/ :cgi -debug /;\n\nThe current list of pragmas is as follows:\n"
                },
                {
                    "name": "-no_undef_params",
                    "content": "This keeps CGI.pm from including undef params in the parameter list.\n"
                },
                {
                    "name": "-utf8",
                    "content": "This makes CGI.pm treat all parameters as text strings rather than binary strings (see\nperlunitut for the distinction), assuming UTF-8 for the encoding.\n\nCGI.pm does the decoding from the UTF-8 encoded input data, restricting this decoding to\ninput text as distinct from binary upload data which are left untouched. Therefore, a\n':utf8' layer must not be used on STDIN.\n\nIf you do not use this option you can manually select which fields are expected to return\nutf-8 strings and convert them using code like this:\n\nuse strict;\nuse warnings;\n\nuse CGI;\nuse Encode qw/ decode /;\n\nmy $cgi   = CGI->new;\nmy $param = $cgi->param('foo');\n$param    = decode( 'UTF-8',$param );\n\n-putdataupload / -postdataupload / -patchdataupload\nMakes \"$cgi->param('PUTDATA');\", \"$cgi->param('PATCHDATA');\", and \"$cgi->param('POSTDATA');\"\nact like file uploads named PUTDATA, PATCHDATA, and POSTDATA. See \"Handling non-urlencoded\narguments\" and \"Processing a file upload field\" PUTDATA/POSTDATA/PATCHDATA are also\navailable via uploadhook.\n"
                },
                {
                    "name": "-nph",
                    "content": "This makes CGI.pm produce a header appropriate for an NPH (no parsed header) script. You may\nneed to do other things as well to tell the server that the script is NPH. See the\ndiscussion of NPH scripts below.\n"
                },
                {
                    "name": "-newstyle_urls",
                    "content": "Separate the name=value pairs in CGI parameter query strings with semicolons rather than\nampersands. For example:\n\n?name=fred;age=24;favoritecolor=3\n\nSemicolon-delimited query strings are always accepted, and will be emitted by selfurl() and\nquerystring(). newstyleurls became the default in version 2.64.\n"
                },
                {
                    "name": "-oldstyle_urls",
                    "content": "Separate the name=value pairs in CGI parameter query strings with ampersands rather than\nsemicolons. This is no longer the default.\n"
                },
                {
                    "name": "-no_debug",
                    "content": "This turns off the command-line processing features. If you want to run a CGI.pm script from\nthe command line, and you don't want it to read CGI parameters from the command line or\nSTDIN, then use this pragma:\n\nuse CGI qw/ -nodebug :standard /;\n"
                },
                {
                    "name": "-debug",
                    "content": "This turns on full debugging. In addition to reading CGI arguments from the command-line\nprocessing, CGI.pm will pause and try to read arguments from STDIN, producing the message\n\"(offline mode: enter name=value pairs on standard input)\" features.\n\nSee the section on debugging for more details.\n"
                }
            ]
        },
        "GENERATING DYNAMIC DOCUMENTS": {
            "content": "Most of CGI.pm's functions deal with creating documents on the fly. Generally you will produce\nthe HTTP header first, followed by the document itself. CGI.pm provides functions for generating\nHTTP headers of various types.\n\nEach of these functions produces a fragment of HTTP which you can print out directly so that it\nis processed by the browser, appended to a string, or saved to a file for later use.\n",
            "subsections": [
                {
                    "name": "Creating a standard http header",
                    "content": "Normally the first thing you will do in any CGI script is print out an HTTP header. This tells\nthe browser what type of document to expect, and gives other optional information, such as the\nlanguage, expiration date, and whether to cache the document. The header can also be manipulated\nfor special purposes, such as server push and pay per view pages.\n\nuse strict;\nuse warnings;\n\nuse CGI;\n\nmy $cgi = CGI->new;\n\nprint $cgi->header;\n\n-or-\n\nprint $cgi->header('image/gif');\n\n-or-\n\nprint $cgi->header('text/html','204 No response');\n\n-or-\n\nprint $cgi->header(\n-type       => 'image/gif',\n-nph        => 1,\n-status     => '402 Payment required',\n-expires    => '+3d',\n-cookie     => $cookie,\n-charset    => 'utf-8',\n-attachment => 'foo.gif',\n-Cost       => '$2.00'\n);\n"
                },
                {
                    "name": "header",
                    "content": "otherwise it defaults to text/html. An optional second parameter specifies the status code and a\nhuman-readable message. For example, you can specify 204, \"No response\" to create a script that\ntells the browser to do nothing at all. Note that RFC 2616 expects the human-readable phase to\nbe there as well as the numeric status code.\n\nThe last example shows the named argument style for passing arguments to the CGI methods using\nnamed parameters. Recognized parameters are -type, -status, -expires, and -cookie. Any other\nnamed parameters will be stripped of their initial hyphens and turned into header fields,\nallowing you to specify any HTTP header you desire. Internal underscores will be turned into\nhyphens:\n\nprint $cgi->header( -Contentlength => 3002 );\n\nMost browsers will not cache the output from CGI scripts. Every time the browser reloads the\npage, the script is invoked anew. You can change this behavior with the -expires parameter. When\nyou specify an absolute or relative expiration interval with this parameter, some browsers and\nproxy servers will cache the script's output until the indicated expiration date. The following\nforms are all valid for the -expires field:\n\n+30s                                  30 seconds from now\n+10m                                  ten minutes from now\n+1h                                   one hour from now\n-1d                                   yesterday (i.e. \"ASAP!\")\nnow                                   immediately\n+3M                                   in three months\n+10y                                  in ten years time\nThursday, 25-Apr-2018 00:40:33 GMT    at the indicated time & date\n\nThe -cookie parameter generates a header that tells the browser to provide a \"magic cookie\"\nduring all subsequent transactions with your script. Some cookies have a special format that\nincludes interesting attributes such as expiration time. Use the cookie() method to create and\nretrieve session cookies.\n\nThe -nph parameter, if set to a true value, will issue the correct headers to work with a NPH\n(no-parse-header) script. This is important to use with certain servers that expect all their\nscripts to be NPH.\n\nThe -charset parameter can be used to control the character set sent to the browser. If not\nprovided, defaults to ISO-8859-1. As a side effect, this sets the charset() method as well. Note\nthat the default being ISO-8859-1 may not make sense for all content types, e.g.:\n\nContent-Type: image/gif; charset=ISO-8859-1\n\nIn the above case you need to pass -charset => '' to prevent the default being used.\n\nThe -attachment parameter can be used to turn the page into an attachment. Instead of displaying\nthe page, some browsers will prompt the user to save it to disk. The value of the argument is\nthe suggested name for the saved file. In order for this to work, you may have to set the -type\nto \"application/octet-stream\".\n\nThe -p3p parameter will add a P3P tag to the outgoing header. The parameter can be an arrayref\nor a space-delimited string of P3P tags. For example:\n\nprint $cgi->header( -p3p => [ qw/ CAO DSP LAW CURa / ] );\nprint $cgi->header( -p3p => 'CAO DSP LAW CURa' );\n\nIn either case, the outgoing header will be formatted as:\n\nP3P: policyref=\"/w3c/p3p.xml\" cp=\"CAO DSP LAW CURa\"\n\nCGI.pm will accept valid multi-line headers when each line is separated with a CRLF value\n(\"\\r\\n\" on most platforms) followed by at least one space. For example:\n\nprint $cgi->header( -ingredients => \"ham\\r\\n\\seggs\\r\\n\\sbacon\" );\n\nInvalid multi-line header input will trigger in an exception. When multi-line headers are\nreceived, CGI.pm will always output them back as a single line, according to the folding rules\nof RFC 2616: the newlines will be removed, while the white space remains.\n"
                },
                {
                    "name": "Generating a redirection header",
                    "content": "print $q->redirect( 'http://somewhere.else/in/movie/land' );\n\nSometimes you don't want to produce a document yourself, but simply redirect the browser\nelsewhere, perhaps choosing a URL based on the time of day or the identity of the user.\n\nThe redirect() method redirects the browser to a different URL. If you use redirection like\nthis, you should not print out a header as well.\n\nYou are advised to use full URLs (absolute with respect to current URL or even including the\nhttp: or ftp: part) in redirection requests as relative URLs are resolved by the user agent of\nthe client so may not do what you want or expect them to do.\n\nYou can also use named arguments:\n\nprint $q->redirect(\n-uri    => 'http://somewhere.else/in/movie/land',\n-nph    => 1,\n-status => '301 Moved Permanently'\n);\n\nAll names arguments recognized by header() are also recognized by redirect(). However, most HTTP\nheaders, including those generated by -cookie and -target, are ignored by the browser.\n\nThe -nph parameter, if set to a true value, will issue the correct headers to work with a NPH\n(no-parse-header) script. This is important to use with certain servers, such as Microsoft IIS,\nwhich expect all their scripts to be NPH.\n\nThe -status parameter will set the status of the redirect. HTTP defines several different\npossible redirection status codes, and the default if not specified is 302, which means \"moved\ntemporarily.\" You may change the status to another status code if you wish.\n\nNote that the human-readable phrase is also expected to be present to conform with RFC 2616,\nsection 6.1.\n"
                },
                {
                    "name": "Creating a self-referencing url that preserves state information",
                    "content": "my $myself = $q->selfurl;\nprint qq(<a href=\"$myself\">I'm talking to myself.</a>);\n"
                },
                {
                    "name": "self_url",
                    "content": "information intact. This is most useful when you want to jump around within the document using\ninternal anchors but you don't want to disrupt the current contents of the form(s). Something\nlike this will do the trick:\n\nmy $myself = $q->selfurl;\nprint \"<a href=\\\"$myself#table1\\\">See table 1</a>\";\nprint \"<a href=\\\"$myself#table2\\\">See table 2</a>\";\nprint \"<a href=\\\"$myself#yourself\\\">See for yourself</a>\";\n\nIf you want more control over what's returned, using the url() method instead.\n\nYou can also retrieve a query string representation of the current object state with"
                },
                {
                    "name": "query_string",
                    "content": "my $thestring = $q->querystring();\n\nThe behavior of calling querystring is currently undefined when the HTTP method is something\nother than GET.\n\nIf you want to retrieved the query string as set in the webserver, namely the environment\nvariable, you can call envquerystring()\n"
                },
                {
                    "name": "Obtaining the script's url",
                    "content": "my $fullurl      = url();\nmy $fullurl      = url( -full =>1 );  # alternative syntax\nmy $relativeurl  = url( -relative => 1 );\nmy $absoluteurl  = url( -absolute =>1 );\nmy $urlwithpath = url( -pathinfo => 1 );\nmy $urlpathqry  = url( -pathinfo => 1, -query =>1 );\nmy $netloc        = url( -base => 1 );\n"
                },
                {
                    "name": "url",
                    "content": "the full form of the URL, including host name and port number\n\nhttp://your.host.com/path/to/script.cgi\n\nYou can modify this format with the following named arguments:\n"
                },
                {
                    "name": "-absolute",
                    "content": "If true, produce an absolute URL, e.g.\n\n/path/to/script.cgi\n"
                },
                {
                    "name": "-relative",
                    "content": "Produce a relative URL. This is useful if you want to re-invoke your script with different\nparameters. For example:\n\nscript.cgi\n"
                },
                {
                    "name": "-full",
                    "content": "Produce the full URL, exactly as if called without any arguments. This overrides the\n-relative and -absolute arguments.\n\n-path (-pathinfo)\nAppend the additional path information to the URL. This can be combined with -full,\n-absolute or -relative. -pathinfo is provided as a synonym.\n\n-query (-querystring)\nAppend the query string to the URL. This can be combined with -full, -absolute or -relative.\n-querystring is provided as a synonym.\n"
                },
                {
                    "name": "-base",
                    "content": "Generate just the protocol and net location, as in http://www.foo.com:8000\n"
                },
                {
                    "name": "-rewrite",
                    "content": "If Apache's modrewrite is turned on, then the script name and path info probably won't\nmatch the request that the user sent. Set -rewrite => 1 (default) to return URLs that match\nwhat the user sent (the original request URI). Set -rewrite => 0 to return URLs that match\nthe URL after the modrewrite rules have run.\n"
                },
                {
                    "name": "Mixing post and url parameters",
                    "content": "my $color = urlparam('color');\n\nIt is possible for a script to receive CGI parameters in the URL as well as in the fill-out form\nby creating a form that POSTs to a URL containing a query string (a \"?\" mark followed by\narguments). The param() method will always return the contents of the POSTed fill-out form,\nignoring the URL's query string. To retrieve URL parameters, call the urlparam() method. Use it\nin the same way as param(). The main difference is that it allows you to read the parameters,\nbut not set them.\n\nUnder no circumstances will the contents of the URL query string interfere with similarly-named\nCGI parameters in POSTed forms. If you try to mix a URL query string with a form submitted with\nthe GET method, the results will not be what you expect.\n\nIf running from the command line, \"urlparam\" will not pick up any parameters given on the\ncommand line.\n"
                },
                {
                    "name": "Processing a file upload field",
                    "content": "Basics\nWhen the form is processed, you can retrieve an IO::File compatible handle for a file upload\nfield like this:\n\nuse autodie;\n\n# undef may be returned if it's not a valid file handle\nif ( my $iohandle = $q->upload('fieldname') ) {\nopen ( my $outfile,'>>','/usr/local/web/users/feedback' );\nwhile ( my $bytesread = $iohandle->read($buffer,1024) ) {\nprint $outfile $buffer;\n}\n}\n\nIn a list context, upload() will return an array of filehandles. This makes it possible to\nprocess forms that use the same name for multiple upload fields.\n\nIf you want the entered file name for the file, you can just call param():\n\nmy $filename = $q->param('fieldname');\n\nDifferent browsers will return slightly different things for the name. Some browsers return the\nfilename only. Others return the full path to the file, using the path conventions of the user's\nmachine. Regardless, the name returned is always the name of the file on the *user's* machine,\nand is unrelated to the name of the temporary file that CGI.pm creates during upload spooling\n(see below).\n\nWhen a file is uploaded the browser usually sends along some information along with it in the\nformat of headers. The information usually includes the MIME content type. To retrieve this\ninformation, call uploadInfo(). It returns a reference to a hash containing all the document\nheaders.\n\nmy $filehandle = $q->upload( 'uploadedfile' );\nmy $type       = $q->uploadInfo( $filehandle )->{'Content-Type'};\nif ( $type ne 'text/html' ) {\ndie \"HTML FILES ONLY!\";\n}\n\nNote that you must use ->upload or ->param to get the file-handle to pass into uploadInfo as\ninternally this is represented as a File::Temp object (which is what will be returned by\n->upload or ->param). When using ->Vars you will get the literal filename rather than the\nFile::Temp object, which will not return anything when passed to uploadInfo. So don't use\n->Vars.\n\nIf you are using a machine that recognizes \"text\" and \"binary\" data modes, be sure to understand\nwhen and how to use them (see the Camel book). Otherwise you may find that binary files are\ncorrupted during file uploads.\n\nAccessing the temp files directly\nWhen processing an uploaded file, CGI.pm creates a temporary file on your hard disk and passes\nyou a file handle to that file. After you are finished with the file handle, CGI.pm unlinks\n(deletes) the temporary file. If you need to you can access the temporary file directly. You can\naccess the temp file for a file upload by passing the file name to the tmpFileName() method:\n\nmy $filehandle  = $q->upload( 'uploadedfile' );\nmy $tmpfilename = $q->tmpFileName( $filehandle );\n\nAs with ->uploadInfo, using the reference returned by ->upload or ->param is preferred, although\nunlike ->uploadInfo, plain filenames also work if possible for backwards compatibility.\n\nThe temporary file will be deleted automatically when your program exits unless you manually\nrename it or set $CGI::UNLINKTMPFILES to 0. On some operating systems (such as Windows NT),\nyou will need to close the temporary file's filehandle before your program exits. Otherwise the\nattempt to delete the temporary file will fail.\n\nChanges in temporary file handling (v4.05+)\nCGI.pm had its temporary file handling significantly refactored, this logic is now all deferred\nto File::Temp (which is wrapped in a compatibility object, CGI::File::Temp - DO NOT USE THIS\nPACKAGE DIRECTLY). As a consequence the PRIVATETEMPFILES variable has been removed along with\ndeprecation of the privatetempfiles routine and complete removal of the CGITempFile package.\nThe $CGITempFile::TMPDIRECTORY is no longer used to set the temp directory, refer to the perldoc\nfor File::Temp if you want to override the default settings in that package (the TMPDIR env\nvariable is still available on some platforms). For Windows platforms the temporary directory\norder remains as before: TEMP > TMP > WINDIR ( > TMPDIR ) so if you have any of these in use in\nexisting scripts they should still work.\n\nThe Fh package still exists but does nothing, the CGI::File::Temp class is a subclass of both\nFile::Temp and the empty Fh package, so if you have any code that checks that the filehandle isa\nFh this should still work.\n\nWhen you get the internal file handle you will receive a File::Temp object, this should be\ntransparent as File::Temp isa IO::Handle and isa IO::Seekable meaning it behaves as previously.\nIf you are doing anything out of the ordinary with regards to temp files you should test your\ncode before deploying this update and refer to the File::Temp documentation for more\ninformation.\n\nHandling interrupted file uploads\nThere are occasionally problems involving parsing the uploaded file. This usually happens when\nthe user presses \"Stop\" before the upload is finished. In this case, CGI.pm will return undef\nfor the name of the uploaded file and set *cgierror()* to the string \"400 Bad request\n(malformed multipart POST)\". This error message is designed so that you can incorporate it into\na status code to be sent to the browser. Example:\n\nmy $file = $q->upload( 'uploadedfile' );\nif ( !$file && $q->cgierror ) {\nprint $q->header( -status => $q->cgierror );\nexit 0;\n}\n\nProgress bars for file uploads and avoiding temp files\nCGI.pm gives you low-level access to file upload management through a file upload hook. You can\nuse this feature to completely turn off the temp file storage of file uploads, or potentially\nwrite your own file upload progress meter.\n\nThis is much like the UPLOADHOOK facility available in Apache::Request, with the exception that\nthe first argument to the callback is an Apache::Upload object, here it's the remote filename.\n\nmy $q = CGI->new( \\&hook [,$data [,$usetempfile]] );\n\nsub hook {\nmy ( $filename, $buffer, $bytesread, $data ) = @;\nprint \"Read $bytesread bytes of $filename\\n\";\n}\n\nThe $data field is optional; it lets you pass configuration information (e.g. a database handle)\nto your hook callback.\n\nThe $usetempfile field is a flag that lets you turn on and off CGI.pm's use of a temporary\ndisk-based file during file upload. If you set this to a FALSE value (default true) then\n$q->param('uploadedfile') will no longer work, and the only way to get at the uploaded data is\nvia the hook you provide.\n\nIf using the function-oriented interface, call the CGI::uploadhook() method before calling"
                },
                {
                    "name": "param",
                    "content": "CGI::uploadhook( \\&hook [,$data [,$usetempfile]] );\n\nThis method is not exported by default. You will have to import it explicitly if you wish to use\nit without the CGI:: prefix.\n\nTroubleshooting file uploads on Windows\nIf you are using CGI.pm on a Windows platform and find that binary files get slightly larger\nwhen uploaded but that text files remain the same, then you have forgotten to activate binary\nmode on the output filehandle. Be sure to call binmode() on any handle that you create to write\nthe uploaded file to disk.\n\nOlder ways to process file uploads\nThis section is here for completeness. if you are building a new application with CGI.pm, you\ncan skip it.\n\nThe original way to process file uploads with CGI.pm was to use param(). The value it returns\nhas a dual nature as both a file name and a lightweight filehandle. This dual nature is\nproblematic if you following the recommended practice of having \"use strict\" in your code. perl\nwill complain when you try to use a string as a filehandle. More seriously, it is possible for\nthe remote user to type garbage into the upload field, in which case what you get from param()\nis not a filehandle at all, but a string.\n\nTo solve this problem the upload() method was added, which always returns a lightweight\nfilehandle. This generally works well, but will have trouble interoperating with some other\nmodules because the file handle is not derived from IO::File. So that brings us to current\nrecommendation given above, which is to call the handle() method on the file handle returned by"
                },
                {
                    "name": "upload",
                    "content": "penalty of loading IO::File the first time you call it.\n"
                }
            ]
        },
        "HTTP COOKIES": {
            "content": "CGI.pm has several methods that support cookies.\n\nA cookie is a name=value pair much like the named parameters in a CGI query string. CGI scripts\ncreate one or more cookies and send them to the browser in the HTTP header. The browser\nmaintains a list of cookies that belong to a particular Web server, and returns them to the CGI\nscript during subsequent interactions.\n\nIn addition to the required name=value pair, each cookie has several optional attributes:\n\n1. an expiration time\nThis is a time/date string (in a special GMT format) that indicates when a cookie expires.\nThe cookie will be saved and returned to your script until this expiration date is reached\nif the user exits the browser and restarts it. If an expiration date isn't specified, the\ncookie will remain active until the user quits the browser.\n\n2. a domain\nThis is a partial or complete domain name for which the cookie is valid. The browser will\nreturn the cookie to any host that matches the partial domain name. For example, if you\nspecify a domain name of \".capricorn.com\", then the browser will return the cookie to Web\nservers running on any of the machines \"www.capricorn.com\", \"www2.capricorn.com\",\n\"feckless.capricorn.com\", etc. Domain names must contain at least two periods to prevent\nattempts to match on top level domains like \".edu\". If no domain is specified, then the\nbrowser will only return the cookie to servers on the host the cookie originated from.\n\n3. a path\nIf you provide a cookie path attribute, the browser will check it against your script's URL\nbefore returning the cookie. For example, if you specify the path \"/cgi-bin\", then the\ncookie will be returned to each of the scripts \"/cgi-bin/tally.pl\", \"/cgi-bin/order.pl\", and\n\"/cgi-bin/customerservice/complain.pl\", but not to the script \"/cgi-private/siteadmin.pl\".\nBy default, path is set to \"/\", which causes the cookie to be sent to any CGI script on your\nsite.\n\n4. a \"secure\" flag\nIf the \"secure\" attribute is set, the cookie will only be sent to your script if the CGI\nrequest is occurring on a secure channel, such as SSL.\n\nThe interface to HTTP cookies is the cookie() method:\n\nmy $cookie = $q->cookie(\n-name    => 'sessionID',\n-value   => 'xyzzy',\n-expires => '+1h',\n-path    => '/cgi-bin/database',\n-domain  => '.capricorn.org',\n-secure  => 1\n);\n\nprint $q->header( -cookie => $cookie );\n",
            "subsections": [
                {
                    "name": "cookie",
                    "content": ""
                },
                {
                    "name": "-name",
                    "content": "The name of the cookie (required). This can be any string at all. Although browsers limit\ntheir cookie names to non-whitespace alphanumeric characters, CGI.pm removes this\nrestriction by escaping and unescaping cookies behind the scenes.\n"
                },
                {
                    "name": "-value",
                    "content": "The value of the cookie. This can be any scalar value, array reference, or even hash\nreference. For example, you can store an entire hash into a cookie this way:\n\nmy $cookie = $q->cookie(\n-name  => 'family information',\n-value => \\%childrensages\n);\n"
                },
                {
                    "name": "-path",
                    "content": "The optional partial path for which this cookie will be valid, as described above.\n"
                },
                {
                    "name": "-domain",
                    "content": "The optional partial domain for which this cookie will be valid, as described above.\n"
                },
                {
                    "name": "-expires",
                    "content": "The optional expiration date for this cookie. The format is as described in the section on\nthe header() method:\n\n\"+1h\"  one hour from now\n"
                },
                {
                    "name": "-secure",
                    "content": "If set to true, this cookie will only be used within a secure SSL session.\n\nThe cookie created by cookie() must be incorporated into the HTTP header within the string\nreturned by the header() method:\n\nuse strict;\nuse warnings;\n\nuse CGI;\n\nmy $q      = CGI->new;\nmy $cookie = ...\nprint $q->header( -cookie => $cookie );\n\nTo create multiple cookies, give header() an array reference:\n\nmy $cookie1 = $q->cookie(\n-name  => 'riddlename',\n-value => \"The Sphynx's Question\"\n);\n\nmy $cookie2 = $q->cookie(\n-name  => 'answers',\n-value => \\%answers\n);\n\nprint $q->header( -cookie => [ $cookie1,$cookie2 ] );\n\nTo retrieve a cookie, request it by name by calling cookie() method without the -value\nparameter. This example uses the object-oriented form:\n\nmy $riddle  = $q->cookie('riddlename');\nmy %answers = $q->cookie('answers');\n\nCookies created with a single scalar value, such as the \"riddlename\" cookie, will be returned\nin that form. Cookies with array and hash values can also be retrieved.\n\nThe cookie and CGI namespaces are separate. If you have a parameter named 'answers' and a cookie\nnamed 'answers', the values retrieved by param() and cookie() are independent of each other.\nHowever, it's simple to turn a CGI parameter into a cookie, and vice-versa:\n\n# turn a CGI parameter into a cookie\nmy $c = cookie( -name => 'answers',-value => [$q->param('answers')] );\n# vice-versa\n$q->param( -name => 'answers',-value => [ $q->cookie('answers')] );\n\nIf you call cookie() without any parameters, it will return a list of the names of all cookies\npassed to your script:\n\nmy @cookies = $q->cookie();\n\nSee the cookie.cgi example script for some ideas on how to use cookies effectively.\n\n$CGI::COOKIECACHE\nIf set to a non-negative integer, this variable will cause CGI.pm to use the cached cookie\ndetails from the previous call to cookie(). By default this cache is off to retain backwards\ncompatibility.\n"
                }
            ]
        },
        "DEBUGGING": {
            "content": "If you are running the script from the command line or in the perl debugger, you can pass the\nscript a list of keywords or parameter=value pairs on the command line or from standard input\n(you don't have to worry about tricking your script into reading from environment variables).\nYou can pass keywords like this:\n\nyourscript.pl keyword1 keyword2 keyword3\n\nor this:\n\nyourscript.pl keyword1+keyword2+keyword3\n\nor this:\n\nyourscript.pl name1=value1 name2=value2\n\nor this:\n\nyourscript.pl name1=value1&name2=value2\n\nTo turn off this feature, use the -nodebug pragma.\n\nTo test the POST method, you may enable full debugging with the -debug pragma. This will allow\nyou to feed newline-delimited name=value pairs to the script on standard input.\n\nWhen debugging, you can use quotes and backslashes to escape characters in the familiar shell\nmanner, letting you place spaces and other funny characters in your parameter=value pairs:\n\nyourscript.pl \"name1='I am a long value'\" \"name2=two\\ words\"\n\nFinally, you can set the path info for the script by prefixing the first name/value parameter\nwith the path followed by a question mark (?):\n\nyourscript.pl /your/path/here?name1=value1&name2=value2\n",
            "subsections": []
        },
        "FETCHING ENVIRONMENT VARIABLES": {
            "content": "Some of the more useful environment variables can be fetched through this interface. The methods\nare as follows:\n\nAccept()\nReturn a list of MIME types that the remote browser accepts. If you give this method a\nsingle argument corresponding to a MIME type, as in Accept('text/html'), it will return a\nfloating point value corresponding to the browser's preference for this type from 0.0 (don't\nwant) to 1.0. Glob types (e.g. text/*) in the browser's accept list are handled correctly.\n\nNote that the capitalization changed between version 2.43 and 2.44 in order to avoid\nconflict with perl's accept() function.\n",
            "subsections": [
                {
                    "name": "raw_cookie",
                    "content": "Returns the HTTPCOOKIE variable. Cookies have a special format, and this method call just\nreturns the raw form (?cookie dough). See cookie() for ways of setting and retrieving cooked\ncookies.\n\nCalled with no parameters, rawcookie() returns the packed cookie structure. You can\nseparate it into individual cookies by splitting on the character sequence \"; \". Called with\nthe name of a cookie, retrieves the unescaped form of the cookie. You can use the regular\ncookie() method to get the names, or use the rawfetch() method from the CGI::Cookie module.\n"
                },
                {
                    "name": "env_query_string",
                    "content": "Returns the QUERYSTRING variable, note that this is the original value as set in the\nenvironment by the webserver and (possibly) not the same value as returned by\nquerystring(), which represents the object state\n"
                },
                {
                    "name": "user_agent",
                    "content": "Returns the HTTPUSERAGENT variable. If you give this method a single argument, it will\nattempt to pattern match on it, allowing you to do something like useragent(Mozilla);\n"
                },
                {
                    "name": "path_info",
                    "content": "Returns additional path information from the script URL. E.G. fetching\n/cgi-bin/yourscript/additional/stuff will result in pathinfo() returning\n\"/additional/stuff\".\n\nNOTE: The Microsoft Internet Information Server is broken with respect to additional path\ninformation. If you use the perl DLL library, the IIS server will attempt to execute the\nadditional path information as a perl script. If you use the ordinary file associations\nmapping, the path information will be present in the environment, but incorrect. The best\nthing to do is to avoid using additional path information in CGI scripts destined for use\nwith IIS. A best attempt has been made to make CGI.pm do the right thing.\n"
                },
                {
                    "name": "path_translated",
                    "content": "As per pathinfo() but returns the additional path information translated into a physical\npath, e.g. \"/usr/local/etc/httpd/htdocs/additional/stuff\".\n\nThe Microsoft IIS is broken with respect to the translated path as well.\n"
                },
                {
                    "name": "remote_host",
                    "content": "Returns either the remote host name or IP address if the former is unavailable.\n"
                },
                {
                    "name": "remote_ident",
                    "content": "Returns the name of the remote user (as returned by identd) or undef if not set\n"
                },
                {
                    "name": "remote_addr",
                    "content": "Returns the remote host IP address, or 127.0.0.1 if the address is unavailable.\n"
                },
                {
                    "name": "request_uri",
                    "content": "Returns the interpreted pathname of the requested document or CGI (relative to the document\nroot). Or undef if not set.\n"
                },
                {
                    "name": "script_name",
                    "content": "Return the script name as a partial URL, for self-referring scripts.\n"
                },
                {
                    "name": "referer",
                    "content": "Return the URL of the page the browser was viewing prior to fetching your script.\n"
                },
                {
                    "name": "auth_type",
                    "content": "Return the authorization/verification method in use for this script, if any.\n"
                },
                {
                    "name": "server_name",
                    "content": "Returns the name of the server, usually the machine's host name.\n"
                },
                {
                    "name": "virtual_host",
                    "content": "When using virtual hosts, returns the name of the host that the browser attempted to contact\n"
                },
                {
                    "name": "server_port",
                    "content": "Return the port that the server is listening on.\n"
                },
                {
                    "name": "server_protocol",
                    "content": "Returns the protocol and revision of the incoming request, or defaults to HTTP/1.0 if this\nis not set\n"
                },
                {
                    "name": "virtual_port",
                    "content": "Like serverport() except that it takes virtual hosts into account. Use this when running\nwith virtual hosts.\n"
                },
                {
                    "name": "server_software",
                    "content": "Returns the server software and version number.\n"
                },
                {
                    "name": "remote_user",
                    "content": "Return the authorization/verification name used for user verification, if this script is\nprotected.\n"
                },
                {
                    "name": "user_name",
                    "content": "Attempt to obtain the remote user's name, using a variety of different techniques. May not\nwork in all browsers.\n"
                },
                {
                    "name": "request_method",
                    "content": "Returns the method used to access your script, usually one of 'POST', 'GET' or 'HEAD'. If\nrunning from the command line it will be undef.\n"
                },
                {
                    "name": "content_type",
                    "content": "Returns the contenttype of data submitted in a POST, generally multipart/form-data or\napplication/x-www-form-urlencoded\n"
                },
                {
                    "name": "http",
                    "content": "Called with no arguments returns the list of HTTP environment variables, including such\nthings as HTTPUSERAGENT, HTTPACCEPTLANGUAGE, and HTTPACCEPTCHARSET, corresponding to\nthe like-named HTTP header fields in the request. Called with the name of an HTTP header\nfield, returns its value. Capitalization and the use of hyphens versus underscores are not\nsignificant.\n\nFor example, all three of these examples are equivalent:\n\nmy $requestedlanguage = $q->http('Accept-language');\n\nmy $requestedlanguage = $q->http('Acceptlanguage');\n\nmy $requestedlanguage = $q->http('HTTPACCEPTLANGUAGE');\n"
                },
                {
                    "name": "https",
                    "content": "The same as *http()*, but operates on the HTTPS environment variables present when the SSL\nprotocol is in effect. Can be used to determine whether SSL is turned on.\n"
                }
            ]
        },
        "USING NPH SCRIPTS": {
            "content": "NPH, or \"no-parsed-header\", scripts bypass the server completely by sending the complete HTTP\nheader directly to the browser. This has slight performance benefits, but is of most use for\ntaking advantage of HTTP extensions that are not directly supported by your server, such as\nserver push and PICS headers.\n\nServers use a variety of conventions for designating CGI scripts as NPH. Many Unix servers look\nat the beginning of the script's name for the prefix \"nph-\". The Macintosh WebSTAR server and\nMicrosoft's Internet Information Server, in contrast, try to decide whether a program is an NPH\nscript by examining the first line of script output.\n\nCGI.pm supports NPH scripts with a special NPH mode. When in this mode, CGI.pm will output the\nnecessary extra header information when the header() and redirect() methods are called.\n\nThe Microsoft Internet Information Server requires NPH mode. As of version 2.30, CGI.pm will\nautomatically detect when the script is running under IIS and put itself into this mode. You do\nnot need to do this manually, although it won't hurt anything if you do.\n\nIn the use statement\nSimply add the \"-nph\" pragma to the list of symbols to be imported into your script:\n\nuse CGI qw(:standard -nph)\n\nBy calling the nph() method:\nCall nph() with a non-zero parameter at any point after using CGI.pm in your program.\n\nCGI->nph(1)\n\nBy using -nph parameters\nin the header() and redirect() statements:\n\nprint header(-nph=>1);\n",
            "subsections": []
        },
        "SERVER PUSH": {
            "content": "CGI.pm provides four simple functions for producing multipart documents of the type needed to\nimplement server push. These functions were graciously provided by Ed Jordan <ed@fidalgo.net>.\nTo import these into your namespace, you must import the \":push\" set. You are also advised to\nput the script into NPH mode and to set $| to 1 to avoid buffering problems.\n\nHere is a simple script that demonstrates server push:\n\n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nuse CGI qw/:push -nph/;\n\n$| = 1;\nprint multipartinit( -boundary=>'----here we go!' );\nfor (0 .. 4) {\nprint multipartstart( -type=>'text/plain' ),\n\"The current time is \",scalar( localtime ),\"\\n\";\nif ($ < 4) {\nprint multipartend();\n} else {\nprint multipartfinal();\n}\nsleep 1;\n}\n\nThis script initializes server push by calling multipartinit(). It then enters a loop in which\nit begins a new multipart section by calling multipartstart(), prints the current local time,\nand ends a multipart section with multipartend(). It then sleeps a second, and begins again. On\nthe final iteration, it ends the multipart section with multipartfinal() rather than with",
            "subsections": [
                {
                    "name": "multipart_end",
                    "content": ""
                },
                {
                    "name": "multipart_init",
                    "content": "multipartinit( -boundary => $boundary, -charset => $charset );\n\nInitialize the multipart system. The -boundary argument specifies what MIME boundary string\nto use to separate parts of the document. If not provided, CGI.pm chooses a reasonable\nboundary for you.\n\nThe -charset provides the character set, if not provided this will default to ISO-8859-1\n"
                },
                {
                    "name": "multipart_start",
                    "content": "multipartstart( -type => $type, -charset => $charset );\n\nStart a new part of the multipart document using the specified MIME type and charset. If not\nspecified, text/html ISO-8859-1 is assumed.\n"
                },
                {
                    "name": "multipart_end",
                    "content": "multipartend()\n\nEnd a part. You must remember to call multipartend() once for each multipartstart(),\nexcept at the end of the last part of the multipart document when multipartfinal() should\nbe called instead of multipartend().\n"
                },
                {
                    "name": "multipart_final",
                    "content": "multipartfinal()\n\nEnd all parts. You should call multipartfinal() rather than multipartend() at the end of\nthe last part of the multipart document.\n\nUsers interested in server push applications should also have a look at the CGI::Push module.\n"
                }
            ]
        },
        "AVOIDING DENIAL OF SERVICE ATTACKS": {
            "content": "A potential problem with CGI.pm is that, by default, it attempts to process form POSTings no\nmatter how large they are. A wily hacker could attack your site by sending a CGI script a huge\nPOST of many gigabytes. CGI.pm will attempt to read the entire POST into a variable, growing\nhugely in size until it runs out of memory. While the script attempts to allocate the memory the\nsystem may slow down dramatically. This is a form of denial of service attack.\n\nAnother possible attack is for the remote user to force CGI.pm to accept a huge file upload.\nCGI.pm will accept the upload and store it in a temporary directory even if your script doesn't\nexpect to receive an uploaded file. CGI.pm will delete the file automatically when it\nterminates, but in the meantime the remote user may have filled up the server's disk space,\ncausing problems for other programs.\n\nThe best way to avoid denial of service attacks is to limit the amount of memory, CPU time and\ndisk space that CGI scripts can use. Some Web servers come with built-in facilities to\naccomplish this. In other cases, you can use the shell *limit* or *ulimit* commands to put\nceilings on CGI resource usage.\n\nCGI.pm also has some simple built-in protections against denial of service attacks, but you must\nactivate them before you can use them. These take the form of two global variables in the CGI\nname space:\n\n$CGI::POSTMAX\nIf set to a non-negative integer, this variable puts a ceiling on the size of POSTings, in\nbytes. If CGI.pm detects a POST that is greater than the ceiling, it will immediately exit\nwith an error message. This value will affect both ordinary POSTs and multipart POSTs,\nmeaning that it limits the maximum size of file uploads as well. You should set this to a\nreasonably high value, such as 10 megabytes.\n\n$CGI::DISABLEUPLOADS\nIf set to a non-zero value, this will disable file uploads completely. Other fill-out form\nvalues will work as usual.\n\nTo use these variables, set the variable at the top of the script, right after the \"use\"\nstatement:\n\n#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nuse CGI;\n\n$CGI::POSTMAX = 1024 * 1024 * 10;  # max 10MB posts\n$CGI::DISABLEUPLOADS = 1;          # no uploads\n\nAn attempt to send a POST larger than $POSTMAX bytes will cause *param()* to return an empty\nCGI parameter list. You can test for this event by checking *cgierror()*, either after you\ncreate the CGI object or, if you are using the function-oriented interface, call <param()> for\nthe first time. If the POST was intercepted, then cgierror() will return the message \"413 POST\ntoo large\".\n\nThis error message is actually defined by the HTTP protocol, and is designed to be returned to\nthe browser as the CGI script's status code. For example:\n\nmy $uploadedfile = $q->param('upload');\nif ( !$uploadedfile && $q->cgierror() ) {\nprint $q->header( -status => $q->cgierror() );\nexit 0;\n}\n\nHowever it isn't clear that any browser currently knows what to do with this status code. It\nmight be better just to create a page that warns the user of the problem.\n",
            "subsections": []
        },
        "MODULE FLAGS": {
            "content": "There are a number of global module flags which affect how CGI.pm operates.\n\n$CGI::APPENDQUERYSTRING\nIf set to a non-zero value, this will add query string parameters to a POST forms parameters\nhence allowing *param()* to return values from the query string as well as from the decoded\nPOST request instead of having to use *urlparam* instead. This makes it easier to get the\nvalue of a parameter when you don't know the source.\n\nCOMPATIBILITY WITH CGI-LIB.PL\nTo make it easier to port existing programs that use cgi-lib.pl the compatibility routine\n\"ReadParse\" is provided. Porting is simple:\n\nOLD VERSION\n\nrequire \"cgi-lib.pl\";\n&ReadParse;\nprint \"The value of the antique is $in{antique}.\\n\";\n\nNEW VERSION\n\nuse CGI;\nCGI::ReadParse();\nprint \"The value of the antique is $in{antique}.\\n\";\n\nCGI.pm's ReadParse() routine creates a tied variable named %in, which can be accessed to obtain\nthe query variables. Like ReadParse, you can also provide your own variable. Infrequently used\nfeatures of ReadParse, such as the creation of @in and $in variables, are not supported.\n\nOnce you use ReadParse, you can retrieve the query object itself this way:\n\nmy $q = $in{CGI};\n\nThis allows you to start using the more interesting features of CGI.pm without rewriting your\nold scripts from scratch.\n\nAn even simpler way to mix cgi-lib calls with CGI.pm calls is to import both the \":cgi-lib\" and\n\":standard\" method:\n\nuse CGI qw(:cgi-lib :standard);\n&ReadParse;\nprint \"The price of your purchase is $in{price}.\\n\";\nprint textfield(-name=>'price', -default=>'$1.99');\n",
            "subsections": [
                {
                    "name": "Cgi-lib functions that are available in CGI.pm",
                    "content": "In compatibility mode, the following cgi-lib.pl functions are available for your use:\n\nReadParse()\nPrintHeader()\nSplitParam()\nMethGet()\nMethPost()\n"
                }
            ]
        },
        "LICENSE": {
            "content": "The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is distributed under the\nArtistic License 2.0. It is currently maintained by Lee Johnson (LEEJO) with help from many\ncontributors.\n",
            "subsections": []
        },
        "CREDITS": {
            "content": "Thanks very much to:\n\nMark Stosberg (mark@stosberg.com)\nMatt Heffron (heffron@falstaff.css.beckman.com)\nJames Taylor (james.taylor@srs.gov)\nScott Anguish (sanguish@digifix.com)\nMike Jewell (mlj3u@virginia.edu)\nTimothy Shimmin (tes@kbs.citri.edu.au)\nJoergen Haegg (jh@axis.se)\nLaurent Delfosse (delfosse@delfosse.com)\nRichard Resnick (applepi1@aol.com)\nCraig Bishop (csb@barwonwater.vic.gov.au)\nTony Curtis (tc@vcpc.univie.ac.at)\nTim Bunce (Tim.Bunce@ig.co.uk)\nTom Christiansen (tchrist@convex.com)\nAndreas Koenig (k@franz.ww.TU-Berlin.DE)\nTim MacKenzie (Tim.MacKenzie@fulcrum.com.au)\nKevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)\nStephen Dahmen (joyfire@inxpress.net)\nEd Jordan (ed@fidalgo.net)\nDavid Alan Pisoni (david@cnation.com)\nDoug MacEachern (dougm@opengroup.org)\nRobin Houston (robin@oneworld.org)\n...and many many more...\nfor suggestions and bug fixes.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "Address bug reports and comments to: <https://github.com/leejo/CGI.pm/issues>\n\nSee the <https://github.com/leejo/CGI.pm/blob/master/CONTRIBUTING.md> file for information on\nraising issues and contributing\n\nThe original bug tracker can be found at:\n<https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm>\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "CGI::Carp - provides Carp implementation tailored to the CGI environment.\n\nCGI::Fast - supports running CGI applications under FastCGI\n",
            "subsections": []
        }
    },
    "summary": "CGI - Handle Common Gateway Interface requests and responses",
    "flags": [],
    "examples": [],
    "see_also": []
}