info > CGI

CGI(3pm) User Contributed Perl Documentation CGI(3pm)

📖 NAME

CGI - Handle Common Gateway Interface requests and responses

🚀 Quick Reference

Use CaseCommandDescription
Create CGI objectmy $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

📋 SYNOPSIS

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');

📝 DESCRIPTION

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.

⚠️ HTML Generation functions should no longer be used

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.

🧑‍💻 Programming style

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.

📞 Calling CGI.pm routines

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, ...

🆕 Creating a new query object (object-oriented style)

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.

📄 Creating a new query object from an input 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({});

🔑 Fetching a list of keywords from the query

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.

📋 Fetching the names of all parameters

my @names = $q->multi_param
my @names = $q->param

Returns parameter names in the order they were submitted by the browser.

🔍 Fetching the value(s) of a single named parameter

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.

✏️ Setting the value(s) of a named parameter

$q->param('foo','an','array','of','values');
$q->param(-name => 'foo', -values => ['an','array','of','values']);

➕ Appending additional values to a named parameter

$q->append(-name =>'foo', -values =>['yet','more','values']);

📦 Importing all parameters into a namespace

$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.

🗑️ Deleting a parameter completely

$q->delete('foo','bar','baz');

To delete all parameters:

$q->delete_all();

📡 Handling non-urlencoded arguments

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');

🔧 Direct access to the parameter list

$q->param_fetch('address')->[1] = '1313 Mockingbird Lane';

Returns an array reference to the named parameter.

📑 Fetching the parameter list as a hash

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.

💾 Saving the state of the script to a file

$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.

❌ Retrieving cgi errors

if ( my $error = $q->cgi_error ) {
    print $q->header( -status => $error );
    print "Error: $error";
    exit 0;
}

📦 Using the function-oriented interface

use CGI qw/ list of methods /;

You can import specific methods or function sets (preceded by ":"). Common sets:

⚙️ Pragmas

Pragmas change the way CGI.pm functions. They are imported with a hyphen prefix:

🌐 GENERATING DYNAMIC DOCUMENTS

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.

📄 Creating a standard http header

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.

🔀 Generating a redirection header

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.

🔗 Creating a self-referencing url that preserves state

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.

🌍 Obtaining the script's url

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.

🔀 Mixing post and url parameters

my $color = url_param('color');

Use url_param() to retrieve parameters from the URL query string when the form uses POST.

📁 Processing a file upload field

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.

🍪 HTTP COOKIES

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.

Creating a cookie

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.

Retrieving a cookie

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.

🐛 DEBUGGING

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 "?".

🌍 FETCHING ENVIRONMENT VARIABLES

⚡ USING NPH SCRIPTS

NPH (no-parsed-header) scripts send the complete HTTP header directly to the browser. CGI.pm supports NPH mode via:

Microsoft IIS requires NPH mode; CGI.pm detects it automatically.

🔄 SERVER PUSH

#!/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;
}

See also CGI::Push.

🛡️ AVOIDING DENIAL OF SERVICE ATTACKS

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".

🚩 MODULE FLAGS

🔄 COMPATIBILITY WITH CGI-LIB.PL

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};.

📜 LICENSE

Copyright 1995-2007, Lincoln D. Stein. Distributed under the Artistic License 2.0. Currently maintained by Lee Johnson (LEEJO) with help from many contributors.

🙏 CREDITS

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.

🐞 BUGS

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

📚 SEE ALSO


perl v5.34.0 2022-02-12 CGI(3pm)

CGI
📖 NAME 🚀 Quick Reference 📋 SYNOPSIS 📝 DESCRIPTION
⚠️ HTML Generation functions should no longer be used 🧑‍💻 Programming style
🌐 GENERATING DYNAMIC DOCUMENTS
📄 Creating a standard http header 🔀 Generating a redirection header 🔗 Creating a self-referencing url that preserves state 🌍 Obtaining the script's url 🔀 Mixing post and url parameters 📁 Processing a file upload field
🍪 HTTP COOKIES
Creating a cookie Retrieving a cookie
🐛 DEBUGGING 🌍 FETCHING ENVIRONMENT VARIABLES ⚡ USING NPH SCRIPTS 🔄 SERVER PUSH 🛡️ AVOIDING DENIAL OF SERVICE ATTACKS 🚩 MODULE FLAGS 🔄 COMPATIBILITY WITH CGI-LIB.PL 📜 LICENSE 🙏 CREDITS 🐞 BUGS 📚 SEE ALSO

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/)
Valid XHTML 1.0 Transitional!Valid CSS!