Docstoc

Perl_07_Introduction to CGI

Document Sample
Perl_07_Introduction to CGI Powered By Docstoc
					         Chapter 7 - Introduction to Common
              Gateway Interface (CGI)
        Outline
        7.1            Introduction
        7.2            A Simple HTTP Transaction
        7.3            A Simple CGI Script
        7.4            Using CGI.pm to Generate HTML
        7.5            Sending Input to a CGI Script
        7.6            Using HTML Forms to Send Input
        7.7            Using CGI.pm to Create forms and Read Input
        7.8            Other Headers
        7.9            Example: An Interactive Portal
        7.10           Internet and World Wide Web Resources




 2001 Prentice Hall, Inc. All rights reserved.
1   #!/usr/bin/perl                                                                               Outline
2   # Fig 7.2: fig07_02.pl
3   # Displays the current date and time in a Web browser.
4
                                         The use warnings statement warns the user of
                                       The statement use strict forces the programmer to
5   use warnings;
                                                                   HTTP variables
                                       declare all typos, the as package header. variables and
                                         possible variables use of uninitialized or lexically
6   use strict;
7
                                         other potential
                                       scoped variables.problems in the code.
8   print "Content-type: text/html\n\n";
9   print "<html><head><title>Current date and time</title>";
10 print "</head>\n<body>";
11 print scalar( localtime() );
                                                                   Until now, the output of print has always
                                                                Built-in function localtime, when evaluated
12 print "</body></html>";                                         scalar context, on the screen. However,
                                                                in been displayedreturns a string which, in this
                                                                case, is output directly to the screen by print.
                                                                   technically speaking,         default target for
                                                                   print is standard output. When a Perl
                                                                   program is executed as a CGI script, the
                                                                   standard output is redirected to the client
                                                                   Web browser.




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                             Outline
 2   # Fig. 7.4: fig07_04.pl
 3   # Program to display CGI environment variables.
 4
 5   use warnings;                                The use statement directs the Perl interpreter to include a set
 6   use strict;                                  of functions from the CGI.pm module. This standard function
 7   use CGI qw( :standard );                     set is designated by the import tag :standard.
 8
 9   print header(), start_html( "Environment Variables" );
10
11   print '<table border = "0" cellspacing = "2">';            When the function is called with a
12                                                                                   the argument is
                                                                single argument,program to
13   foreach my $variable ( sort( keys %ENV ) ) {           Function start_html returnsprint the
                                                                Directs the Perl                   a string
                                                                HTTP header using the <title> tags an
                                                                embedded between function header from
                                                            containing the standard opening tags of
14      print Tr( td( b( "$variable:" ) ),
                                                                of the returned string to give the Web
15                  td( i( $ENV{ $variable } ) ) );         HTML CGI library.
                                                                the document (<html>, <head>,
                                                                page a name, which is displayed in the
16   }                                                      <title>, etc., up to the opening <body>
17
                                                                browser’s title bar.
                                                            tag). table in which the data will be
