📖 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 parameter value | my $value = $q->param('name'); | Single value (scalar) |
| 🔍 Get multiple parameter values | my @values = $q->multi_param('name'); | Safe list context |
| 📤 Generate HTTP header | print $q->header('text/html'); | Content-Type header |
| 🍪 Set cookie | my $c = $q->cookie(-name=>'n', -value=>'v'); | Create cookie object |
| 📎 Redirect browser | print $q->redirect('http://example.com'); | HTTP 302 redirect |
| 📁 Handle file upload | my $fh = $q->upload('field'); | Get file handle |
| 💾 Save state to file | $q->save(\*FILE); | Persist parameter state |
| 🔗 Self-referencing URL | my $url = $q->self_url; | Preserve current parameters |
| 📊 Fetch environment variable | my $ua = $q->user_agent; | HTTP_USER_AGENT |
| ⚠️ Protect against DoS | $CGI::POST_MAX = 10*1024*1024; | Limit POST size |
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');
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.
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.
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.
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();
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').
my $q = CGI->new;
Parses input from POST, GET, DELETE methods. Set CGI package variables before calling new. File upload handles reset to beginning.
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("");
my @keywords = $q->keywords;
my @names = $q->multi_param; # OR
my @names = $q->param; # discouraged
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).
$q->param('foo','an','array','of','values');
$q->param( -name => 'foo', -value => 'the value' );
$q->append( -name =>'foo', -values =>['yet','more','values'] );
$q->import_names('R'); # Creates $R::foo, @R::foo, etc.
⚠️ Don't import into 'main' — security risk. Non-legal characters become underscores.
$q->delete('foo','bar','baz');
$q->delete_all(); # clears all parameters
my $data = $q->param('POSTDATA');
my $data = $q->param('PUTDATA');
my $data = $q->param('PATCHDATA');
Also available via upload_hook and -putdata_upload option.
$q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
my $params = $q->Vars; # tied hash reference (scalar)
my %params = $q->Vars; # ordinary hash (list)
Multivalued parameters packed with null character (\0).
$q->save(\*FILEHANDLE);
Format: NAME=VALUE lines, URL-escaped. Multiple records separated by = on its own line.
if (my $error = $q->cgi_error) {
print $q->header(-status => $error);
print "Error: $error";
}
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).
-no_undef_params – exclude undef params-utf8 – treat all parameters as UTF-8 text strings-putdata_upload / -postdata_upload / -patchdata_upload – treat PUTDATA etc. as file uploads-nph – produce NPH headers-newstyle_urls – use semicolons in query strings (default)-oldstyle_urls – use ampersands-no_debug – disable command-line processing-debug – enable full debuggingprint $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.
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.
my $myself = $q->self_url;
print qq(I'm talking to myself.);
my $the_string = $q->query_string();
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);
my $color = url_param('color');
param() returns POST values; url_param() returns URL query parameters.
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.
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.
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.
Accept() – MIME types accepted by browser; optional argument returns preference floatraw_cookie() – returns HTTP_COOKIE raw stringenv_query_string() – original QUERY_STRING from environmentuser_agent() – HTTP_USER_AGENT; optional pattern matchpath_info() – additional path after script namepath_translated() – physical path equivalentremote_host() – remote host name or IPremote_ident() – identd usernameremote_addr() – remote IP (default 127.0.0.1)request_uri() – interpreted pathnamescript_name() – partial URL for self-referencereferer() – previous URLauth_type() – authorization methodserver_name() – host namevirtual_host() – host from browserserver_port() – listening portserver_protocol() – protocol/revisionvirtual_port() – virtual host portserver_software() – server softwareremote_user() – authorization nameuser_name() – remote user (attempted)request_method() – POST/GET/HEADcontent_type() – POST content typehttp() – any HTTP header (e.g. http('Accept-language'))https() – HTTPS environment variablesNPH (no-parsed-header) scripts send complete HTTP header directly. Enable NPH via:
use CGI qw(:standard -nph);CGI->nph(1);print header(-nph=>1);Microsoft IIS requires NPH mode; CGI.pm auto-detects IIS.
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.
$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".
param() includes query string valuescookie() calluse 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().
Copyright 1995-2007, Lincoln D. Stein. Artistic License 2.0. Maintained by Lee Johnson (LEEJO).
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.
Report issues at https://github.com/leejo/CGI.pm/issues. See CONTRIBUTING.md. Original bug tracker: RT.
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)
Enhanced by LLM: deepseek-v4-pro / taotoken.net / www.chedong.com - original format