Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Dolce Sunglasses amp;Gabbana Sunglasses amp;Gabbana Dolce Dolce gxd4OFwqFZ

Perl 5 version 20.1 documentation

CGI - Handle Common Gateway Interface requests and responses

       
  1. use CGI;
  2. my $q = CGI->new;
  3. # Process an HTTP request
  4. @values = $q->param('form_field');
  5. $fh = $q->upload('file_field');
  6. $riddle = $querySunglasses Dolce amp;Gabbana amp;Gabbana Dolce Dolce Sunglasses ->cookie('riddle_name');
  7. %answers = $query->cookie('answers');
  8. # Prepare various HTTP responses
  9. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header();
  10. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header('application/json');
  11. $cookie1 = $q->cookie(-name=>'riddle_name', -value=>"The Sphynx's Question");
  12. $cookie2 = $q->cookie(-name=>'answers', -value=>\%answers);
  13. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header(
  14. -type => 'image/gif',
  15. -expires => '+3d',
  16. -cookie => [$cookie1,$cookie2]
  17. );
  18. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $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. Major features including processing form submissions, file uploads, reading and writing cookies, query string generation and manipulation, and processing and preparing HTTP headers. Some HTML generation utilities are included as well.

CGI.pm performs very well in a vanilla CGI.pm environment and also comes with built-in support for mod_perl and mod_perl2 as well as FastCGI.

It has the benefit of having developed and refined over 10 years with input from dozens of contributors and being deployed on thousands of websites. CGI.pm has been included in the Perl distribution since Perl 5.4, and has become a de-facto standard.

PROGRAMMING STYLE

Dolce Dolce amp;Gabbana Sunglasses amp;Gabbana Sunglasses Dolce There are two styles of programming with CGI.pm, an object-oriented style and a function-oriented style. In the object-oriented style you create one or more CGI objects and then use object methods to create the various elements of the page. Each CGI object starts out with the list of named parameters that were passed to your CGI script by the server. You can modify the objects, save them to a file or database and recreate them. Because each object corresponds to the "state" of the CGI script, and because each object's parameter list is independent of the others, this allows you to save the state of the script and restore it later.

For example, using the object oriented style, here is how you create a simple "Hello World" HTML page:

       
  1. amp;Gabbana Dolce Sunglasses amp;Gabbana Sunglasses Dolce Dolce #!/usr/local/bin/perl -w
  2. use CGI; # load CGI routines
  3. $q = CGI->new; # create new CGI object
  4. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header, # create the HTTP header
  5. $q->start_html('hello world'), # start the HTML
  6. $q->h1('hello world'), # level 1 header
  7. $q->end_html; # end the HTML

In the function-oriented style, there is one default CGI object that you rarely deal with directly. Instead you just call functions to retrieve CGI parameters, create HTML tags, manage cookies, and so on. This provides you with a cleaner programming interface, but limits you to using one CGI object at a time. The following example prints the same page, but uses the function-oriented interface. The main differences are that we now need to import a set of functions into our name space (usually the "standard" functions), and we don't need to create the CGI object.

       
  1. #!/usr/local/bin/perl
  2. use CGI qw/:standard/; # load standard CGI routines
  3. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header, # create the HTTP header
  4. start_html('hello world'), # start the HTML
  5. h1('hello world'), # level 1 header
  6. end_html; # end the HTML

The examples in this document mainly use the object-oriented style. See HOW TO IMPORT FUNCTIONS for important information on function-oriented programming in CGI.pm

CALLING CGI.PM ROUTINES

Most CGI.pm routines accept several arguments, sometimes as many as 20 optional ones! To simplify this interface, all routines use a named argument calling style that looks like this:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header(-type=>'image/gif',-expires=>'+3d');

Each argument name is preceded by a dash. Neither case nor order matters in the argument list. -type, -Type, and -TYPE are all acceptable. In fact, only the first argument needs to begin with a dash. If a dash is present in the first argument, CGI.pm assumes dashes for the subsequent ones.

