[logo] CGI.pm - a Perl5 CGI Library

Version 2.70, 8/4/2000, L. Stein

This has been severely hacked from L Stein's CGI.pm documentation at http://stein.cshl.org/WWW/software/CGI/

Abstract

This perl 5 library uses objects to create Web fill-out forms on the fly and to parse their contents. It provides a simple interface for parsing and interpreting query strings passed to CGI scripts. However, it also offers a rich set of functions for creating fill-out forms. Instead of remembering the syntax for HTML form elements, you just make a series of perl function calls. An important fringe benefit of this is that the value of the previous query is used to initialize the form, so that the state of the form is preserved from invocation to invocation.

Everything is done through a ``CGI'' object. When you create one of these objects it examines the environment for a query string, parses it, and stores the results. You can then ask the CGI object to return or modify the query values. CGI objects handle POST and GET methods correctly, and correctly distinguish between scripts called from <ISINDEX> documents and form-based documents. In fact you can debug your script from the command line without worrying about setting up environment variables.

Function-Oriented vs Object-Oriented Use

CGI.pm can be used in two distinct modes called function-oriented and object-oriented. In the function-oriented mode, you first import CGI functions into your script's namespace, then call these functions directly. A simple function-oriented script looks like this:
#!/usr/local/bin/perl
use CGI qw/:standard/;
print header(),
      start_html(-title=>'Wow!'),
      h1('Wow!'),
      'Look Ma, no hands!',
      end_html();
The use operator loads the CGI.pm definitions and imports the ":standard" set of function definitions. We then make calls to various functions such as header(), to generate the HTTP header, start_html(), to produce the top part of an HTML document, h1() to produce a level one header, and so forth.

In the object-oriented mode, you use CGI; without specifying any functions or function sets to import. In this case, you communicate with CGI.pm via a CGI object. The object is created by a call to CGI::new() and encapsulates all the state information about the current CGI transaction, such as values of the CGI parameters passed to your script. Although more verbose, this coding style has the advantage of allowing you to create multiple CGI objects, save their state to disk or to a database, and otherwise manipulate them to achieve neat effects.

The same script written using the object-oriented style looks like this:

#!/usr/local/bin/perl
use CGI;
$q = new CGI;
print $q->header(),
      $q->start_html(-title=>'Wow!'),
      $q->h1('Wow!'),
      'Look Ma, no hands!',
      $q->end_html();
The object-oriented mode also has the advantage of consuming somewhat less memory than the function-oriented coding style. This may be of value to users of persistent Perl interpreters such as mod_perl.

Creating a new CGI object

The most basic use of CGI.pm is to get at the query parameters submitted to your script. To create a new CGI object that contains the parameters passed to your script, put the following at the top of your perl CGI programs:
    use CGI;
    $query = new CGI;

Fetching A List Of Keywords From The Query

    @keywords = $query->keywords

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.

Fetching The Value(s) Of A 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.

If a value is not given in the query string, as in the queries "name1=&name2=" or "name1&name2", it will be returned as an empty string (not undef).


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');
Parameter names are case insensitive: you can use -name, or -Name or -NAME.

Creating the HTTP Header

Creating the Standard Header for a Virtual Document

   print $query->header('image/gif');
This prints out the required HTTP Content-type: header and the requisite blank line beneath it. If no parameter is specified, it will default to 'text/html'.

An extended form of this method allows you to specify a status code and a message to pass back to the browser:

   print $query->header(-type=>'image/gif',
                        -status=>'204 No Response');
This presents the browser with a status code of 204 (No response). Properly-behaved browsers will take no action, simply remaining on the current page. (This is appropriate for a script that does some processing but doesn't need to display any results, or for a script called when a user clicks on an empty part of a clickable image map.)

Several other named parameters are recognized. Here's a contrived example that uses them all:

   print $query->header(-type=>'image/gif',
                        -status=>'402 Payment Required',
                        -expires=>'+3d',
                        -cookie=>$my_cookie,
                        -charset=>'UTF-7',
                        -attachment=>'foo.gif',
                        -Cost=>'$0.02');

HTML Shortcuts

Creating an HTML Header

   named parameter style
   print $query->start_html(-title=>'Secrets of the Pyramids',
                            -author=>'fred@capricorn.org',
                            -base=>'true',
			    -meta=>{'keywords'=>'pharoah secret mummy',
                                    'copyright'=>'copyright 1996 King Tut'},
			    -style=>{'src'=>'/styles/style1.css'},
                            -dtd=>1,
                            -BGCOLOR=>'blue');


Ending an HTML Document

  print $query->end_html
This ends an HTML document by printing the </BODY> </HTML> tags.

Other HTML Tags

CGI.pm provides shortcut methods for many other HTML tags. All HTML2 tags and the Netscape extensions are supported, as well as the HTML3 tags that are in common usage (including tables). Unpaired tags, paired tags, and tags that contain attributes are all supported using a simple syntax.

To see the list of HTML tags that are supported, open up the CGI.pm file and look at the functions defined in the %EXPORT_TAGS array.

Debugging

If you are running the script from the command line or in the perl debugger, you can pass the script a list of keywords or parameter=value pairs on the command line or from standard input (you don't have to worry about tricking your script into reading from environment variables). You can pass keywords like this:
   my_script.pl keyword1 keyword2 keyword3
or this:
   my_script.pl keyword1+keyword2+keyword3
or this:
   my_script.pl name1=value1 name2=value2
or this:
   my_script.pl name1=value1&name2=value2
If you pass the -debug pragma to CGI.pm, you can send CGI name-value pairs as newline-delimited parameters on standard input:
   % my_script.pl
   first_name=fred
   last_name=flintstone
   occupation='granite miner'
   ^D

HTTP Session Variables

Some of the more useful environment variables can be fetched through this interface. The methods include:
Accept()
auth_type()
raw_cookie()
path_info()
Table of contents

HTTP Cookies

Netscape browsers versions 1.1 and higher, and all versions of Internet Explorer support a so-called "cookie" designed to help maintain state within a browser session. CGI.pm has several methods that support cookies.

The interface to HTTP cookies is the cookie() method:

    $cookie = $query->cookie(-name=>'sessionID',
			     -value=>'xyzzy',
			     -expires=>'+1h',
			     -path=>'/cgi-bin/database',
			     -domain=>'.capricorn.org',
			     -secure=>1);
    print $query->header(-cookie=>$cookie);
The cookie created by cookie() must be incorporated into the HTTP header within the string returned by the header() method:
	print $query->header(-cookie=>$my_cookie);
To retrieve a cookie, request it by name by calling cookie() method without the -value parameter:
	use CGI;
	$query = new CGI;
	%answers = $query->cookie('answers');
	# $query->cookie(-name=>'answers') works too!
To retrieve the names of all cookies passed to your script, call cookie() without any parameters. This allows you to iterate through all cookies:
	foreach $name ($query->cookie()) {
            print $query->cookie($name);
        }