man > CGI

📛 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 parameter valuemy $value = $q->param('name');Single value (scalar)
🔍 Get multiple parameter valuesmy @values = $q->multi_param('name');Safe list context
📤 Generate HTTP headerprint $q->header('text/html');Content-Type header
🍪 Set cookiemy $c = $q->cookie(-name=>'n', -value=>'v');Create cookie object
📎 Redirect browserprint $q->redirect('http://example.com');HTTP 302 redirect
📁 Handle file uploadmy $fh = $q->upload('field');Get file handle
💾 Save state to file$q->save(\*FILE);Persist parameter state
🔗 Self-referencing URLmy $url = $q->self_url;Preserve current parameters
📊 Fetch environment variablemy $ua = $q->user_agent;HTTP_USER_AGENT
⚠️ Protect against DoS$CGI::POST_MAX = 10*1024*1024;Limit POST size

📝 SYNOPSIS

use strict;
use warnings;
use CGI;

my $q = CGI->new;
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');

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. Features include: form processing, file uploads, cookies, query string generation, and HTTP headers. Works with mod_perl, mod_perl2, and FastCGI.

⚠️ CGI.pm HAS BEEN REMOVED FROM THE PERL CORE

If you upgrade perl or rely on a system perl, you must install CGI.pm yourself via cpan/cpanm/vendor package. The CGI::Fast module has been split into its own distribution. See CGI::Alternatives for better alternatives.

🚫 HTML Generation functions should no longer be used

All HTML generation functions are deprecated. Use a template engine like Template::Toolkit for separation of concerns. See CGI::HTML::Functions for the deprecated documentation.

💻 Programming style

Two styles: object-oriented (OO) and function-oriented. OO recommended. Create CGI object, use methods. Function-oriented uses imported functions with a default internal object.

OO example:

use CGI;
my $q = CGI->new;
print $q->header;

Function-oriented example:

use CGI qw/:standard/;
print header();

📞 Calling CGI.pm routines

Most routines use named arguments with dashes. Case and order do not matter. Example:

print $q->header( -type => 'image/gif', -expires => '+3d' );

Some routines accept a single argument without a name (e.g. header('text/html')). Nonstandard HTTP headers can be added by providing unrecognized named arguments (e.g. -cost => 'Three smackers').

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

my $q = CGI->new;

Parses input from POST, GET, DELETE methods. Set CGI package variables before calling new. File upload handles reset to beginning.

📁 Creating a new query object from an input file

my $q = CGI->new($input_filehandle);

Accepts file handle, hash reference, query string, or existing CGI object. For function-oriented, use restore_parameters().

my $q = CGI->new({'dinosaur' => 'barney', 'song' => 'I love you'});
my $q = CGI->new('dinosaur=barney&color=purple');
my $empty = CGI->new("");

🔑 Fetching a list of keywords from the query

my @keywords = $q->keywords;

📋 Fetching the names of all parameters passed to your script

my @names = $q->multi_param;   # OR
my @names = $q->param;          # discouraged

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

my @values = $q->multi_param('foo');   # list
my $value = $q->param('foo');          # scalar (first value)

⚠️ Calling param() in list context can cause vulnerabilities. Use scalar or multi_param(). Unset parameters return undef (scalar) or empty list (list).

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

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

➕ 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 $R::foo, @R::foo, etc.

⚠️ Don't import into 'main' — security risk. Non-legal characters become underscores.

🗑️ Deleting a parameter completely

$q->delete('foo','bar','baz');
$q->delete_all();   # clears all parameters

📦 Handling non-urlencoded arguments

my $data = $q->param('POSTDATA');
my $data = $q->param('PUTDATA');
my $data = $q->param('PATCHDATA');

Also available via upload_hook and -putdata_upload option.

🛠️ Direct access to the parameter list

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

🏷️ Fetching the parameter list as a hash

my $params = $q->Vars;         # tied hash reference (scalar)
my %params = $q->Vars;         # ordinary hash (list)

Multivalued parameters packed with null character (\0).

💾 Saving the state of the script to a file

$q->save(\*FILEHANDLE);

Format: NAME=VALUE lines, URL-escaped. Multiple records separated by = on its own line.

⚠️ Retrieving CGI errors

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

🔧 Using the function-oriented interface

use CGI qw/ param header /;
print header('text/plain');
my $zipcode = param('zipcode');

Import sets: :cgi (all CGI handling), :all (all methods except :cgi-lib).

Pragmas

🌐 GENERATING DYNAMIC DOCUMENTS

📤 Creating a standard HTTP header

print $q->header;
print $q->header('image/gif');
print $q->header('text/html','204 No response');
print $q->header(
    -type       => 'image/gif',
    -nph        => 1,
    -status     => '402 Payment required',
    -expires    => '+3d',
    -cookie     => $cookie,
    -charset    => 'utf-8',
    -attachment => 'foo.gif',
    -Cost       => '$2.00'
);

Parameters: -type (default text/html), -status, -expires, -cookie, -nph, -charset (default ISO-8859-1), -attachment, -p3p. Any other parameters become custom headers.