Several routines are commonly called with just one argument. In the case of these routines you can provide the single argument without an argument name. header() happens to be one of these routines. In this case, the single argument is the document type.

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header('text/html');

Other such routines are documented below.

Sometimes named arguments expect a scalar, sometimes a reference to an array, and sometimes a reference to a hash. Often, you can pass any type of argument and the routine will do whatever is most appropriate. For example, the param() routine is used to set a CGI parameter to a single or a multi-valued value. The two cases are shown below:

       
  1. $q->param(-name=>'veggie',-value=>'tomato');
  2. $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);

A large number of routines in CGI.pm actually aren't specifically defined in the module, but are generated automatically as needed. These are the "HTML shortcuts," routines that generate HTML tags for use in dynamically-generated pages. HTML tags have both attributes (the attribute="value" pairs within the tag itself) and contents (the part between the opening and closing pairs.) To distinguish between attributes and contents, CGI.pm uses the convention of passing HTML attributes as a hash reference as the first argument, and the contents, if any, as any subsequent arguments. It works out like this:

       
  1. Code Generated HTML
  2. ---- --------------
  3. h1()

  4. h1('some','contents');

    some contents

  5. h1({-align=>left});

  6. h1({-align=>left},'contents');

    contents

HTML tags are described in more detail later.

Many newcomers to CGI.pm are puzzled by the difference between the calling conventions for the HTML shortcuts, which require curly braces around the HTML tag attributes, and the calling conventions for other routines, which manage to generate attributes without the curly brackets. Don't be confused. As a convenience the curly braces are optional in all but the HTML shortcuts. If you like, you can use curly braces when calling any routine that takes named arguments. For example:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header( {-type=>'image/gif',-expires=>'+3d'} );

If you use the -w switch, you will be warned that some CGI.pm argument names conflict with built-in Perl functions. The most frequent of these is the -values argument, used to create multi-valued menus, radio button clusters and the like. To get around this warning, you have several choices:

1.

Use another name for the argument, if one is available. For example, -value is an alias for -values.

2.

Change the capitalization, e.g. -Values

3.

Put quotes around the argument name, e.g. '-values'

Many routines will do something useful with a named argument that it doesn't recognize. For example, you can produce non-standard HTTP header fields by providing them as named arguments:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header(-type => 'text/html',
  2. -cost => 'Three smackers',
  3. -annoyance_level => 'high',
  4. -complaints_to => 'bit bucket');

This will produce the following nonstandard HTTP header:

       
  1. HTTP/1.0 200 OK
  2. Cost: Three smackers
  3. Annoyance-level: high
  4. Complaints-to: bit bucket
  5. Content-type: text/html

Notice the way that underscores are translated automatically into hyphens. HTML-generating routines perform a different type of translation.

This feature allows you to keep up with the rapidly changing HTTP and HTML "standards".

CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):

       
  1. $query = CGI->new;

This will parse the input (from POST, GET and DELETE methods) and store it into a perl5 object called $query.

Any filehandles from file uploads will have their position reset to the beginning of the file.

CREATING A NEW QUERY OBJECT FROM AN INPUT FILE

       
  1. $query = CGI->new(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:

       
  1. $query = CGI->new(\*STDIN);

You can also initialize the CGI object with a FileHandle or IO::File object.

If you are using the function-oriented interface and want to initialize CGI state from a file handle, the way to do this is with restore_parameters(). This will (re)initialize the default CGI object from the indicated file handle.

       
  1. open (IN,"test.in") || die;
  2. restore_parameters(IN);
  3. close IN;

You can also initialize the query object from a hash reference:

       
  1. $query = CGI->new( {'dinosaur'=>'barney',
  2. 'song'=>'I love you',
  3. 'friends'=>[qw/Jessica George Nancy/]}
  4. );

or from a properly formatted, URL-escaped query string:

       
  1. $query = CGI->new('dinosaur=barney&color=purple');

or from a previously existing CGI object (currently this clones the parameter list, but none of the other object-specific fields, such as autoescaping):

       
  1. $old_query = CGI->new;
  2. $new_query = CGI->new($old_query);

To create an empty query, initialize it from an empty string or hash:

       
  1. $empty_query = CGI->new("");
  2. -or-
  3. $empty_query = CGI->new({});

FETCHING A LIST OF KEYWORDS FROM THE QUERY:

       
  1. @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.

FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:

       
  1. @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 and contains a string without ampersands (e.g. "value1+value2+value3") , there will be a single parameter named "keywords" containing the "+"-delimited 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).

FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:

       
  1. @values = $query->param('foo');
  2. -or-
  3. $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=", it will be returned as an empty string.

If the parameter does not exist at all, then param() will return undef in a scalar context, and the empty list in a list context.

SETTING THE VALUE(S) OF A NAMED PARAMETER:

       
  1. $query->param(amp;Gabbana Dolce Dolce Sunglasses Sunglasses Dolce amp;Gabbana '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:

       
  1. $query->param(-name=>'foo',-values=>['an','array','of','values']);
  2. -or-
  3. $query->param(-name=>'foo',-value=>'the value');

APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:

       
  1. $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.

IMPORTING ALL PARAMETERS INTO A NAMESPACE:

       
  1. $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!!!!

NOTE 1: Variable names are transformed as necessary into legal Perl variable names. All non-legal characters are transformed into underscores. If you need to keep the original names, you should use the param() method instead to access CGI variables by name.

NOTE 2: In older versions, this method was called import(). As of version 2.20, this name has been removed completely to avoid conflict with the built-in Perl module import operator.

DELETING A PARAMETER COMPLETELY:

       
  1. $query->delete('foo','bar','baz');

This completely clears a list of parameters. It sometimes useful for resetting parameters that you don't want passed down between script invocations.

If you are using the function call interface, use "Delete()" instead to avoid conflicts with Perl's built-in delete operator.

DELETING ALL PARAMETERS:

       
  1. $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.

Use Delete_all() instead if you are using the function call interface.

HANDLING NON-URLENCODED ARGUMENTS

If POSTed data is not of type application/x-www-form-urlencoded or multipart/form-data, then the POSTed data will not be processed, but instead be returned as-is in a parameter named POSTDATA. To retrieve it, use code like this:

       
  1. my $data = $query->param('POSTDATA');

Likewise if PUTed data can be retrieved with code like this:

       
  1. my $data = $query->param('PUTDATA');

(If you don't know what the preceding means, don't worry about it. It only affects people trying to use CGI for XML processing and other specialized tasks.)

DIRECT ACCESS TO THE PARAMETER LIST:

       
  1. $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
  2. unshift @{$q->param_fetch(-name=>'address')},'George Munster';

If you need access to the parameter list in a way that isn't covered by the methods given in the previous sections, you can obtain a direct reference to it by calling the param_fetch() method with the name of the parameter. This will return an array reference to the named parameter, which you then can manipulate in any way you like.

You can also use a named argument style using the -name argument.

FETCHING THE PARAMETER LIST AS A HASH:

       
  1. $params = $q->Vars;
  2. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $params->{'address'};
  3. @foo = split("\0",$params->{Dolce Sunglasses Dolce amp;Gabbana Dolce amp;Gabbana Sunglasses 'foo'});
  4. %params = $q->Vars;
  5. use CGI ':cgi-lib';
  6. $params = Vars;

Many people want to fetch the entire parameter list as a hash in which the keys are the names of the CGI parameters, and the values are the parameters' values. The Vars() method does this. Called in a scalar context, it returns the parameter list as a tied hash reference. Changing a key changes the value of the parameter in the underlying CGI parameter list. Called in a list context, it returns the parameter list as an ordinary hash. This allows you to read the contents of the parameter list, but not to change it.

When using this, the thing you must watch out for are multivalued CGI parameters. Because a hash cannot distinguish between scalar and list context, multivalued parameters will be returned as a packed string, separated by the "\0" (null) character. You must split this packed string in order to get at the individual values. This is the convention introduced long ago by Steve Brenner in his cgi-lib.pl module for Perl version 4.

If you wish to use Vars() as a function, import the :cgi-lib set of function calls (also see the section on CGI-LIB compatibility).

SAVING THE STATE OF THE SCRIPT TO A FILE:

       
  1. $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:

       
  1. NAME1=VALUE1
  2. NAME1=VALUE1'
  3. NAME2=VALUE2
  4. NAME3=VALUE3
  5. =

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 new. 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:

       
  1. use CGI;
  2. open (OUT,'>>','test.out') || die;
  3. $records = 5;
  4. for (0..$records) {
  5. my $q = CGI->new;
  6. $q->param(-name=>'counter',-value=>$_);
  7. $q->save(\*OUT);
  8. }
  9. close OUT;
  10. # reopen for reading
  11. open (IN,'<','test.out') || die;
  12. while (!eof(IN)) {
  13. my $q = CGI->new(\*IN);
  14. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->param('counter'),"\n";
  15. }

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

       
  1. http://stein.cshl.org/boulder/

for further details.

If you wish to use this method from the function-oriented (non-OO) interface, the exported name for this method is save_parameters().

RETRIEVING CGI ERRORS

Errors can occur while processing user input, particularly when processing uploaded files. When these errors occur, CGI will stop processing and return an empty parameter list. You can test for the existence and nature of errors using the cgi_error() function. The error messages are formatted as HTTP status codes. You can either incorporate the error text into an HTML page, or use it as the value of the HTTP status:

       
  1. my $error = $q->cgi_error;
  2. if ($error) {
  3. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->header(-status=>$error),
  4. $q->start_html('Problems'),
  5. $q->h2('Request not processed'),
  6. $q->strong($error);
  7. exit 0;
  8. }

When using the function-oriented interface (see the next section), errors may only occur the first time you call param(). Be ready for this!

USING THE FUNCTION-ORIENTED INTERFACE

To use the function-oriented interface, you must specify which CGI.pm routines or sets of routines to import into your script's namespace. There is a small overhead associated with this importation, but it isn't much.

       
  1. use CGI ;

The listed methods will be imported into the current package; you can call them directly without creating a CGI object first. This example shows how to import the param() and header() methods, and then use them directly:

       
  1. use CGI 'param','header';
  2. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header('text/plain');
  3. $zipcode = param('zipcode');

More frequently, you'll import common sets of functions by referring to the groups by name. All function sets are preceded with a ":" character as in ":html3" (for tags defined in the HTML 3 standard).

Here is a list of the function sets you can import:

  • :cgi

    Import all CGI-handling methods, such as param(), path_info() and the like.

  • :form

    Import all fill-out form generating methods, such as textfield().

  • :html2

    Import all methods that generate HTML 2.0 standard elements.

  • :html3

    Import all methods that generate HTML 3.0 elements (such as

    , and ).

  • :html4

    Import all methods that generate HTML 4 elements (such as , and

  • ).

  • :netscape

    Import the , and

    tags.

  • :html

    Import all HTML-generating shortcuts (i.e. 'html2', 'html3', 'html4' and 'netscape')

  • :standard

    Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.

  • :all

    Import all the available methods. For the full list, see the CGI.pm code, where the variable %EXPORT_TAGS is defined.

  • If you import a function name that is not part of CGI.pm, the module will treat it as a new HTML tag and generate the appropriate subroutine. You can then use it like any other HTML tag. This is to provide for the rapidly-evolving HTML "standard." For example, say Microsoft comes out with a new tag called (which causes the user's desktop to be flooded with a rotating gradient fill until his machine reboots). You don't need to wait for a new version of CGI.pm to start using it immediately:

           
    1. use CGI qw/:standard :html3 gradient/;
    2. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U gradient({-start=>'red',-end=>'blue'});

    Note that in the interests of execution speed CGI.pm does not use the standard Exporter syntax for specifying load symbols. This may change in the future.

    If you import any of the state-maintaining CGI or form-generating methods, a default CGI object will be created and initialized automatically the first time you use any of the methods that require one to be present. This includes param(), textfield(), submit() and the like. (If you need direct access to the CGI object, you can find it in the global variable $CGI::Q). By importing CGI.pm methods, you can create visually elegant scripts:

           
    1. use CGI qw/:standard/;
    2. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U
    3. header,
    4. start_html('Simple Script'),
    5. h1('Simple Script'),
    6. start_form,
    7. "What's your name? ",textfield(amp;Gabbana Dolce Dolce Sunglasses Sunglasses Dolce amp;Gabbana 'name'),p,
    8. "What's the combination?",
    9. checkbox_group(-name=>'words',
    10. -values=>['eenie','meenie','minie','moe'],
    11. -defaults=>['eenie','moe']),p,
    12. "What's your favorite color?",
    13. popup_menu(-name=>'color',
    14. -values=>['red','green','blue','chartreuse']),p,
    15. submit,
    16. end_form,
    17. hr,"\n";
    18. if (param) {
    19. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U
    20. "Your name is ",em(param('name')),p,
    21. "The keywords are: ",em(join(", ",paramamp;Gabbana Dolce Sunglasses Dolce Sunglasses Dolce amp;Gabbana ('words'))),p,
    22. "Your favorite color is ",em(param('color')),".\n";
    23. }
    24. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U end_html;

    PRAGMAS

    In addition to the function sets, there are a number of pragmas that you can import. Pragmas, which are always preceded by a hyphen, change the way that CGI.pm functions in various ways. Pragmas, function sets, and individual functions can all be imported in the same use() line. For example, the following use statement imports the standard set of functions and enables debugging mode (pragma -debug):

           
    1. use CGI qw/:standard -debug/;

    The current list of pragmas is as follows:

    • -any

      When you use CGI -any, then any method that the query object doesn't recognize will be interpreted as a new HTML tag. This allows you to support the next ad hoc HTML extension. This lets you go wild with new and unsupported tags:

               
      1. use CGI qw(-any);
      2. $q=CGI->new;
      3. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->gradient({speed=>'fast',start=>'red',end=>'blue'});

      Since using any causes any mistyped method name to be interpreted as an HTML tag, use it with care or not at all.

    • -compile

      This causes the indicated autoloaded methods to be compiled up front, rather than deferred to later. This is useful for scripts that run for an extended period of time under FastCGI or mod_perl, and for those destined to be crunched by Malcolm Beattie's Perl compiler. Use it in conjunction with the methods or method families you plan to use.

               
      1. use CGI qw(-compile :standard :html3);

      or even

               
      1. use CGI qw(-compile :all);

      Note that using the -compile pragma in this way will always have the effect of importing the compiled functions into the current namespace. If you want to compile without importing use the compile() method instead:

               
      1. use CGI();
      2. CGI->compile();

      This is particularly useful in a mod_perl environment, in which you might want to precompile all CGI routines in a startup script, and then import the functions individually in each mod_perl script.

    • -nosticky

      By default the CGI module implements a state-preserving behavior called "sticky" fields. The way this works is that if you are regenerating a form, the methods that generate the form field values will interrogate param() to see if similarly-named parameters are present in the query string. If they find a like-named parameter, they will use it to set their default values.

      Sometimes this isn't what you want. The -nosticky pragma prevents this behavior. You can also selectively change the sticky behavior in each element that you generate.

    • -tabindex

      Automatically add tab index attributes to each form field. With this option turned off, you can still add tab indexes manually by passing a -tabindex option to each field-generating method.

    • -no_undef_params

      This keeps CGI.pm from including undef params in the parameter list.

    • -no_xhtml

      By default, CGI.pm versions 2.69 and higher emit XHTML (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this feature. Thanks to Michalis Kabrianis for this feature.

      If start_html()'s -dtd parameter specifies an HTML 2.0, 3.2, 4.0 or 4.01 DTD, XHTML will automatically be disabled without needing to use this pragma.

    • -utf8

      This makes CGI.pm treat all parameters as UTF-8 strings. Use this with care, as it will interfere with the processing of binary uploads. It is better to manually select which fields are expected to return utf-8 strings and convert them using code like this:

               
      1. use Encode;
      2. my $arg = decode utf8=>param('foo');
    • -nph

      This makes CGI.pm produce a header appropriate for an NPH (no parsed header) script. You may need to do other things as well to tell the server that the script is NPH. See the discussion of NPH scripts below.

    • -newstyle_urls

      Separate the name=value pairs in CGI parameter query strings with semicolons rather than ampersands. For example:

               
      1. ?name=fred;age=24;favorite_color=3

      Semicolon-delimited query strings are always accepted, and will be emitted by self_url() and query_string(). newstyle_urls became the default in version 2.64.

    • -oldstyle_urls

      Separate the name=value pairs in CGI parameter query strings with ampersands rather than semicolons. This is no longer the default.

    • -autoload

      This overrides the autoloader so that any function in your program that is not recognized is referred to CGI.pm for possible evaluation. This allows you to use all the CGI.pm functions without adding them to your symbol table, which is of concern for mod_perl users who are worried about memory consumption. Warning: when -autoload is in effect, you cannot use "poetry mode" (functions without the parenthesis). Use hr() rather than hr, or add something like use subs qw/hr p header/ to the top of your script.

    • -no_debug

      This turns off the command-line processing features. If you want to run a CGI.pm script from the command line to produce HTML, and you don't want it to read CGI parameters from the command line or STDIN, then use this pragma:

               
      1. use CGI qw(-no_debug :standard);
    • -debug

      This turns on full debugging. In addition to reading CGI arguments from the command-line processing, CGI.pm will pause and try to read arguments from STDIN, producing the message "(offline mode: enter name=value pairs on standard input)" features.

      See the section on debugging for more details.

    • -private_tempfiles

      CGI.pm can process uploaded file. Ordinarily it spools the uploaded file to a temporary directory, then deletes the file when done. However, this opens the risk of eavesdropping as described in the file upload section. Another CGI script author could peek at this data during the upload, even if it is confidential information. On Unix systems, the -private_tempfiles pragma will cause the temporary file to be unlinked as soon as it is opened and before any data is written into it, reducing, but not eliminating the risk of eavesdropping (there is still a potential race condition). To make life harder for the attacker, the program chooses tempfile names by calculating a 32 bit checksum of the incoming HTTP headers.

      To ensure that the temporary file cannot be read by other CGI scripts, use suEXEC or a CGI wrapper program to run your script. The temporary file is created with mode 0600 (neither world nor group readable).

      The temporary directory is selected using the following algorithm:

               
      1. 1. if $CGITempFile::TMPDIRECTORY is already set, use that
      2. 2. if the environment variable TMPDIR exists, use the location
      3. indicated.
      4. 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
      5. /tmp, /temp, ::Temporary Items, and \WWW_ROOT.

      Each of these locations is checked that it is a directory and is writable. If not, the algorithm tries the next choice.

    SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS

    Many of the methods generate HTML tags. As described below, tag functions automatically generate both the opening and closing tags. For example:

           
    1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U h1('Level 1 Header');

    produces

           
    1. Level 1 Header

    There will be some times when you want to produce the start and end tags yourself. In this case, you can use the form start_tag_name and end_tag_name, as in:

           
    1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U start_h1,'Level 1 Header',end_h1;

    With a few exceptions (described below), start_tag_name and end_tag_name functions are not generated automatically when you use CGI. However, you can specify the tags you want to generate start/end functions for by putting an asterisk in front of their name, or, alternatively, requesting either "start_tag_name" or "end_tag_name" in the import list.

    Example:

           
    1. use CGI qw/:standard *table start_ul/;

    In this example, the following functions are generated in addition to the standard ones:

    1.
    start_table() (generates a
    tag)
    2.
    end_table() (generates a
    tag)
    3.
    start_ul() (generates a
      tag)
    4.
    end_ul() (generates a
tag)

Most of CGI.pm's functions deal with creating documents on the fly. Generally you will produce the HTTP header first, followed by the document itself. CGI.pm provides functions for generating HTTP headers of various types as well as for generating HTML. For creating GIF images, see the GD.pm module.

Each of these functions produces a fragment of HTML or HTTP which you can print out directly so that it displays in the browser window, append to a string, or save to a file for later use.

CREATING A STANDARD HTTP HEADER:

Normally the first thing you will do in any CGI script is print out an HTTP header. This tells the browser what type of document to expect, and gives other optional information, such as the language, expiration date, and whether to cache the document. The header can also be manipulated for special purposes, such as server push and pay per view pages.

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header;
  2. -or-
  3. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header('image/gif');
  4. -or-
  5. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header('text/html','204 No response');
  6. -or-
  7. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header(-type=>'image/gif',
  8. -nph=>1,
  9. -status=>'402 Payment required',
  10. -expires=>'+3d',
  11. -cookie=>$cookie,
  12. -charset=>'utf-7',
  13. -attachment=>'foo.gif',
  14. -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. Note that RFC 2616 expects the human-readable phase to be there as well as the numeric status code.

The last example shows the named argument style for passing arguments to the CGI methods using named parameters. Recognized parameters are -type, -status, -expires, and -cookie. Any other named parameters will be stripped of their initial hyphens and turned into header fields, allowing you to specify any HTTP header you desire. Internal underscores will be turned into hyphens:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header(-Content_length=>3002);

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 -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:

       
  1. +30s 30 seconds from now
  2. +10m ten minutes from now
  3. +1h one hour from now
  4. -1d yesterday (i.e. "ASAP!")
  5. now immediately
  6. +3M in three months
  7. +10y in ten years time
  8. Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date

The -cookie parameter generates a header that tells the browser to provide a "magic cookie" during all subsequent transactions with your script. Some cookies have a special format that includes interesting attributes such as expiration time. Use the cookie() method to create and retrieve session cookies.

The -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 that expect all their scripts to be NPH.

The -charset parameter can be used to control the character set sent to the browser. If not provided, defaults to ISO-8859-1. As a side effect, this sets the charset() method as well.

The -attachment parameter can be used to turn the page into an attachment. Instead of displaying the page, some browsers will prompt the user to save it to disk. The value of the argument is the suggested name for the saved file. In order for this to work, you may have to set the -type to "application/octet-stream".

The -p3p parameter will add a P3P tag to the outgoing header. The parameter can be an arrayref or a space-delimited string of P3P tags. For example:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header(-p3p=>[qw(CAO DSP LAW CURa)]);
  2. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header(-p3p=>'CAO DSP LAW CURa');

In either case, the outgoing header will be formatted as:

       
  1. P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"

CGI.pm will accept valid multi-line headers when each line is separated with a CRLF value ("\r\n" on most platforms) followed by at least one space. For example:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U header( -ingredients => "ham\r\n\seggs\r\n\sbacon" );

Invalid multi-line header input will trigger in an exception. When multi-line headers are received, CGI.pm will always output them back as a single line, according to the folding rules of RFC 2616: the newlines will be removed, while the white space remains.

GENERATING A REDIRECTION HEADER

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->redirect('http://somewhere.else/in/movie/land');

Sometimes you don't want to produce a document yourself, but simply redirect the browser elsewhere, perhaps choosing a URL based on the time of day or the identity of the user.

The redirect() method redirects the browser to a different URL. If you use redirection like this, you should not print out a header as well.

You should always use full URLs (including the http: or ftp: part) in redirection requests. Relative URLs will not work correctly.

You can also use named arguments:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->redirect(
  2. -uri=>'http://somewhere.else/in/movie/land',
  3. -nph=>1,
  4. -status=>'301 Moved Permanently');

All names arguments recognized by header() are also recognized by redirect(). However, most HTTP headers, including those generated by -cookie and -target, are ignored by the browser.

The -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 IIS, which expect all their scripts to be NPH.

The -status parameter will set the status of the redirect. HTTP defines three different possible redirection status codes:

       
  1. 301 Moved Permanently
  2. 302 Found
  3. 303 See Other

The default if not specified is 302, which means "moved temporarily." You may change the status to another status code if you wish. Be advised that changing the status to anything other than 301, 302 or 303 will probably break redirection.

Note that the human-readable phrase is also expected to be present to conform with RFC 2616, section 6.1.

CREATING THE HTML DOCUMENT HEADER

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U start_html(-title=>'Secrets of the Pyramids',
  2. -author=>'fred@capricorn.org',
  3. -base=>'true',
  4. -target=>'_blank',
  5. -meta=>{'keywords'=>'pharaoh secret mummy',
  6. 'copyright'=>'copyright 1996 King Tut'},
  7. -style=>{'src'=>'/styles/style1.css'},
  8. -BGCOLOR=>'blue');

The start_html() routine creates the top of the page, along with a lot of optional information that controls the page's appearance and behavior.

This method returns a canned HTML header and the opening tag. All parameters are optional. In the named parameter form, recognized parameters are -title, -author, -base, -xbase, -dtd, -lang and -target (see below for the explanation). Any additional parameters you provide, such as the unofficial BGCOLOR attribute, are added to the tag. Additional parameters must be proceeded by a hyphen.

The argument -xbase allows you to provide an HREF for the

       
  1. -xbase=>"http://home.mcom.com/"

All relative links will be interpreted relative to this tag.

The argument -target allows you to provide a default target frame for all the links and fill-out forms on the page. This is a non-standard HTTP feature which only works with some browsers!

       
  1. -target=>"answer_window"

All relative links will be interpreted relative to this tag. You add arbitrary meta information to the header with the -meta argument. This argument expects a reference to a hash containing name/value pairs of meta information. These will be turned into a series of header tags that look something like this:

       

To create an HTTP-EQUIV type of tag, use -head, described below.

The -style argument is used to incorporate cascading stylesheets into your code. See the section on CASCADING STYLESHEETS for more information.

The -lang argument is used to incorporate a language attribute into the tag. For example:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U $q->start_html(-lang=>'fr-CA');

The default if not specified is "en-US" for US English, unless the -dtd parameter specifies an HTML 2.0 or 3.2 DTD, in which case the lang attribute is left off. You can force the lang attribute to left off in other cases by passing an empty string (-lang=>'').

The -encoding argument can be used to specify the character set for XHTML. It defaults to iso-8859-1 if not specified.

The -dtd argument can be used to specify a public DTD identifier string. For example:

       
  1. -dtd => '-//W3C//DTD HTML 4.01 Transitional//EN')

Alternatively, it can take public and system DTD identifiers as an array:

       
  1. dtd => [ '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd' ]

For the public DTD identifier to be considered, it must be valid. Otherwise it will be replaced by the default DTD. If the public DTD contains 'XHTML', CGI.pm will emit XML.

The -declare_xml argument, when used in conjunction with XHTML, will put a declaration at the top of the HTML header. The sole purpose of this declaration is to declare the character set encoding. In the absence of -declare_xml, the output HTML will contain a tag that specifies the encoding, allowing the HTML to pass most validators. The default for -declare_xml is false.

You can place other arbitrary HTML elements to the section with the -head tag. For example, to place a element in the head section, use this:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U start_html(-head=>Link({-rel=>'shortcut icon',
  2. -href=>'favicon.ico'}));

To incorporate multiple HTML elements into the section, just pass an array reference:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U start_html(-head=>[
  2. Link({-rel=>'next',
  3. -href=>'http://www.capricorn.com/s2.html'}),
  4. Link({-rel=>'previous',
  5. -href=>'http://www.capricorn.com/s1.html'})
  6. ]
  7. );

And here's how to create an HTTP-EQUIV tag:

       
  1. HYPER LABEL hoodie up POP ORANGE Superdry Zip q6xAS6U start_html(-head=>meta({-http_equiv => 'Content-Type',
  2. -content => 'text/html'}))

JAVASCRIPTING: The -script, -noScript, -onLoad, -onMouseOver, -onMouseOut and -onUnload parameters are used to add JavaScript calls to your pages. -script should point to a block of text containing JavaScript function definitions. This block will be placed within a