CGI(3pm) User Contributed Perl Documentation CGI(3pm)
CGI - Handle Common Gateway Interface requests and responses
| Use Case | Command | Description |
|---|---|---|
| Create CGI object | my $q = CGI->new; | Parse request and create object |
| Get single parameter | $q->param('name'); | Fetch form field value (scalar) |
| Get multiple parameter values | $q->multi_param('name'); | Fetch list of values (safe) |
| Get uploaded file handle | $q->upload('field'); | Returns IO::File compatible handle |
| Create a cookie | $q->cookie(-name=>'n', -value=>'v'); | Build cookie object |
| Retrieve a cookie | $q->cookie('name'); | Get cookie value |
| Print HTTP header | $q->header(); | Output Content-Type header |
| Redirect browser | $q->redirect('http://url'); | Send 302 redirect |
| Self-referencing URL | $q->self_url(); | URL preserving state |
| Query string representation | $q->query_string(); | Current state as query string |
| Set POST size limit | $CGI::POST_MAX = 10_485_760; | Limit POST body to 10MB |
| Disable file uploads | $CGI::DISABLE_UPLOADS = 1; | Refuse all uploads |
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('form_field');
my $value = $q->param('param_name');
my $fh = $q->upload('file_field');
my $riddle = $q->cookie('riddle_name');
my %answers = $q->cookie('answers');
# Prepare various HTTP responses
print $q->header();
print $q->header('application/json');
my $cookie1 = $q->cookie(
-name => 'riddle_name',
-value => "The Sphynx's Question"
);
my $cookie2 = $q->cookie(
-name => 'answers',
-value => \%answers
);
print $q->header(
-type => 'image/gif',
-expires => '+3d',
-cookie => [ $cookie1,$cookie2 ]
);
print $q->redirect('http://somewhere.else/in/movie/land');
CGI.pm is a stable, complete and mature solution for processing and preparing HTTP requests and responses. Major features include processing form submissions, file uploads, reading and writing cookies, query string generation and manipulation, and processing and preparing HTTP headers.
CGI.pm performs very well in a vanilla CGI environment and also comes with built-in support for mod_perl and mod_perl2 as well as FastCGI.
It has been developed and refined over 20 years with input from dozens of contributors and deployed on thousands of websites. CGI.pm was included in the perl distribution from perl v5.4 to v5.20, however it has now been removed from the perl core.
⚠️ CGI.pm HAS BEEN REMOVED FROM THE PERL CORE
See http://perl5.git.perl.org/perl.git/commitdiff/e9fa5a80
If you upgrade to a new version of perl or rely on a system/vendor perl, you will have to install CGI.pm yourself with cpan/cpanm/a vendor package/manually. The CGI::Fast module has been split into its own distribution, so you do not need a compiler to install CGI.pm.
The rationale is that CGI.pm is no longer considered good practice for developing web applications. See CGI::Alternatives for better alternatives.
All HTML generation functions within CGI.pm are no longer being maintained. Any issues, bugs, or patches will be rejected unless they relate to fundamentally broken page rendering. You should use a template engine for better separation of concerns. See CGI::Alternatives for an example of using CGI.pm with Template::Toolkit.
These functions are considered deprecated, but they will continue to exist in CGI.pm without deprecation warnings ("soft" deprecation). All documentation for these functions has been moved to CGI::HTML::Functions.
There are two styles of programming with CGI.pm: an object-oriented (OO) style and a function-oriented style. You are recommended to use the OO style as CGI.pm will create an internal default object when functions are called procedurally, avoiding method name clashes with perl builtins.
In the OO style you create one or more CGI objects and use object methods. Each CGI object starts with the list of named parameters passed to your CGI script. You can modify, save, and recreate them, allowing you to save and restore script state.
Example:
#!/usr/bin/env perl
use strict;
use warnings;
use CGI;
my $q = CGI->new;
print $q->header;
In the function-oriented style, there is one default CGI object. You import functions and call them directly:
#!/usr/bin/env perl
use strict;
use warnings;
use CGI qw/:standard/;
print header();
See HOW TO IMPORT FUNCTIONS for important information on function-oriented programming.
Most CGI.pm routines accept several arguments using a named argument calling style with dashes:
print $q->header(
-type => 'image/gif',
-expires => '+3d',
);
Neither case nor order matters. Only the first argument needs to begin with a dash. Some routines can be called with a single argument without a name, e.g. header('text/html').
Named arguments can be scalar, array reference, or hash reference. For example, param() is used to set a single or multi-valued parameter:
$q->param(-name => 'veggie', -value => 'tomato');
$q->param(-name => 'veggie', -value => [ qw/tomato tomahto/ ]);
Unrecognized named arguments produce non-standard HTTP header fields:
print $q->header(
-type => 'text/html',
-cost => 'Three smackers',
-annoyance_level => 'high',
);
# Produces: Cost: Three smackers, Annoyance-level: high, ...
my $q = CGI->new;
This parses input (POST, GET, DELETE) and stores it in a perl5 object. All file uploads have their position reset to the beginning of the file.
my $q = CGI->new( $input_filehandle );
You can also initialize from a hash reference, a URL-escaped query string, or a previously existing CGI object. To create an empty query, use an empty string or hash:
my $empty_query = CGI->new("");
my $empty_query = CGI->new({});
my @keywords = $q->keywords
If the script was invoked as the result of an ISINDEX search, the parsed keywords can be obtained using the keywords() method.
my @names = $q->multi_param
my @names = $q->param
Returns parameter names in the order they were submitted by the browser.
my @values = $q->multi_param('foo');
my $value = $q->param('foo');
Warning: calling param() in list context can lead to vulnerabilities. Use multi_param() instead. If a parameter is not given, returns an empty string; if it does not exist, returns undef in scalar context or empty list in list context.
$q->param('foo','an','array','of','values');
$q->param(-name => 'foo', -values => ['an','array','of','values']);
$q->append(-name =>'foo', -values =>['yet','more','values']);
$q->import_names('R');
Creates variables in the given namespace. WARNING: don't import into 'main'; this is a major security risk. Non-legal characters are transformed into underscores. It is recommended to use the param() method instead.
$q->delete('foo','bar','baz');
To delete all parameters:
$q->delete_all();
If POSTed data is not of type application/x-www-form-urlencoded or multipart/form-data, the data is returned as-is in a parameter named POSTDATA. Similarly for PUT and PATCH data:
my $data = $q->param('POSTDATA');
my $data = $q->param('PUTDATA');
my $data = $q->param('PATCHDATA');
$q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
Returns an array reference to the named parameter.
my $params = $q->Vars;
print $params->{'address'};
In scalar context returns a tied hash reference; in list context returns an ordinary hash. Multivalued parameters are packed with null characters.
$q->save(\*FILEHANDLE)
Writes the current form state to a filehandle. The format is:
NAME1=VALUE1
NAME1=VALUE1'
NAME2=VALUE2
NAME3=VALUE3
=
Multiple records can be saved and read back with multiple calls to new.
if ( my $error = $q->cgi_error ) {
print $q->header( -status => $error );
print "Error: $error";
exit 0;
}
use CGI qw/ list of methods /;
You can import specific methods or function sets (preceded by ":"). Common sets:
:cgi – all CGI-handling methods:all – all available methods (except :cgi-lib)Pragmas change the way CGI.pm functions. They are imported with a hyphen prefix:
-no_undef_params – excludes undef params from the parameter list-utf8 – treats all parameters as UTF-8 text strings-putdata_upload / -postdata_upload / -patchdata_upload – makes PUTDATA/POSTDATA/PATCHDATA act like file uploads-nph – produces headers for NPH (no parsed header) scripts-newstyle_urls – separate name=value pairs with semicolons (default since 2.64)-oldstyle_urls – separate with ampersands (no longer default)-no_debug – turns off command-line processing-debug – enables full debugging (reads from STDIN)Most of CGI.pm's functions deal with creating documents on the fly. Generally you produce the HTTP header first, followed by the document itself.
print $cgi->header;
print $cgi->header('image/gif');
print $cgi->header('text/html','204 No response');
print $cgi->header(
-type => 'image/gif',
-nph => 1,
-status => '402 Payment required',
-expires => '+3d',
-cookie => $cookie,
-charset => 'utf-8',
-attachment => 'foo.gif',
-Cost => '$2.00'
);
The header() method returns the Content-type header. Recognized parameters: -type, -status, -expires, -cookie, -nph, -charset, -attachment, -p3p. Any other named parameters become HTTP header fields (underscores become hyphens).
Valid expiration formats: +30s, +10m, +1h, now, +3M, +10y, absolute date.
print $q->redirect( 'http://somewhere.else/in/movie/land' );
print $q->redirect(
-uri => 'http://somewhere.else/in/movie/land',
-nph => 1,
-status => '301 Moved Permanently'
);
Redirects the browser to a different URL. Use full URLs for best results.
my $myself = $q->self_url;
print qq(<a href="$myself">I'm talking to myself.</a>);
Also available: query_string() returns the current state as a query string; env_query_string() returns the original QUERY_STRING from the environment.
my $full_url = url();
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 );
Parameters: -absolute, -relative, -full, -path/-path_info, -query/-query_string, -base, -rewrite.
my $color = url_param('color');
Use url_param() to retrieve parameters from the URL query string when the form uses POST.
if ( my $io_handle = $q->upload('field_name') ) {
open ( my $out_file,'>>','/usr/local/web/users/feedback' );
while ( my $bytesread = $io_handle->read($buffer,1024) ) {
print $out_file $buffer;
}
}
In list context, upload() returns an array of filehandles. Use param() to get the original filename. Use uploadInfo() to get MIME headers:
my $type = $q->uploadInfo( $filehandle )->{'Content-Type'};
Access the temporary file directly with tmpFileName(). Temporary files are deleted automatically unless you rename them or set $CGI::UNLINK_TMP_FILES to 0.
Changes in v4.05+ use File::Temp internally. The PRIVATE_TEMPFILES variable is removed. The Fh package is empty; CGI::File::Temp is a subclass of both File::Temp and the empty Fh.
For interrupted uploads, cgi_error() returns "400 Bad request (malformed multipart POST)".
Progress bars: use a hook callback:
my $q = CGI->new( \&hook [,$data [,$use_tempfile]] );
sub hook {
my ( $filename, $buffer, $bytes_read, $data ) = @_;
print "Read $bytes_read bytes of $filename\n";
}
Set $use_tempfile to false to disable temp file storage.
CGI.pm supports cookies with methods for creating and retrieving them. A cookie is a name=value pair with optional attributes: expiration time, domain, path, and secure flag.
my $cookie = $q->cookie(
-name => 'sessionID',
-value => 'xyzzy',
-expires => '+1h',
-path => '/cgi-bin/database',
-domain => '.capricorn.org',
-secure => 1
);
print $q->header( -cookie => $cookie );
Parameters: -name (required), -value (scalar, array ref, or hash ref), -path, -domain, -expires, -secure.
my $riddle = $q->cookie('riddle_name');
my %answers = $q->cookie('answers');
Calling cookie() without parameters returns a list of all cookie names.
$CGI::COOKIE_CACHE – if set to a non-negative integer, caches cookie details from the previous call. Default is off.
You can run the script from the command line with keywords or parameter=value pairs:
your_script.pl keyword1 keyword2 keyword3
your_script.pl name1=value1 name2=value2
Use -no_debug pragma to turn off this feature. Use -debug pragma to enable full debugging (reads from STDIN). You can use quotes and backslashes to escape characters. Set path info by prefixing with a path followed by "?".
Accept() – returns list of MIME types the browser accepts; with argument returns preference float (0.0 to 1.0)raw_cookie() – returns HTTP_COOKIE raw stringenv_query_string() – returns QUERY_STRING from environmentuser_agent() – returns HTTP_USER_AGENT; with argument pattern matchespath_info() – returns additional path informationpath_translated() – returns physical path of additional path inforemote_host() – returns remote host name or IPremote_ident() – returns remote user name from identdremote_addr() – returns remote host IPrequest_uri() – returns interpreted pathnamescript_name() – returns script name as partial URLreferer() – returns referring URLauth_type() – returns authorization methodserver_name() – returns server host namevirtual_host() – returns virtual host nameserver_port() – returns server portserver_protocol() – returns protocol/revisionvirtual_port() – returns port considering virtual hostsserver_software() – returns server softwareremote_user() – returns authorization/verification nameuser_name() – attempts to obtain remote user's namerequest_method() – returns 'POST', 'GET', 'HEAD'content_type() – returns content type of POST datahttp() – returns list or value of HTTP environment variableshttps() – same as http() but for HTTPS variablesNPH (no-parsed-header) scripts send the complete HTTP header directly to the browser. CGI.pm supports NPH mode via:
use CGI qw(:standard -nph)CGI->nph(1)-nph=>1 in header() and redirect()Microsoft IIS requires NPH mode; CGI.pm detects it automatically.
#!/usr/bin/env perl
use strict;
use warnings;
use CGI qw/:push -nph/;
$| = 1;
print multipart_init( -boundary=>'----here we go!' );
for (0 .. 4) {
print multipart_start( -type=>'text/plain' ),
"The current time is ",scalar( localtime ),"\n";
if ($_ < 4) {
print multipart_end();
} else {
print multipart_final();
}
sleep 1;
}
multipart_init() – initializes multipart systemmultipart_start() – starts a new partmultipart_end() – ends a partmultipart_final() – ends all partsSee also CGI::Push.
Set global variables to limit resource usage:
$CGI::POST_MAX = 1024 * 1024 * 10; # max 10MB posts
$CGI::DISABLE_UPLOADS = 1; # no uploads
If a POST exceeds $POST_MAX, param() returns an empty list and cgi_error() returns "413 POST too large".
$CGI::APPEND_QUERY_STRING – if true, query string parameters are added to POST form parameters, making them available via param().use CGI;
CGI::ReadParse();
print "The value of the antique is $in{antique}.\n";
Provides ReadParse(), PrintHeader(), SplitParam(), MethGet(), MethPost(). The tied variable %in contains query variables. Retrieve the query object with my $q = $in{CGI};.
Copyright 1995-2007, Lincoln D. Stein. Distributed under the Artistic License 2.0. Currently maintained by Lee Johnson (LEEJO) with help from many contributors.
Thanks to: Mark Stosberg, Matt Heffron, James Taylor, Scott Anguish, Mike Jewell, Timothy Shimmin, Joergen Haegg, Laurent Delfosse, Richard Resnick, Craig Bishop, Tony Curtis, Tim Bunce, Tom Christiansen, Andreas Koenig, Tim MacKenzie, Kevin B. Hendricks, Stephen Dahmen, Ed Jordan, David Alan Pisoni, Doug MacEachern, Robin Houston, and many more.
Address bug reports and comments to: https://github.com/leejo/CGI.pm/issues
See CONTRIBUTING.md for information on raising issues.
Original bug tracker: https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm
perl v5.34.0 2022-02-12 CGI(3pm)
Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-14 20:52 @2600:1f28:365:80b0:4d23:66fa:c2bb:7bae
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)