18   print '</table>', end_html();
                                               Begins hash is a built-in hashtable in Perl that contains the
                                            The %ENV the HTML
                                               displayed.
                                            names and values of all the environment variables.
             Function Tr returns a string containing the opening <tr>
             (table row) tag theactual second beofend_html %ENV,table the final opening
      The foreach loop TheIn the closing </tr> tag in of output isthe value of the
                                                     the keys
                           iterates through each output to the cell simply the
                                        text to argument wecreate a
                      close and table argument
                 We lexically The first and call calls function td to generate the
      sorting them              first.                           to generate
                                              variable, $ENV{ followed by colon
                           name of the environment variable, $variablea}, italicized
                 </body> Tr takes two arguments, each of which
                               environment<td> (table data) tags around each cell of the table
             row. Function and </html> tags.
                               and closing
                           ("$variable:"). generated by function i within a table
                               (with <i> tags thus, the table is output
             represent one cell in the table row; contains the output of the b function, which
                               column. Each cell
                               generates td).
                               cell
             with two columns. (using<b> (bold) tags around text to be output in bold type.




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                  Outline
 2   # Fig. 7.5: fig07_05.pl
 3   # An example of using QUERY_STRING.     The QUERY_STRING variable contains extra
 4
                                             information that is appended to a URL in a
 5   use warnings;
                                             of QUERY_STRING is placed into variable
                                   The value GET request, following a question mark (?).
 6   use strict;
                                  $query.
 7   use CGI qw( :standard );              We test to see if $query is empty. If so, we
 8                                         print a message instructing the user to add a
 9   my $query = $ENV{ "QUERY_STRING" };
                                           query string to the URL.
10
11   print header(), start_html( "QUERY_STRING example" );
12   print h2( "Name/Value Pairs" );
13
14   if ( $query eq "" ) {
15      print 'Please add some name-value pairs to the URL above. ';
16       print 'Or try <a href = "fig07_05.pl?name=Joe&age=29">this</a>.';

17   }
18   else {
19      print i( "The query string is '$query'." ), br();
20
21       my @pairs = split( "&", $query );
                                                       To break apart each of these resulting name–
22
                                                       value pairs, we use a foreach loop that
23       foreach my $pair ( @pairs ) {                 iterates through each $pair in turn.
24          my ( $name, $value ) = split( "=", $pair );
25          print "You set '$name' to value '$value'.", br();
26       }
27   }                                                 We call split to break the pair at the equals
28                                                    sign into a $name and a $value.
29 print end_html();
 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
              Ta g na m e            type            De sc rip tio n
                                     a tt rib ut e
                                     (fo r input
                                     ta g s)
              <input>                text            Provides a single-line text field for text input. This tag is the default
                                                     input type.
                                     password        Like text, but each character typed by the user appears as an
                                                     asterisk (*) to hide the input for security.
                                     checkbox        Displays a checkbox that can be checked (true) or unchecked (false).

                                     radio           Radio buttons are like checkboxes, except that only one radio button
                                                     in a group of radio buttons can be selected at a time.

                                     button          A standard push button.
                                     submit          A push button that submits form data according to the form’s
                                                     action.
                                     image           The same as submit, but displays on image rather than a button.

                                     reset           A button that resets form fields to their default values.
                                     file            Displays a text field and button that allow the user to specify a file to
                                                     upload to a Web server. The button displays a file dialog box that
                                                     allows the user to select the file.
                                     hidden          Allows hidden form data that can be used by the form handler on the
                                                     server.
              <select>                               Drop-down menu or selection box. This tag is used with the
                                                     <option> tag to specify options to select.
              <textarea>                             This is a multiline area in which text can be input or displayed.

               Fig. 7.6       HTML form elements.


 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                             Outline
2    # Fig 7.7: fig07_07.pl
3    # Demonstrates GET method with HTML form.
4                                                   During the second execution of the script, when the
5    use warnings;                                  query string is decoded, value word is assigned to
6    use strict;                                    variable $name and the user’s favorite word is
7    use CGI qw( :standard );                       assigned to variable $value.
8
9    our ( $name, $value ) = split( '=', $ENV{ QUERY_STRING } );
10
11 print header(), start_html( 'Using GET with forms' );                        The form contains two input
12 print p( 'Enter one of your favorite words here: ' );                        fields. The first is a single-line
13                                                                              text field (type = "text")
14 print '<form method = "GET" action = "fig07_07.pl">';                        with the name word. The
15 print '<input type = "text" name = "word">';                                 second displays a button, labeled
16 print '<input type = "submit" value = "Submit word">';                       Submit word, to submit the
17 print '</form>';                                                             form data.
18
                                                                                 The form is output with
19 if ( $name eq 'word' ) {
                                                                                 the <form> tags. Notice
20      print p( 'Your word is: ', b(             $value ) );
                                                                                 that the method attribute
21 }
22
                                                                                 is GET and the action
23 print end_html();                                                             attribute is the name of a
                                                                                 file, in of the the file is
                                                   Also during the second execution this case script, the
                                                  conditional statement is true and the word outputs to the
                                                                                 fig07_07.pl.
                                                  screen.


 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                          Outline
2    # Fig 7.8: fig07_08.pl
3    # Demonstrates POST method with HTML form.
4
5    use warnings;                            Function read is used to read in exactly that many characters
6    use strict;                              from The POST method sets the environment characters in the
                                                    standard input (STDIN) and store the variable
7    use CGI qw( :standard );
                                                   CONTENT_LENGTH, to indicate the number of
                                              $data variable.
8                                                  characters of data that were sent (or posted).
9    our ( $data, $name, $value );
10
11   read( STDIN, $data, $ENV{ 'CONTENT_LENGTH' } );
12   ( $name, $value ) = split( '=', $data );
13
14   print header(), start_html( 'Using POST with forms' );
15   print p( 'Enter one of your favorite words here: ' );
16
17   print   '<form method = "POST" action = "fig07_08.pl">';
18   print   '<input type = "text" name = "word">';
19   print   '<input type = "submit" value = "Submit word">';
20   print   '</form>';
21
22   if ( $name eq 'word' ) {
23    print p( 'Your word is: ', b( $value ) );
24 }
25
26 print end_html();



 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                        Outline
2    # Fig 7.9: fig07_09.pl
3    # Demonstrates use of CGI.pm with HTML form.
4
5    use warnings;                                Function param takes one argument: the name of an
6    use strict;                                  HTML form field. If form data containing a name–value
7    use CGI qw( :standard );                     pair with the given name (in this case, word) were
8                                                 submitted, then the name’s associated value would be
9    my $word = param( "word" );                Function start_form generates theundef. <form> tag.
                                                  returned. Otherwise, param returns opening
10
                                               When no arguments are given, start_form defaults to the
11 print header(), start_html(
                                               POST method.
                                              'Using CGI.pm with forms' );
12 print p( 'Enter one of your favorite words here: ' );
13
14 print start_form(), textfield( "word" );
                                                                     Function textfield generates HTML
15 print submit( "Submit word" ), end_form();                        to create an <input> single-line form
16                                                                   element with the name word.
17 print p( 'Your word is: ', b( $word ) ) if $word;
18 print end_html();

                         submit creates a submit button with
               FunctionFunction end_form prints the closing form tag, </form>.
                  given an if structure to word) the label.
               theWe useargument (Submit execute as a print statement only if $word
                  was assigned a value from function param.




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
 1   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">                   Outline
 2   <!-- Fig. 7.10: fig07_10.html -->
 3
 4   <html><head><title>Enter here</title></head>
 5
 6   <body>
 7   <h1>Welcome to Deitel Travel!</h1>
 8
 9   <form method = "POST"
10         action = "http://localhost/cgi-bin/fig07_11.pl">
11
12   Please enter your name:<br/>                   Field to collect client’s name.
13   <input type = "text" name = "name"><br/>
14
15   Members, please enter the password:<br/>
16   <input type = "password" name = "password"><br/>
17
                                                              Field to collect member’s password.
18   <font size = "-1">
19   <i>Note that password is not encrypted.</i><br/><br/>
20
21   <input type = "submit">
22   </form>
23
24   </body></html>




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!perl                                                                             Outline
 2   # Fig. 7.11: fig07_11.pl
 3   # Handles entry to Deitel Travel
 4
 5   use warnings;
 6   use strict;
 7   use CGI qw( :standard );
 8
 9   print redirect( "/fig07_10.html" ) unless param( "name" );
10
11   my $name = param( "name" );                        We assign the form-field values to variables
12   my $password = param( "password" );                $name and $password.
13                                                         Checks if any data were posted for the
                                                                                to function param.
                                                           name field using print personal
14   print   header(), start_html( "Deitel Travel" ),     The use $nameweekly aspecials are
                                                             We current
15           h1( "Welcome, $name!" );                      Unless data have been
                                                          displayed. for the client.posted, the client
                                                             greeting
16                                                         is redirected to the portal page
                                                                              If the member password
17   print   "Here are our weekly specials:", br(),
18            ul( li( "Boston to Taiwan for \$300" ) );
                                                                              is correct, additional
19                                                                            specials are output.
20   if ( $password eq "Coast2coast" ) {
21      print hr(), "Current specials just for members:", br(),
22            ul( li( "San Diego to Hong Kong for \$250" ) );
                                                                           If the password is not
23   }
                                                                           correct and the client
24   elsif ( $password ne "" ) {
25      print i( "Sorry, you entered the wrong password.",
                                                                           submitted anything other
26               "If you have the correct password, enter",                than the empty string, the
27               "it to see more specials." );                             client is informed that the
28   }                                                                     password was invalid.

 2001 Prentice Hall, Inc. All rights reserved.
29 else {                                                                                      Outline
30      print i( "Become a member today for more great deals!" );
31 }
32
                                                  If no password was entered, a message promoting the benefits
33 print hr(), end_html();
                                                  of membership is output.




 2001 Prentice Hall, Inc. All rights reserved.
                                                  Outline




 2001 Prentice Hall, Inc. All rights reserved.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:2/10/2012
language:
pages:20