A CGI.pm modul
A CGI.pm Perl modult Lincoln D. Stein készítette, és gyakorlatilag azt lehet mondani,
hogy amit egy Perl program CGI-vel és HTML-lel kezdeni tud, azt tudja a CGI.pm.
Ha valaki CGI programokat akar írni Perl-ben, és nem akar maga szenvedni a cgi paraméterek,
sütik, egyebek kezelésével, vagy akár a HTML kimenet pontos szintaktikájával, akkor használja a
CGI.pm modult.
címről tölthető le. És nagyon sokat lehet belőle Perl programozást is tanulni.
Ez a Perl könyvtár Perl5 objektumokat használ Web formok létrehozásához,
illetve
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/
=head1 INSTALLATION:
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:
BEGIN
use CGI;
The CGI distribution also comes with a cute module called L.
It redefines the die(), warn(), confess() and croak() 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.
=head1 DESCRIPTION
=head2 CREATING A NEW QUERY OBJECT:
$query = new CGI;
This will parse the input (from both POST and GET methods) and store
it into a perl5 object called $query.
=head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
$query = new CGI(INPUTFILE);
If you provide a file handle to the new() 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 save() 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(
);
or from a properly formatted, URL-escaped query string:
$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();
=head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
@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 keywords() method.
=head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
@names = $query->param
If the script was invoked with a parameter list
(e.g. "name1=value1&name2=value2&name3=value3"), the param()
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).
=head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
@values = $query->param('foo');
-or-
$value = $query->param('foo');
Pass the param() 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.
=head2 SETTING THE VALUE(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.)
param() 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');
=head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
$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.
=head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
$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 B. As of version 2.20,
this name has been removed completely to avoid conflict with the built-in
Perl module B operator.
=head2 DELETING A PARAMETER COMPLETELY:
$query->delete('foo');
This completely clears a parameter. It sometimes useful for
resetting parameters that you don't want passed down between
script invocations.
=head2 DELETING ALL PARAMETERS:
$query->delete_all();
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.
=head2 SAVING THE STATE OF THE FORM TO A FILE:
$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 new() 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 B. 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)
close OUT;
# reopen for reading
open (IN,"test.out") || die;
while (!eof(IN))
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.
=head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
$myself = $query->self_url;
print "I'm talking to myself.";
self_url() 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 form(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 url() 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 query_string():
$the_string = $query->query_string;
=head2 COMPATIBILITY WITH CGI-LIB.PL
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.\n";
NEW VERSION
use CGI;
CGI::ReadParse
print "The value of the antique is $in.\n";
CGI.pm's ReadParse() 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;
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.
=head2 CALLING CGI FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
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 -Name or
-NAME. You don't have to use the hyphen if you don't want to. After
creating a CGI object, call the B 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.
=head2 CREATING THE HTTP HEADER:
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');
header() 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:
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
B<-type>, B<-status>, B<-expires>, and B<-cookie>. 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 B<-expires> 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
(CGI::expires() is the static function call used internally that turns
relative time intervals into HTTP dates. You can call it directly if
you wish.)
The B<-cookie> 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 cookie() method to create and retrieve
session cookies.
The B<-nph> 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.
=head2 GENERATING A REDIRECTION INSTRUCTION
print $query->redirect('http://somewhere.else/in/movie/land');
redirects the browser elsewhere. If you use redirection like this,
you should B 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 servers and browsers.
One hint I can offer is that relative links may not work correctly
when 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 B<-nph> 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.
=head2 CREATING THE HTML HEADER:
print $query->start_html(-title=>'Secrets of the Pyramids',
-author=>'fred@capricorn.org',
-base=>'true',
-meta=>,
-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 and -base (see below for the
explanation). Any additional parameters you provide, such as the
Netscape unofficial BGCOLOR attribute, are added to the tag.
The argument B<-xbase> 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.
You add arbitrary meta information to the header with the B<-meta>
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 B
method.
JAVASCRIPTING: The B<-script>, B<-onLoad> and B<-onUnload> parameters
are used to add Netscape JavaScript calls to your pages. B<-script>
should point to a block of text containing JavaScript function
definitions. This block will be placed within a