/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
NNNNAAAAMMMMEEEE
CGI - Simple Common Gateway Interface Class
SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
use CGI;
# the rest is too complicated for a synopsis; keep reading
AAAABBBBSSSSTTTTRRRRAAAACCCCTTTT
This perl library uses perl5 objects to make it easy to
create Web fill-out forms and parse their contents. This
package defines CGI objects, entities that contain the
values of the current query string and other state
variables. Using a CGI object's methods, you can examine
keywords and parameters passed to your script, and create
forms whose initial values are taken from the current query
(thereby preserving state information).
The current version of CGI.pm is available at
http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
IIIINNNNSSSSTTTTAAAALLLLLLLLAAAATTTTIIIIOOOONNNN::::
To install this package, just change to the directory in
which this file is found and type the following:
perl Makefile.PL
make
make install
This will copy CGI.pm to your perl library directory for use
by all perl scripts. You probably must be root to do this.
Now you can load the CGI routines in your Perl scripts with
the line:
use CGI;
If you don't have sufficient privileges to install CGI.pm in
the Perl library directory, you can put CGI.pm into some
convenient spot, such as your home directory, or in cgi-bin
itself and prefix all Perl scripts that call it with
something along the lines of the following preamble:
use lib '/home/davis/lib';
use CGI;
If you are using a version of perl earlier than 5.002 (such
as NT perl), use this instead:
12/May/97 Last change: perl 5.003 with 1
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
BEGIN {
unshift(@INC,'/home/davis/lib');
}
use CGI;
The CGI distribution also comes with a cute module called
the _C_G_I::_C_a_r_p manpage. It redefines the _d_i_e(), _w_a_r_n(),
_c_o_n_f_e_s_s() and _c_r_o_a_k() error routines so that they write
nicely formatted error messages into the server's error log
(or to the output stream of your choice). This avoids long
hours of groping through the error and access logs, trying
to figure out which CGI script is generating error
messages. If you choose, you can even have fatal error
messages echoed to the browser to avoid the annoying and
uninformative "Server Error" message.
DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
CCCCRRRREEEEAAAATTTTIIIINNNNGGGG AAAA NNNNEEEEWWWW QQQQUUUUEEEERRRRYYYY OOOOBBBBJJJJEEEECCCCTTTT::::
$query = new CGI;
This will parse the input (from both POST and GET methods)
and store it into a perl5 object called $query.
CCCCRRRREEEEAAAATTTTIIIINNNNGGGG AAAA NNNNEEEEWWWW QQQQUUUUEEEERRRRYYYY OOOOBBBBJJJJEEEECCCCTTTT FFFFRRRROOOOMMMM AAAANNNN IIIINNNNPPPPUUUUTTTT FFFFIIIILLLLEEEE
$query = new CGI(INPUTFILE);
If you provide a file handle to the _n_e_w() method, it will
read parameters from the file (or STDIN, or whatever). The
file can be in any of the forms describing below under
debugging (i.e. a series of newline delimited TAG=VALUE
pairs will work). Conveniently, this type of file is
created by the _s_a_v_e() method (see below). Multiple records
can be saved and restored.
Perl purists will be pleased to know that this syntax
accepts references to file handles, or even references to
filehandle globs, which is the "official" way to pass a
filehandle:
$query = new CGI(\*STDIN);
You can also initialize the query object from an associative
array reference:
$query = new CGI( {'dinosaur'=>'barney',
'song'=>'I love you',
'friends'=>[qw/Jessica George Nancy/]}
);
or from a properly formatted, URL-escaped query string:
12/May/97 Last change: perl 5.003 with 2
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
$query = new CGI('dinosaur=barney&color=purple');
To create an empty query, initialize it from an empty string
or hash:
$empty_query = new CGI("");
-or-
$empty_query = new CGI({});
FFFFEEEETTTTCCCCHHHHIIIINNNNGGGG AAAA LLLLIIIISSSSTTTT OOOOFFFF KKKKEEEEYYYYWWWWOOOORRRRDDDDSSSS FFFFRRRROOOOMMMM TTTTHHHHEEEE QQQQUUUUEEEERRRRYYYY::::
@keywords = $query->keywords
If the script was invoked as the result of an
search, the parsed keywords can be obtained as an array
using the _k_e_y_w_o_r_d_s() method.
FFFFEEEETTTTCCCCHHHHIIIINNNNGGGG TTTTHHHHEEEE NNNNAAAAMMMMEEEESSSS OOOOFFFF AAAALLLLLLLL TTTTHHHHEEEE PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRRSSSS PPPPAAAASSSSSSSSEEEEDDDD TTTTOOOO YYYYOOOOUUUURRRR
SSSSCCCCRRRRIIIIPPPPTTTT::::
@names = $query->param
If the script was invoked with a parameter list (e.g.
"name1=value1&name2=value2&name3=value3"), the _p_a_r_a_m()
method will return the parameter names as a list. If the
script was invoked as an script, there will be a
single parameter named 'keywords'.
NOTE: As of version 1.5, the array of parameter names
returned will be in the same order as they were submitted by
the browser. Usually this order is the same as the order in
which the parameters are defined in the form (however, this
isn't part of the spec, and so isn't guaranteed).
FFFFEEEETTTTCCCCHHHHIIIINNNNGGGG TTTTHHHHEEEE VVVVAAAALLLLUUUUEEEE OOOORRRR VVVVAAAALLLLUUUUEEEESSSS OOOOFFFF AAAA SSSSIIIINNNNGGGGLLLLEEEE NNNNAAAAMMMMEEEEDDDD PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRR::::
@values = $query->param('foo');
-or-
$value = $query->param('foo');
Pass the _p_a_r_a_m() method a single argument to fetch the value
of the named parameter. If the parameter is multivalued
(e.g. from multiple selections in a scrolling list), you can
ask to receive an array. Otherwise the method will return a
single value.
12/May/97 Last change: perl 5.003 with 3
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
SSSSEEEETTTTTTTTIIIINNNNGGGG TTTTHHHHEEEE _V_A_L_U_E(S) OF A NAMED PARAMETER:
$query->param('foo','an','array','of','values');
This sets the value for the named parameter 'foo' to an
array of values. This is one way to change the value of a
field AFTER the script has been invoked once before.
(Another way is with the -override parameter accepted by all
methods that generate form elements.)
_p_a_r_a_m() also recognizes a named parameter style of calling
described in more detail later:
$query->param(-name=>'foo',-values=>['an','array','of','values']);
-or-
$query->param(-name=>'foo',-value=>'the value');
AAAAPPPPPPPPEEEENNNNDDDDIIIINNNNGGGG AAAADDDDDDDDIIIITTTTIIIIOOOONNNNAAAALLLL VVVVAAAALLLLUUUUEEEESSSS TTTTOOOO AAAA NNNNAAAAMMMMEEEEDDDD PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRR::::
$query->append(-name=>;'foo',-values=>['yet','more','values']);
This adds a value or list of values to the named parameter.
The values are appended to the end of the parameter if it
already exists. Otherwise the parameter is created. Note
that this method only recognizes the named argument calling
syntax.
IIIIMMMMPPPPOOOORRRRTTTTIIIINNNNGGGG AAAALLLLLLLL PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRRSSSS IIIINNNNTTTTOOOO AAAA NNNNAAAAMMMMEEEESSSSPPPPAAAACCCCEEEE::::
$query->import_names('R');
This creates a series of variables in the 'R' namespace.
For example, $R::foo, @R:foo. For keyword lists, a variable
@R::keywords will appear. If no namespace is given, this
method will assume 'Q'. WARNING: don't import anything
into 'main'; this is a major security risk!!!!
In older versions, this method was called iiiimmmmppppoooorrrrtttt(((()))). As of
version 2.20, this name has been removed completely to avoid
conflict with the built-in Perl module iiiimmmmppppoooorrrrtttt operator.
DDDDEEEELLLLEEEETTTTIIIINNNNGGGG AAAA PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRR CCCCOOOOMMMMPPPPLLLLEEEETTTTEEEELLLLYYYY::::
$query->delete('foo');
This completely clears a parameter. It sometimes useful for
resetting parameters that you don't want passed down between
script invocations.
12/May/97 Last change: perl 5.003 with 4
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
DDDDEEEELLLLEEEETTTTIIIINNNNGGGG AAAALLLLLLLL PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRRSSSS::::
$query->_d_e_l_e_t_e__a_l_l();
This clears the CGI object completely. It might be useful
to ensure that all the defaults are taken when you create a
fill-out form.
SSSSAAAAVVVVIIIINNNNGGGG TTTTHHHHEEEE SSSSTTTTAAAATTTTEEEE OOOOFFFF TTTTHHHHEEEE FFFFOOOORRRRMMMM TTTTOOOO AAAA FFFFIIIILLLLEEEE::::
$query->save(FILEHANDLE)
This will write the current state of the form to the
provided filehandle. You can read it back in by providing a
filehandle to the _n_e_w() method. Note that the filehandle
can be a file, a pipe, or whatever!
The format of the saved file is:
NAME1=VALUE1
NAME1=VALUE1'
NAME2=VALUE2
NAME3=VALUE3
=
Both name and value are URL escaped. Multi-valued CGI
parameters are represented as repeated names. A session
record is delimited by a single = symbol. You can write out
multiple records and read them back in with several calls to
nnnneeeewwww. You can do this across several sessions by opening the
file in append mode, allowing you to create primitive guest
books, or to keep a history of users' queries. Here's a
short example of creating multiple session records:
use CGI;
open (OUT,">>test.out") || die;
$records = 5;
foreach (0..$records) {
my $q = new CGI;
$q->param(-name=>'counter',-value=>$_);
$q->save(OUT);
}
close OUT;
# reopen for reading
open (IN,"test.out") || die;
while (!eof(IN)) {
my $q = new CGI(IN);
print $q->param('counter'),"\n";
}
12/May/97 Last change: perl 5.003 with 5
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
The file format used for save/restore is identical to that
used by the Whitehead Genome Center's data exchange format
"Boulderio", and can be manipulated and even databased using
Boulderio utilities. See
http://www.genome.wi.mit.edu/genome_software/other/boulder.html
for further details.
CCCCRRRREEEEAAAATTTTIIIINNNNGGGG AAAA SSSSEEEELLLLFFFF----RRRREEEEFFFFEEEERRRREEEENNNNCCCCIIIINNNNGGGG UUUURRRRLLLL TTTTHHHHAAAATTTT PPPPRRRREEEESSSSEEEERRRRVVVVEEEESSSS SSSSTTTTAAAATTTTEEEE
IIIINNNNFFFFOOOORRRRMMMMAAAATTTTIIIIOOOONNNN::::
$myself = $query->self_url;
print "I'm talking to myself.";
_s_e_l_f__u_r_l() will return a URL, that, when selected, will
reinvoke this script with all its state information intact.
This is most useful when you want to jump around within the
document using internal anchors but you don't want to
disrupt the current contents of the _f_o_r_m(s). Something like
this will do the trick.
$myself = $query->self_url;
print "See table 1";
print "See table 2";
print "See for yourself";
If you don't want to get the whole query string, call the
method _u_r_l() to return just the URL for the script:
$myself = $query->url;
print "No query string in this baby!\n";
You can also retrieve the unprocessed query string with
_q_u_e_r_y__s_t_r_i_n_g():
$the_string = $query->query_string;
CCCCOOOOMMMMPPPPAAAATTTTIIIIBBBBIIIILLLLIIIITTTTYYYY WWWWIIIITTTTHHHH CCCCGGGGIIII----LLLLIIIIBBBB....PPPPLLLL
To make it easier to port existing programs that use cgi-
lib.pl the compatibility routine "ReadParse" is provided.
Porting is simple:
OLD VERSION
require "cgi-lib.pl";
&ReadParse;
print "The value of the antique is $in{antique}.\n";
NEW VERSION
use CGI;
CGI::ReadParse
12/May/97 Last change: perl 5.003 with 6
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
print "The value of the antique is $in{antique}.\n";
CGI.pm's _R_e_a_d_P_a_r_s_e() routine creates a tied variable named
%in, which can be accessed to obtain the query variables.
Like ReadParse, you can also provide your own variable.
Infrequently used features of ReadParse, such as the
creation of @in and $in variables, are not supported.
Once you use ReadParse, you can retrieve the query object
itself this way:
$q = $in{CGI};
print $q->textfield(-name=>'wow',
-value=>'does this really work?');
This allows you to start using the more interesting features
of CGI.pm without rewriting your old scripts from scratch.
CCCCAAAALLLLLLLLIIIINNNNGGGG CCCCGGGGIIII FFFFUUUUNNNNCCCCTTTTIIIIOOOONNNNSSSS TTTTHHHHAAAATTTT TTTTAAAAKKKKEEEE MMMMUUUULLLLTTTTIIIIPPPPLLLLEEEE AAAARRRRGGGGUUUUMMMMEEEENNNNTTTTSSSS
In versions of CGI.pm prior to 2.0, it could get difficult
to remember the proper order of arguments in CGI function
calls that accepted five or six different arguments. As of
2.0, there's a better way to pass arguments to the various
CGI functions. In this style, you pass a series of
name=>argument pairs, like this:
$field = $query->radio_group(-name=>'OS',
-values=>[Unix,Windows,Macintosh],
-default=>'Unix');
The advantages of this style are that you don't have to
remember the exact order of the arguments, and if you leave
out a parameter, in most cases it will default to some
reasonable value. If you provide a parameter that the
method doesn't recognize, it will usually do something
useful with it, such as incorporating it into the HTML form
tag. For example if Netscape decides next week to add a new
JUSTIFICATION parameter to the text field tags, you can
start using the feature without waiting for a new version of
CGI.pm:
$field = $query->textfield(-name=>'State',
-default=>'gaseous',
-justification=>'RIGHT');
This will result in an HTML tag that looks like this:
Parameter names are case insensitive: you can use -name, or
12/May/97 Last change: perl 5.003 with 7
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
-Name or -NAME. You don't have to use the hyphen if you
don't want to. After creating a CGI object, call the
uuuusssseeee____nnnnaaaammmmeeeedddd____ppppaaaarrrraaaammmmeeeetttteeeerrrrssss(((()))) method with a nonzero value. This
will tell CGI.pm that you intend to use named parameters
exclusively:
$query = new CGI;
$query->use_named_parameters(1);
$field = $query->radio_group('name'=>'OS',
'values'=>['Unix','Windows','Macintosh'],
'default'=>'Unix');
Actually, CGI.pm only looks for a hyphen in the first
parameter. So you can leave it off subsequent parameters if
you like. Something to be wary of is the potential that a
string constant like "values" will collide with a keyword
(and in fact it does!) While Perl usually figures out when
you're referring to a function and when you're referring to
a string, you probably should put quotation marks around all
string constants just to play it safe.
CCCCRRRREEEEAAAATTTTIIIINNNNGGGG TTTTHHHHEEEE HHHHTTTTTTTTPPPP HHHHEEEEAAAADDDDEEEERRRR::::
print $query->header;
-or-
print $query->header('image/gif');
-or-
print $query->header('text/html','204 No response');
-or-
print $query->header(-type=>'image/gif',
-nph=>1,
-status=>'402 Payment required',
-expires=>'+3d',
-cookie=>$cookie,
-Cost=>'$2.00');
_h_e_a_d_e_r() returns the Content-type: header. You can provide
your own MIME type if you choose, otherwise it defaults to
text/html. An optional second parameter specifies the
status code and a human-readable message. For example, you
can specify 204, "No response" to create a script that tells
the browser to do nothing at all. If you want to add
additional fields to the header, just tack them on to the
end:
12/May/97 Last change: perl 5.003 with 8
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
print $query->header('text/html','200 OK','Content-Length: 3002');
The last example shows the named argument style for passing
arguments to the CGI methods using named parameters.
Recognized parameters are ----ttttyyyyppppeeee, ----ssssttttaaaattttuuuussss, ----eeeexxxxppppiiiirrrreeeessss, and ----
ccccooooooookkkkiiiieeee. Any other parameters will be stripped of their
initial hyphens and turned into header fields, allowing you
to specify any HTTP header you desire.
Most browsers will not cache the output from CGI scripts.
Every time the browser reloads the page, the script is
invoked anew. You can change this behavior with the ----
eeeexxxxppppiiiirrrreeeessss parameter. When you specify an absolute or relative
expiration interval with this parameter, some browsers and
proxy servers will cache the script's output until the
indicated expiration date. The following forms are all
valid for the -expires field:
+30s 30 seconds from now
+10m ten minutes from now
+1h one hour from now
-1d yesterday (i.e. "ASAP!")
now immediately
+3M in three months
+10y in ten years time
Thursday, 25-Apr-96 00:40:33 GMT at the indicated time & date
(_C_G_I::_e_x_p_i_r_e_s() is the static function call used internally
that turns relative time intervals into HTTP dates. You can
call it directly if you wish.)
The ----ccccooooooookkkkiiiieeee parameter generates a header that tells the
browser to provide a "magic cookie" during all subsequent
transactions with your script. Netscape cookies have a
special format that includes interesting attributes such as
expiration time. Use the _c_o_o_k_i_e() method to create and
retrieve session cookies.
The ----nnnnpppphhhh parameter, if set to a true value, will issue the
correct headers to work with a NPH (no-parse-header) script.
This is important to use with certain servers, such as
Microsoft Internet Explorer, which expect all their scripts
to be NPH.
GGGGEEEENNNNEEEERRRRAAAATTTTIIIINNNNGGGG AAAA RRRREEEEDDDDIIIIRRRREEEECCCCTTTTIIIIOOOONNNN IIIINNNNSSSSTTTTRRRRUUUUCCCCTTTTIIIIOOOONNNN
print $query->redirect('http://somewhere.else/in/movie/land');
redirects the browser elsewhere. If you use redirection
like this, you should nnnnooootttt print out a header as well. As of
version 2.0, we produce both the unofficial Location: header
and the official URI: header. This should satisfy most
12/May/97 Last change: perl 5.003 with 9
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
servers and browsers.
One hint I can offer is that relative links may not work
correctly when you generate a redirection to another
document on your site. This is due to a well-intentioned
optimization that some servers use. The solution to this is
to use the full URL (including the http: part) of the
document you are redirecting to.
You can use named parameters:
print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
-nph=>1);
The ----nnnnpppphhhh parameter, if set to a true value, will issue the
correct headers to work with a NPH (no-parse-header) script.
This is important to use with certain servers, such as
Microsoft Internet Explorer, which expect all their scripts
to be NPH.
CCCCRRRREEEEAAAATTTTIIIINNNNGGGG TTTTHHHHEEEE HHHHTTTTMMMMLLLL HHHHEEEEAAAADDDDEEEERRRR::::
print $query->start_html(-title=>'Secrets of the Pyramids',
-author=>'fred@capricorn.org',
-base=>'true',
-target=>'_blank',
-meta=>{'keywords'=>'pharaoh secret mummy',
'copyright'=>'copyright 1996 King Tut'},
-BGCOLOR=>'blue');
-or-
print $query->start_html('Secrets of the Pyramids',
'fred@capricorn.org','true',
'BGCOLOR="blue"');
This will return a canned HTML header and the opening
tag. All parameters are optional. In the named parameter
form, recognized parameters are -title, -author, -base, -
xbase and -target (see below for the explanation). Any
additional parameters you provide, such as the Netscape
unofficial BGCOLOR attribute, are added to the tag.
The argument ----xxxxbbbbaaaasssseeee allows you to provide an HREF for the
tag different from the current location, as in
-xbase=>"http://home.mcom.com/"
All relative links will be interpreted relative to this tag.
The argument ----ttttaaaarrrrggggeeeetttt allows you to provide a default target
frame for all the links and fill-out forms on the page. See
12/May/97 Last change: perl 5.003 with 10
/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)User Contributed Perl Documentation/USR/LOCAL/LIB/PERL5/SITE_PERL/CGI(1)
the Netscape documentation on frames for details of how to
manipulate this.
-target=>"answer_window"
All relative links will be interpreted relative to this tag.
You add arbitrary meta information to the header with the ----
mmmmeeeettttaaaa argument. This argument expects a reference to an
associative array containing name/value pairs of meta
information. These will be turned into a series of header
tags that look something like this:
There is no support for the HTTP-EQUIV type of tag.
This is because you can modify the HTTP header directly with
the hhhheeeeaaaaddddeeeerrrr(((()))) method.
JAVASCRIPTING: The ----ssssccccrrrriiiipppptttt, ----nnnnooooSSSSccccrrrriiiipppptttt, ----oooonnnnLLLLooooaaaadddd and ----oooonnnnUUUUnnnnllllooooaaaadddd
parameters are used to add Netscape JavaScript calls to your
pages. ----ssssccccrrrriiiipppptttt should point to a block of text containing
JavaScript function definitions. This block will be placed
within a