Valid -expires formats: +30s, +10m, +1h, -1d, now, +3M, +10y, or absolute date.

🔀 Generating a redirection header

print $q->redirect('http://somewhere.else/in/movie/land');
print $q->redirect(
    -uri    => 'http://example.com',
    -nph    => 1,
    -status => '301 Moved Permanently'
);

Default status 302. Use full URLs.

🔗 Creating a self-referencing URL that preserves state

my $myself = $q->self_url;
print qq(I'm talking to myself.);
my $the_string = $q->query_string();

📍 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 $netloc        = url(-base => 1);

🔀 Mixing POST and URL parameters

my $color = url_param('color');

param() returns POST values; url_param() returns URL query parameters.

📁 Processing a file upload field

if (my $io_handle = $q->upload('field_name')) {
    open (my $out_file,'>>','output');
    while (my $bytesread = $io_handle->read($buffer,1024)) {
        print $out_file $buffer;
    }
}
my $filename = $q->param('field_name');           # original filename
my $type = $q->uploadInfo($io_handle)->{'Content-Type'};  # MIME type
my $tmpfilename = $q->tmpFileName($io_handle);    # temp file path

Upload hook for progress bars:

my $q = CGI->new(\&hook, $data, $use_tempfile);
sub hook {
    my ($filename, $buffer, $bytes_read, $data) = @_;
    print "Read $bytes_read bytes of $filename\n";
}

To disable temp files, set $use_tempfile to false.

🍪 HTTP COOKIES

my $cookie = $q->cookie(
    -name    => 'sessionID',
    -value   => 'xyzzy',
    -expires => '+1h',
    -path    => '/cgi-bin/database',
    -domain  => '.capricorn.org',
    -secure  => 1
);
print $q->header(-cookie => $cookie);

Retrieve:

my $riddle  = $q->cookie('riddle_name');
my %answers = $q->cookie('answers');
my @cookies = $q->cookie();    # all cookie names

Parameters: -name (required), -value, -path, -domain, -expires, -secure. Cookie and CGI namespaces are separate.

🐞 DEBUGGING

Run from command line with keywords or name=value pairs:

your_script.pl keyword1 keyword2 keyword3
your_script.pl name1=value1 name2=value2

Use -debug pragma for STDIN input. Use quotes and backslashes for special characters. Set path info with /your/path?name1=value1.

🌍 FETCHING ENVIRONMENT VARIABLES

🏷️ USING NPH SCRIPTS

NPH (no-parsed-header) scripts send complete HTTP header directly. Enable NPH via:

Microsoft IIS requires NPH mode; CGI.pm auto-detects IIS.

🔁 SERVER PUSH

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

Functions: multipart_init (boundary, charset), multipart_start (type, charset), multipart_end, multipart_final. See also CGI::Push.

🛡️ AVOIDING DENIAL OF SERVICE ATTACKS

$CGI::POST_MAX = 1024 * 1024 * 10;  # 10 MB max
$CGI::DISABLE_UPLOADS = 1;           # disable uploads

If POST exceeds limit, param() returns empty; cgi_error() returns "413 POST too large".

⚙️ MODULE FLAGS

🔗 COMPATIBILITY WITH CGI-LIB.PL

use CGI qw(:cgi-lib :standard);
&ReadParse;
print "The value of the antique is $in{antique}.\n";
print textfield(-name=>'price', -default=>'$1.99');

Functions: ReadParse(), PrintHeader(), SplitParam(), MethGet(), MethPost().

📜 LICENSE

Copyright 1995-2007, Lincoln D. Stein. Artistic License 2.0. Maintained by Lee Johnson (LEEJO).

🙏 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

Report issues at https://github.com/leejo/CGI.pm/issues. See CONTRIBUTING.md. Original bug tracker: RT.

📚 SEE ALSO

CGI::Carp, CGI::Fast.

CGI
📛 NAME 🚀 Quick Reference 📝 SYNOPSIS 📖 DESCRIPTION
⚠️ CGI.pm HAS BEEN REMOVED FROM THE PERL CORE 🚫 HTML Generation functions should no longer be used 💻 Programming style 📞 Calling CGI.pm routines 🆕 Creating a new query object (object-oriented style) 📁 Creating a new query object from an input file 🔑 Fetching a list of keywords from the query 📋 Fetching the names of all parameters passed to your script 🔍 Fetching the value(s) of a single named parameter ✏️ Setting the value(s) of a named parameter ➕ Appending additional values to a named parameter 📥 Importing all parameters into a namespace 🗑️ Deleting a parameter completely 📦 Handling non-urlencoded arguments 🛠️ Direct access to the parameter list 🏷️ Fetching the parameter list as a hash 💾 Saving the state of the script to a file ⚠️ Retrieving CGI errors 🔧 Using the function-oriented interface
🌐 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 🐞 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.22-1-g1b0fcb4 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-05 06:29 @216.73.216.52
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-pro / taotoken.net / www.chedong.com - original format

^_top_^