• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

perl-CGI

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

CGI Library

 

AS OF 10 FEBRUARY 2005 (CGI.pm VERSION 3.06) THIS DOCUMENT IS NO LONGER BEING MAINTAINED. PLEASE CONSULT THE CGI POD DOCUMENTATION USING "perldoc 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.

A script to create a fill-out form that remembers its state each time it's invoked is very easy to write with CGI.pm:

#!/usr/local/bin/perl
use CGI qw(:standard);
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your name? ",textfield('name'),
p,
"What's the combination?",
p,
checkbox_group(-name=>'words',
-values=>['eenie','meenie','minie','moe'],
-defaults=>['eenie','minie']),
p,
"What's your favorite color? ",
popup_menu(-name=>'color',
-values=>['red','green','blue','chartreuse']),
p,
submit,
end_form,
hr;
if (param()) {
print
"Your name is",em(param('name')),
p,
"The keywords are: ",em(join(", ",param('words'))),
p,
"Your favorite color is ",em(param('color')),
hr;
}
print end_html;
Select this link to try the script
More scripting examples
Source code examples from The Official Guide to CGI.pm

 

Contents

  • Downloading
  • Installation
  • Function-Oriented vs Object-Oriented Use
  • Creating a new CGI query object
  • Saving the state of the form
  • CGI Functions that Take Multiple Arguments
  • Creating the HTTP header
  • HTML shortcuts
  • Creating forms
  • Importing CGI methods
  • Retrieving CGI.pm errors
  • Debugging
  • HTTP session variables
  • HTTP Cookies
  • Support for frames
  • Support for JavaScript
  • Limited Support for Cascading Style Sheets
  • Using NPH Scripts
  • Advanced techniques
  • Subclassing CGI.pm
  • Using CGI.pm with mod_perl and FastCGI
  • Migrating from cgi-lib.pl
  • Using the File Upload Feature
  • Server Push
  • Avoiding Denial of Service Attacks
  • Using CGI.pm on non-Unix Platforms
  • The Relationship of CGI.pm to the CGI::* Modules
  • Distribution information
  • The CGI.pm Book
  • CGI.pm and the Year 2000 Problem
  • Bug Reporting and Support
  • What's new?

  • Downloads

     

    Installation

    The current version of the software can always be downloaded from the master copy of this document maintained at http://stein.cshl.org/WWW/software/CGI/.

    This package requires perl 5.004 or higher. Earlier versions of Perl may work, but CGI.pm has not been tested with them. If you're really stuck, edit the source code to remove the line that says "require 5.004", but don't be surprised if you run into problems.

    If you are using a Unix system, you should have perl do the installation for you. Move to the directory containing CGI.pm and type the following commands:

    % perl Makefile.PL
    % make
    % make install
    
    You may need to be root to do the last step.

    This will create two new files in your Perl library. CGI.pm is the main library file. Carp.pm (in the subdirectory "CGI") contains some optional utility routines for writing nicely formatted error messages into your server logs. See the Carp.pm man page for more details.

    If you get error messages when you try to install, then you are either:

    1. Running a Windows NT or Macintosh port of Perl that doesn't have make or the MakeMaker program built into it.
    2. Have an old version of Perl. Upgrade to 5.004 or higher.
    In the former case don't panic. Here's a recipe that will work (commands are given in MS-DOS/Windows form):
    > cd CGI.pm-2.73
    > copy CGI.pm C:\Perl\lib
    > mkdir C:\Perl\lib\CGI
    > copy CGI\*.pm C:\Perl\lib\CGI
    
    Modify this recipe if your Perl library has a different location.

    For Macintosh users, just drag the file named CGI.pm into the folder where your other Perl .pm files are stored. Also drag the subfolder named "CGI".

    If you do not have sufficient privileges to install into /usr/local/lib/perl5, you can still use CGI.pm. Modify the installation recipe as follows:

    % perl Makefile.PL INSTALLDIRS=site INSTALLSITELIB=/home/your/private/dir
    % make
    % make install
    
    Replace /home/your/private/dir with the full path to the directory you want the library placed in. Now preface your CGI scripts with a preamble something like the following:
    use lib '/home/your/private/dir';
    use CGI;
    
    Be sure to replace /home/your/private/dir with the true location of CGI.pm.

    Notes on using CGI.pm in NT and other non-Unix platforms


    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 addition to the standard set, there are many optional sets of less frequently used CGI functions. See Importing CGI Methods for full details.
    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
    Many of the code examples below show the object-oriented coding style. Mentally translate them into the function-oriented style if you prefer.

    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;
    
    In the object-oriented world of Perl 5, this code calls the new() method of the CGI class and stores a new CGI object into the variable named $query. The new() method does all the dirty work of parsing the script parameters and environment variables and stores its results in the new object. You'll now make method calls with this object to get at the parameters, generate form elements, and do other useful things.

    An alternative form of the new() method allows you to read script parameters from a previously-opened file handle:

        $query = new CGI(FILEHANDLE)
    
    The filehandle can contain a URL-encoded query string, or can be a series of newline delimited TAG=VALUE pairs. This is compatible with the save() method. This lets you save the state of a CGI script to a file and reload it later. It's also possible to save the contents of several query objects to the same file, either within a single script or over a period of time. You can then reload the multiple records into an array of query objects with something like this:
    open (IN,"test.in") || die;
    while (!eof(IN)) {
    my $q = new CGI(IN);
    push(@queries,$q);
    }
    
    You can make simple databases this way, or create a guestbook. If you're a Perl purist, you can pass a reference to the filehandle glob instead of the filehandle name. This is the "official" way to pass filehandles in Perl5:
     
     my $q = new CGI(\*IN);
    (If you don't know what I'm talking about, then you're not a Perl purist and you needn't worry about it.)

    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.

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

    You can initialize a CGI object from an associative-array reference. Values can be either single- or multivalued:

    $query = new CGI({'dinosaur'=>'barney',
    'song'=>'I love you',
    'friends'=>[qw/Jessica George Nancy/]});
    
    You can initialize a CGI object by passing a URL-style query string to the new() method like this:
    $query = new CGI('dinosaur=barney&color=purple');
    
    Or you can clone a CGI object from an existing one. The parameter lists of the clone will be identical, but other fields, such as autoescaping, are not:
    $old_query = new CGI;
    $new_query = new CGI($old_query);
    

    This form also allows you to create a CGI object that is initially empty:

    $empty_query = new CGI('');
    

    If you are using mod_perl, you can initialize a CGI object at any stage of the request by passing the request object to CGI->new:

    $q = CGI->new($r);
    

    To do this with the function-oriented interface, set Apache->request($r) before calling the first CGI function.Finally, you can pass code reference to new() in order to install an upload_hook function that will be called regularly while a long file is being uploaded. See Creating a File Upload Field for details.See advanced techniques for more information.

    Fetching A List Of Keywords From The Query

        @keywords = $query->keywords
    
    If the script was invoked as the result of an <ISINDEX> search, the parsed keywords can be obtained with the keywords() method. This method will return the keywords as a perl array.

    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. For backwards compatibility if the script was invoked as an <ISINDEX> script and contains a string without ampersands (e.g. "value1+value2+value3") , there will be a single parameter named "keywords" containing the "+"-delimited keywords.

    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). This feature is new in 2.63, and was introduced to avoid multiple "undefined value" warnings when running with the -w switch.

    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

       $query->param('foo','an','array','of','values');
    -or-
    $query->param(-name=>'foo',-values=>['an','array','of','values']);
    
    This sets the value for the named parameter 'foo' to one or more values. These values will be used to initialize form elements, if you so desire. Note that this is the one way to forcibly change the value of a form field after it has previously been set.

    The second example shows an alternative "named parameter" style of function call that is accepted by most of the CGI methods. See Calling CGI functions that Take Multiple Arguments for an explanation of this style.

    Appending a 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.

    Deleting a Named Parameter Entirely

       $query->delete('foo');
    
    This deletes a named parameter entirely. This is useful when you want to reset the value of the parameter so that it isn't passed down between invocations of the script.

    Deleting all Parameters

       $query->delete_all();
    
    This deletes all the parameters and leaves you with an empty CGI object. This may be useful to restore all the defaults produced by the form element generating methods.

     

    Handling non-URLencoded ArgumentsIf 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:

       my $data = $query->param('POSTDATA');
    
    (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.)

    Importing parameters into a namespace

       $query->import_names('R');
    print "Your name is $R::name\n"
    print "Your favorite colors are @R::colors\n";
    This imports all parameters into the given name space. For example, if there were parameters named 'foo1', 'foo2' and 'foo3', after executing $query->import_names('R'), the variables @R::foo1, $R::foo1, @R::foo2, $R::foo2,etc. would conveniently spring into existence. Since CGI has no way of knowing whether you expect a multi- or single-valued parameter, it creates two variables for each parameter. One is an array, and contains all the values, and the other is a scalar containing the first member of the array. Use whichever one is appropriate. For keyword(a+b+c+d) lists, the variable @R::keywords will be created. 

    If you don't specify a name space, this method assumes namespace "Q".

    An optional second argument to import_names, if present and non-zero, will delete the contents of the namespace before loading it. This may be useful for environments like mod_perl in which the script does not exit after processing a request.Warning: do not import into namespace 'main'. This represents a major security risk, as evil people could then use this feature to redefine central variables such as @INC. CGI.pm will exit with an error if you try to do this.

    NOTE: 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 insteadto access CGI variables by name.

     

    Direct Access to the Parameter List

    $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
    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 above, you can obtain adirectreference to it by calling the param_fetch() method with the name of the parameter you want. This will return an array reference to the named parameters, which you then can manipulate in any way you like.

    You may call param_fetch() with the name of the CGI parameter, or with the -name argument, which has the same meaning as elsewhere.Fetching the Parameter List as a Hash

    $params = $q->Vars;
    print $params->{'address'};
    @foo = split("\0",$params->{'foo'});
    %params = $q->Vars;
    use CGI ':cgi-lib';
    $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, itreturns 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 an list context, it returns the parameter list as an ordinary hash. This allows ou 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).

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

        my $error = $q->cgi_error;
    if ($error) {
    print $q->header(-status=>$error),
    $q->start_html('Problems'),
    $q->h2('Request not processed'),
    $q->strong($error);
    exit 0;
    }
    When using the function-oriented interface (see the next section), errors may only occur the first time you call param(). Be prepared for this! Table of contents

    Saving the Current State of a Form

    Saving the State to a File

       $query->save(\*FILEHANDLE)
    
    This writes the current query out to the file handle of your choice. The file handle must already be open and be writable, but other than that it can point to a file, a socket, a pipe, or whatever. The contents of the form are written out as TAG=VALUE pairs, which can be reloaded with the new() method at some later time. You can write out multiple queries to the same file and later read them into query objects one by one.

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

    Saving the State in a Self-Referencing URL

       $my_url=$query->self_url
    
    This call returns a URL that, when selected, reinvokes this script with all its state information intact. This is most useful when you want to jump around within a script-generated document using internal anchors, but don't want to disrupt the current contents of the form(s). See advanced techniques for an example.

    If you'd like to get the URL without the entire query string appended to it, use the url() method:

       $my_self=$query->url
    

    Obtaining the Script's URL

        $full_url      = $query->url();
    $full_url      = $query->url(-full=>1);  #alternative syntax
    $relative_url  = $query->url(-relative=>1);
    $absolute_url  = $query->url(-absolute=>1);
    $url_with_path = $query->url(-path_info=>1);
    $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
    
    url() returns the script's URL in a variety of formats. Called without any arguments, it returns the full form of the URL, including host name and port number
    http://your.host.com/path/to/script.cgi
    
    You can modify this format with the following named arguments:
    -absolute
    If true, produce an absolute URL, e.g.
    /path/to/script.cgi
    

     

    -relative
    Produce a relative URL. This is useful if you want to reinvoke your script with different parameters. For example:
        script.cgi
    

     

    -full
    Produce the full URL, exactly as if called without any arguments. This overrides the -relative and -absolute arguments.

     

    -path,-path_info
    Append the additional path information to the URL. This can be combined with -full, -absolute or -relative. -path_info is provided as a synonym.

     

    -query (-query_string)
    Append the query string to the URL. This can be combined with -full, -absolute or -relative. -query_string is provided as a synonym.

    Mixing POST and URL Parameters

       $color = $query->url_param('color');
    
    It is possible for a script to receive CGI parameters in the URL as well as in the fill-out form by creating a form that POSTs to a URL containing a query string (a "?" mark followed by arguments). The param() method will always return the contents of the POSTed fill-out form, ignoring the URL's query string. To retrieve URL parameters, call the url_param() method. Use it in the same way as param(). The main difference is that it allows you to read the parameters, but not set them.

    Under no circumstances will the contents of the URL query string interfere with similarly-named CGI parameters in POSTed forms. If you try to mix a URL query string with a form submitted with the GET method, the results will not be what you expect.

    Table of contents


    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, it will usually 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 tag as an attribute. 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:
       <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
    JUSTIFICATION="RIGHT">
    
    Parameter names are case insensitive: you can use -name, or -Name or -NAME. 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.

    HTML/HTTP parameters that contain internal hyphens, such as -Content-language can be passed by putting quotes around them, or by using an underscore for the second hyphen, e.g. -Content_language.

    The fact that you must use curly {} braces around the attributes passed to functions that create simple HTML tags but don't use them around the arguments passed to all other functions has many people, including myself, confused. As of 2.37b7, the syntax is extended to allow you to use curly braces for all function calls:

       $field = $query->radio_group({-name=>'OS',
    -values=>[Unix,Windows,Macintosh],
    -default=>'Unix'});
    
    Table of contents

    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');
    

    -expires

    Some browsers, such as Internet Explorer, cache the output of CGI scripts. Others, such as Netscape Navigator do not. This leads to annoying and inconsistent behavior when going from one browser to another. You can force the behavior to be consistent by using the -expires parameter. When you specify an absolute or relative expiration interval with this parameter, 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
    Thu, 25-Apr-1999 00:40:33 GMT     at the indicated time & date
    
    When you use -expires, the script also generates a correct time stamp for the generated document to ensure that your clock and the browser's clock agree. This allows you to create documents that are reliably cached for short periods of time.

    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.

    -cookie

    The -cookie parameter generates a header that tells Netscape browsers to return a "magic cookie" during all subsequent transactions with your script. HTTP cookies have a special format that includes interesting attributes such as expiration time. Use the cookie() method to create and retrieve session cookies. The value of this parameter can be either a scalar value or an array reference. You can use the latter to generate multiple cookies. (You can use the alias -cookies for readability.)

    -nph

    The -nph parameter, if set to a non-zero value, will generate a valid header for use in no-parsed-header scripts. For example:
    print $query->header(-nph=>1,
    -status=>'200 OK',
    -type=>'text/html');
    
    You will need to use this if:
    1. You are using Microsoft Internet Information Server.
    2. If you need to create unbuffered output, for example for use in a "server push" script.
    3. To take advantage of HTTP extensions not supported by your server.
    See Using NPH Scripts for more information.

    -charset

    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 calls the charset() method to set the behavior for escapeHTML().

    -attachment

    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".

    -p3p

    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:
    print header(-p3p=>[qw(CAO DSP LAW CURa)]);
    print header(-p3p=>'CAO DSP LAW CURa');
    
    In either case, the outgoing header will be formatted as:
    P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
    

    Other header fields

    Any other parameters that you pass to header() will be turned into correctly formatted HTTP header fields, even if they aren't called for in the current HTTP spec. For example, the example that appears a few paragraphs above creates a field that looks like this:
       Cost: $0.02
    
    You can use this to take advantage of new HTTP header fields without waiting for the next release of CGI.pm.

    Creating the Header for a Redirection Request

       print $query->redirect('http://somewhere.else/in/the/world');
    
    This generates a redirection request for the remote browser. It will immediately go to the indicated URL. You should exit soon after this. Nothing else will be displayed.

    You can add your own headers to this as in the header() method.

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

    An alternative syntax for redirect() is:

    print $query->redirect(-location=>'http://somewhere.else/',
    -nph=>1,
    -status=>301);
    
    The -location parameter gives the destination URL. You may also use -uri or -url if you prefer.

    The -nph parameter, if non-zero tells CGI.pm that this script is running as a no-parsed-header script. See Using NPH Scripts for more information.

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

    301 Moved Permanently
    302 Found
    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.

    The -method parameter tells the browser what method to use for redirection. This is handy if, for example, your script was called from a fill-out form POST operation, but you want to redirect the browser to a static page that requires a GET.

    All other parameters recognized by the header() method are also valid in redirect. Table of contents


    HTML Shortcuts

    Creating an HTML Header

       named parameter style
    print $query->start_html(-title=>'Secrets of the Pyramids',
    -author=>'[email protected]',
    -base=>'true',
    -meta=>{'keywords'=>'pharoah secret mummy',
    'copyright'=>'copyright 1996 King Tut'},
    -style=>{'src'=>'/styles/style1.css'},
    -dtd=>1,
    -BGCOLOR=>'blue');
    old style
    print $query->start_html('Secrets of the Pyramids',
    '[email protected]','true');
    
    This will return a canned HTML header and the opening <BODY> tag. All parameters are optional:
    • The title (-title)
    • The author's e-mail address (will create a <LINK REV="MADE"> tag if present (-author)
    • A true flag if you want to include a <BASE> tag in the header (-base). This helps resolve relative addresses to absolute ones when the document is moved, but makes the document hierarchy non-portable. Use with care!
    • A -xbase parameter, if you want to include a <BASE> tag that points to some external location. Example:
            print $query->start_html(-title=>'Secrets of the Pyramids',
          -xbase=>'http://www.nile.eg/pyramid.html');
          
    • A -target parameter, if you want to have all links and fill out forms on the page go to a different frame. Example:
            print $query->start_html(-title=>'Secrets of the Pyramids',
          -target=>'answer_frame');
          
      -target can be used with either -xbase or -base.
    • A -meta parameter to define one or more <META> tags. Pass this parameter a reference to an associative array containing key/value pairs. Each pair becomes a <META> tag in a format similar to this one.
            <META NAME="keywords" CONTENT="pharoah secret mummy">
          <META NAME="description" CONTENT="copyright 1996 King Tut">
          
      To create an HTTP-EQUIV tag, use the -head argument as described below.
    • The -encoding argument can be used to specify the character set for XHTML. It defaults to iso-8859-1 if not specified.
    • The -declare_xml argument, when used in conjunction with XHTML, will put a <?xml> 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.
    • A -lang> argument is used to incorporate a language attribute into the <HTM>> tag. The default if not specified is "en-US" for US English. For example:
          print $q->start_html(-lang=>'fr-CA');
          
      To leave off the lang attribute, as you must do if you want to generate legal HTML 3.2 or earlier, pass the empty string (-lang=>'').
    • A -dtd parameter to make start_html() generate an SGML document type definition for the document. This is used by SGML editors and high-end Web publishing systems to determine the type of the document. However, it breaks some browsers, in particular AOL's. The value of this parameter can be one of:
      1. A valid DTD (see http://ugweb.cs.ualberta.ca/~gerald/validate/lib/catalog for a list). Example:
        -dtd=>'-//W3C//DTD HTML 3.2//EN'
      2. A true value that does not begin with "-//", in which case you will get the standard default DTD (valid for HTML 2.0).
      You can change the default DTD by calling default_dtd() with the preferred value.
    • A -style parameter to define a cascading stylesheet. More information on this can be found in Limited Support for Cascading Style Sheets
    • A -head parameter to define other arbitrary elements of the <HEAD> section. For example:
            print start_html(-head=>Link({-rel=>'next',
          -href=>'http://www.capricorn.com/s2.html'}));
          
      or even
            print start_html(-head=>[ Link({-rel=>'next',
          -href=>'http://www.capricorn.com/s2.html'}),
          Link({-rel=>'previous',
          -href=>'http://www.capricorn.com/s1.html'})
          ]
          );
          
      To create an HTTP-EQUIV tag, use something like this:
            print start_html(-head=>meta({-http_equiv=>'Content-Type',
          -content=>'text/html'}))
          
    • A -script parameter to define Netscape JavaScript functions to incorporate into the HTML page. This is the preferred way to define a library of JavaScript functions that will be called from elsewhere within the page. CGI.pm will attempt to format the JavaScript code in such a way that non-Netscape browsers won't try to display the JavaScript code. Unfortunately some browsers get confused nevertheless. Here's an example of how to create a JavaScript library and incorporating it into the HTML code header:
            $query = new CGI;
          print $query->header;
          $JSCRIPT=<<END;
          // Ask a silly question
          function riddle_me_this() {
          var r = prompt("What walks on four legs in the morning, " +
          "two legs in the afternoon, " +
          "and three legs in the evening?");
          response(r);
          }
          // Get a silly answer
          function response(answer) {
          if (answer == "man")
          alert("Right you are!");
          else
          alert("Wrong!  Guess again.");
          }
          END
          print $query->start_html(-title=>'The Riddle of the Sphinx',
          -script=>$JSCRIPT);
          
      Netscape 3.0 and higher allows you to place the JavaScript code in an external document and refer to it by URL. This allows you to keep the JavaScript code in a file or CGI script rather than cluttering up each page with the source. Netscape 3.X-4.X and Internet Explorer 3.X-4.X also recognize a "language" parameter that allows you to use other languages, such as VBScript and PerlScript (yes indeed!) To use these attributes pass a HASH reference in the -script parameter containing one or more of the keys language, src, or code. Here's how to refer to an external script URL:
            print $q->start_html(-title=>'The Riddle of the Sphinx',
          -script=>{-language=>'JavaScript',
          -src=>'/javascript/sphinx.js'}
          );
          
      Here's how to refer to scripting code incorporated directly into the page:
           print $q->start_html(-title=>'The Riddle of the Sphinx',
          -script=>{-language=>'PerlScript',
          -code=>'print "hello world!\n;"'}
          );
          
      A final feature allows you to incorporate multiple <SCRIPT> sections into the header. Just pass the list of script sections as an array reference. This allows you to specify different source files for different dialects of JavaScript. Example:
           print $q->start_html(-title=>'The Riddle of the Sphinx',
          -script=>[
          { -language => 'JavaScript1.0',
          -src      => '/javascript/utilities10.js'
          },
          { -language => 'JavaScript1.1',
          -src      => '/javascript/utilities11.js'
          },
          { -language => 'JavaScript1.2',
          -src      => '/javascript/utilities12.js'
          },
          { -language => 'JavaScript28.2',
          -src      => '/javascript/utilities219.js'
          }
          ]
          );
          
      (If this looks a bit extreme, take my advice and stick with straight CGI scripting.)

       

    • A -noScript parameter to pass some HTML that will be displayed in browsers that do not have JavaScript (or have JavaScript turned off).
    • -onLoad and -onUnload parameters to register JavaScript event handlers to be executed when the page generated by your script is opened and closed respectively. Example:
            print $query->start_html(-title=>'The Riddle of the Sphinx',
          -script=>$JSCRIPT,
          -onLoad=>'riddle_me_this()');
          
      See JavaScripting for more details.
    • Any additional attributes you want to incorporate into the <BODY> tag (as many as you like). This is a good way to incorporate other Netscape extensions, such as background color and wallpaper pattern. (The example above sets the page background to a vibrant blue.) You can use this feature to take advantage of new HTML features without waiting for a CGI.pm release.

    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 and HTML4 tags. 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.

    Unpaired Tags

    Unpaired tags include <P>, <HR> and <BR>. The syntax for creating them is:
       print $query->hr;
    
    This prints out the text "<hr>".

    Paired Tags

    Paired tags include <EM>, <I> and the like. The syntax for creating them is:
       print $query->em("What a silly art exhibit!");
    
    This prints out the text "<em>What a silly art exhibit!</em>".

    You can pass as many text arguments as you like: they'll be concatenated together with spaces. This allows you to create nested tags easily:

       print $query->h3("The",$query->em("silly"),"art exhibit");
    
    This creates the text:
       <h3>The <em>silly</em> art exhibit</h3>
    

    When used in conjunction with the import facility, the HTML shortcuts can make CGI scripts easier to read. For example:

       use CGI qw/:standard/;
    print h1("Road Guide"),
    ol(
    li(a({href=>"start.html"},"The beginning")),
    li(a({href=>"middle.html"},"The middle")),
    li(a({href=>"end.html"},"The end"))
    );
    

    Most HTML tags are represented as lowercase function calls. There are a few exceptions:

    1. The <tr> tag used to start a new table row conflicts with the perl translate function tr(). Use TR() or Tr() instead.
    2. The <param> tag used to pass parameters to an applet conflicts with CGI's own param() method. Use PARAM() instead.
    3. The <select> tag used to create selection lists conflicts with Perl's select() function. Use Select() instead.
    4. The <sub> tag used to create subscripts conflicts wit Perl's operator for creating subroutines. Use Sub() instead.

    Tags with Attributes

    To add attributes to an HTML tag, simply pass a reference to an associative array as the first argument. The keys and values of the associative array become the names and values of the attributes. For example, here's how to generate an <A> anchor link:
       use CGI qw/:standard/;
    print a({-href=>"bad_art.html"},"Jump to the silly exhibit");
    <A HREF="bad_art.html">Jump to the silly exhibit</A>
    
    You may dispense with the dashes in front of the attribute names if you prefer:
       print img {src=>'fred.gif',align=>'LEFT'};
    <IMG ALIGN="LEFT" SRC="fred.gif">
    
    Sometimes an HTML tag attribute has no argument. For example, ordered lists can be marked as COMPACT, or you wish to specify that a table has a border with <TABLE BORDER>. The syntax for this is an argument that that points to an undef string:
       print ol({compact=>undef},li('one'),li('two'),li('three'));
    
    Prior to CGI.pm version 2.41, providing an empty ('') string as an attribute argument was the same as providing undef. However, this has changed in order to accomodate those who want to create tags of the form <IMG ALT="">. The difference is shown in this table:
    CODE RESULT
    img({alt=>undef}) <IMG ALT>
    img({alt=>''}) <IMT ALT="">

    Distributive HTML Tags and Tables

    All HTML tags are distributive. If you give them an argument consisting of a reference to a list, the tag will be distributed across each element of the list. For example, here's one way to make an ordered list:
    print ul(
    li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']);
    );
    
    This example will result in HTML output that looks like this:
    <UL>
    <LI TYPE="disc">Sneezy</LI>
    <LI TYPE="disc">Doc</LI>
    <LI TYPE="disc">Sleepy</LI>
    <LI TYPE="disc">Happy</LI>
    </UL>
    
    You can take advantage of this to create HTML tables easily and naturally. Here is some code and the HTML it outputs:
    use CGI qw/:standard :html3/;
    print table({-border=>undef},
    caption(strong('When Should You Eat Your Vegetables?')),
    Tr({-align=>CENTER,-valign=>TOP},
    [
    th(['','Breakfast','Lunch','Dinner']),
    th('Tomatoes').td(['no','yes','yes']),
    th('Broccoli').td(['no','no','yes']),
    th('Onions').td(['yes','yes','yes'])
    ]
    )
    );
    
    When Should You Eat Your Vegetables?
      Breakfast Lunch Dinner
    Tomatoes no yes yes
    Broccoli no no yes
    Onions yes yes yes

    If you want to produce tables programatically, you can do it this way:

    use CGI qw/:standard :html3/;
    @values = (1..5);
    @headings = ('N','N'.sup('2'),'N'.sup('3'));
    @rows = th(\@headings);
    foreach $n (@values) {
    push(@rows,td([$n,$n**2,$n**3]));
    }
    print table({-border=>undef,-width=>'25%'},
    caption(b('Wow.  I can multiply!')),
    Tr(\@rows)
    );
    
    Wow. I can multiply!
    N N2 N3
    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    Table of contents

    Creating Forms

    General note 1. The various form-creating methods all return strings to the caller. These strings will contain the HTML code that will create the requested form element. You are responsible for actually printing out these strings. It's set up this way so that you can place formatting tags around the form elements.

    General note 2. The default values that you specify for the forms are only used the first time the script is invoked. If there are already values present in the query string, they are used, even if blank.

    If you want to change the value of a field from its previous value, you have two choices:

    1. call the param() method to set it.
    2. use the -override (alias -force) parameter. (This is a new feature in 2.15) This forces the default value to be used, regardless of the previous value of the field:
             print $query->textfield(-name=>'favorite_color',
          -default=>'red',
          -override=>1);
          
    If you want to reset all fields to their defaults, you can:
    1. Create a special defaults button using the defaults() method.
    2. Create a hypertext link that calls your script without any parameters.
    General note 3. You can put multiple forms on the same page if you wish. However, be warned that it isn't always easy to preserve state information for more than one form at a time. See advanced techniques for some hints.

    General note 4. By popular demand, the text and labels that you provide for form elements are escaped according to HTML rules. This means that you can safely use "<CLICK ME>" as the label for a button. However, this behavior may interfere with your ability to incorporate special HTML character sequences, such as &Aacute; (Á) into your fields. If you wish to turn off automatic escaping, call the autoEscape() method with a false value immediately after creating the CGI object:

         $query = new CGI;
    $query->autoEscape(0);
    
    You can turn autoescaping back on at any time with $query->autoEscape(1)

    General note 5. Some of the form-element generating methods return multiple tags. In a scalar context, the tags will be concatenated together with spaces, or whatever is the current value of the $" global. In a list context, the methods will return a list of elements, allowing you to modify them if you wish. Usually you will not notice this behavior, but beware of this:

        printf("%s\n",$query->end_form())
    
    end_form() produces several tags, and only the first of them will be printed because the format only expects one value.

     

    Form Elements

  • Opening a form
  • Text entry fields
  • Big text entry fields
  • Password fields
  • File upload fields
  • Popup menus
  • Scrolling lists
  • Checkbox groups
  • Individual checkboxes
  • Radio button groups
  • Submission buttons
  • Reset buttons
  • Reset to defaults button
  • Hidden fields
  • Clickable Images
  • JavaScript Buttons
  • Autoescaping HTML
  • Up to table of contents

    Creating An Isindex Tag

       print $query->isindex($action);
    
    isindex() without any arguments returns an <ISINDEX> tag that designates your script as the URL to call. If you want the browser to call a different URL to handle the search, pass isindex() the URL you want to be called.

    Starting And Ending A Form

       print $query->startform($method,$action,$encoding);
    ...various form stuff...
    print $query->endform;
    
    startform() will return a <FORM> tag with the optional method, action and form encoding that you specify. endform() returns a </FORM> tag.

    The form encoding supports the "file upload" feature of Netscape 2.0 (and higher) and Internet Explorer 4.0 (and higher). The form encoding tells the browser how to package up the contents of the form in order to transmit it across the Internet. There are two types of encoding that you can specify:

    application/x-www-form-urlencoded
    This is the type of encoding used by all browsers prior to Netscape 2.0. It is compatible with many CGI scripts and is suitable for short fields containing text data. For your convenience, CGI.pm stores the name of this encoding type in $CGI::URL_ENCODED.
    multipart/form-data
    This is the newer type of encoding introduced by Netscape 2.0. It is suitable for forms that contain very large fields or that are intended for transferring binary data. Most importantly, it enables the "file upload" feature of Netscape 2.0 forms. For your convenience, CGI.pm stores the name of this encoding type in CGI::MULTIPART()

    Forms that use this type of encoding are not easily interpreted by CGI scripts unless they use CGI.pm or another library that knows how to handle them. Unless you are using the file upload feature, there's no particular reason to use this type of encoding.

    For compatability, the startform() method uses the older form of encoding by default. If you want to use the newer form

    鲜花

    握手

    雷人

    路过

    鸡蛋
    该文章已有0人参与评论

    请发表评论

    全部评论

    专题导读
    上一篇:
    WindowsMyeclipse10安装Perl插件发布时间:2022-07-22
    下一篇:
    把perl脚本编译成exe发布时间:2022-07-22
    热门推荐
    热门话题
    阅读排行榜

    扫描微信二维码

    查看手机版网站

    随时了解更新最新资讯

    139-2527-9053

    在线客服(服务时间 9:00~18:00)

    在线QQ客服
    地址:深圳市南山区西丽大学城创智工业园
    电邮:jeky_zhao#qq.com
    移动电话:139-2527-9053

    Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap