Lecture 7 Introduction to CGI and Perl by ekc11009

VIEWS: 70 PAGES: 53

									 Lecture 7: Introduction to CGI and Perl
  Web Architecture & Web server
  CGI Common Gateway Interface
  examples of server-side programming
     Perl
            •   Data types
            •   String processing
            •   Client-server environment variables
            •   Form Processing & Business Logic
          SSI



INE1020: Introduction to Internet Engineering         4: Web Architecture   1
 1. Web Architecture
  Three-tier architecture:
     Presentation: clients contains both the presentation and
      application logic components.
     Content: web server provides interactive view of information
      from a data store.
     Data and service level: provides data for the web server.



                   HTTP request

                                     Internet                       Database
                   HTTP response                                     server
      Client computers
     with web browsers                          Web server

                                                                    Data and service
       Presentation level                       Content level
                                                                          level



INE1020: Introduction to Internet Engineering                   4: Web Architecture    2
 1. Web Architecture
  Multi-tier architecture:
    Application-level or middleware: has an application server,
     which is used to find requested data and services, makes
     them available for viewing, and carries out transactions.
    Data and service level: has a variety of data and services
     accessible by the application server.


                                                                                  Database
              HTTP request                                                         server

                               Internet
              HTTP response
                                                                                    Billing
  Client computers                                                                  system
      with web                                  Web server      Application
      browsers                                                    server
                                                                                    Data and
     Presentation                               Content level   Application
                                                                                  service level
         level                                                    level
INE1020: Introduction to Internet Engineering                         4: Web Architecture         3
 1. Web Server
  A web server is a network server that manages
     access to files, folders and other resources over
     Internet or local Intranet via HTTP
          Handle permissions
          Execute programs
          Keep track of directories and files
          Communicate with client computers
  A web server consists of a computer with:
     a suitable operating system
     a suitable file system
     a network connection
     web server software – which accepts requests from
      browsers such as IE and Netscape

INE1020: Introduction to Internet Engineering    4: Web Architecture   4
 1. Examples of Web Server Software


    Microsoft Personal Web Server
     Microsoft Internet Information Server
    W3C Jigsaw Web Server
          http://jigsaw.w3.org/Distrib/

    Apache:
      • http://Apache-Server.Com/tutorials/




INE1020: Introduction to Internet Engineering   4: Web Architecture   5
2. CGI
 Server-side technologies such as CGI(Common Gateway Interface) ,
  SSI(Server Side Include) and ASPs (Active Server pages)
 CGI:.
    is a standard for interfacing external applications with web
     servers.
    extends Web server's functionality through outside scripts or
     compiled programs.
 Data path of a typical CGI-based application




INE1020: Introduction to Internet Engineering       4: Web Architecture   6
 2. CGI
  Web browser
    Take info from user
            • typically http://www.mydomain.com/cgi-bin/<program name>
          Using HTTP, sends info to a Web server
          Server-side CGI program executed
          Standard output from server-side applications or scripts
           redirected or piped to CGI
          Output sent from CGI over the Internet to the client
           browser for rendering
  CGI is an interface
     Cannot be directly programmed
     Script or executable program must be used to interact with
      it

INE1020: Introduction to Internet Engineering         4: Web Architecture   7
 2. CGI
  CGI programs can be written in any language,
   e.g. C/C++, Fortran, Perl, TCL, any Unix shell,
   Visual Basic
  CGI programs need to reside in a special
   directory, so that the Web server knows to
   execute the program rather than just display
   it to the browser.
          typically resides in /cgi-bin directory.
  Within Web server
    Permission needs to be granted by Web master to
     allow specific programs to be executed on the
     server

INE1020: Introduction to Internet Engineering   4: Web Architecture   8
 3. Perl
  Perl: Practical Extraction and Report Language
     High-level programming language
     Developed by Larry Wall in 1987
     Rich, easy-to-use text-processing capabilities
     Alternative to the terse and strict C programming language
     Powerful alternative to UNIX shell scripts
     To check current version: type “perl –v” (in UNIX)
     Logical choice for programming the server side of
      interactive Web-based applications
            • Most popular language for doing so today
          Is continuously corrected and evolved by the online Perl
           community
            • Stays competitive with newer server-side technologies

INE1020: Introduction to Internet Engineering            4: Web Architecture   9
 3. Perl
  Perl initially developed for UNIX platform
     Always intended to be a cross-platform computer language

    ActivePerl
          Version of Perl for Windows
          Free download at http://www.activestate.com
          Includes the core Perl package
            • Predefined functionality expected to behave the same across
              all platforms
            • Perl Interpreter - perl.exe – placed in bin directory
                 – Loaded into memory each time Perl program invoked
          Extension of Perl programs is .pl
            • Associated with Perl interpreter by default
  Perl program execution
     Type perl followed by filename of Perl source code at
      command line (DOS prompt)
INE1020: Introduction to Internet Engineering           4: Web Architecture   10
 3. Perl
    Comment Character - #
          Goes at beginning of every line with comment
  Function print
          Outputs text indicated by quotation marks (“…”)
  Escape sequence \n
          When inside a string, moves cursor to next line
  Statements terminated with semicolons (;)
     Exception: where braces ({}) used to denote block of code

       1   # Fig. 27.4: first.pl
       2   # A first program in Perl.
       3
       4   print "Welcome to Perl!\n";


      Welcome to Perl!


INE1020: Introduction to Internet Engineering        4: Web Architecture   11
 3.1. Perl Data Types
  Perl contains set of data types
     Represent different kinds of information
     Each variable name has special character preceding it
            • $ - variable contains scalar value
                – Strings, integer numbers and floating-point numbers
            • @ - indexed array
                – Uses an integer (called an index) to reference array elements
                – An ordered list of scalar variables that can be accessed using integer
                   indices
            • % - hash
                – Uses keys that are strings to reference individual array elements
                – An unordered set of scalar variables whose values are accessed using
                   unique scalar values (ie, strings) called keys.
         Variables do not have to be initialized before being used
  Variable names in strings
         Serve as place-holders for values they represent
         If have no declared value – set to null (empty) value
INE1020: Introduction to Internet Engineering                    4: Web Architecture   12
 3.1. Perl Data Types
  Example: to demonstrate scalar variables
       # Program to illustrate the use of scalar variables.

       $number = 5;
       print( "The value of variable \$number is: $number\n\n" );

       $number += 5;
       print( "Variable \$number after adding 5 is: $number\n" );

       $number *= 2;
       print( "Variable \$number after multiplying by 2 is: " );
       print( "$number\n\n\n" );

       The value of variable $number is: 5
       Variable $number after adding 5 is: 10
       Variable $number after multiplying by 2 is: 20




INE1020: Introduction to Internet Engineering            4: Web Architecture   13
 3.1. Perl Data Types
   •Example: to demonstrate uninitialized variables
  # using an uninitialized variable in the context of a string
  print( "Using a variable before initializing: $variable\n\n" );
  # using an uninitialized variable in a numeric context
  $test = $undefined + 5;
  print( "Adding uninitialized variable \$undefined " );
  print( "to 5 yields: $test\n" );

 Using a variable before initializing:
 Adding uninitialized variable $undefined to 5 yields: 5


  •uninitialized variables have the value undef
  •Undef is evaluated to different values depending on variable‟s context
  •Numeric context, undef evaluates to 0
  •String context, undef evaluates to “”

INE1020: Introduction to Internet Engineering          4: Web Architecture   14
3.1. Perl Data Types
    •Example: adding strings and numeric variables
#using strings in numeric context
$string = "A string value";
$number = 1;
$number += $string;
print("Adding a string to an integer : \n");
print(" \$number = \$number + \$string = $number \n");


$string2 = "15charactersand1";
$number2 = $number + $string2;
print("Adding a string with numbers in the beginning of the string\n ");
print("\$number2 = \$number + \$string2 = $number2\n\n");
print("evaluating a string in numeric context does not");
print(" the value of the string, \n \"$string2\" yields: ");
print("$string2\n");


INE1020: Introduction to Internet Engineering            4: Web Architecture   15
 3.1. Perl Data Types


 Adding a string to an integer :
 $number = $number + $string = 1
 Adding a string with numbers in the beginning of the string
 $number2 = $number + $string2 = 16

 evaluating a string in numeric context does not the value of the
    string,
  "15charactersand1" yields: 15charactersand1




INE1020: Introduction to Internet Engineering     4: Web Architecture   16
 3.1. Perl Data Types
  Perl can store arrays
  Array definition
    @arrayName = (“element1”, “element2”, …, “elementN”);
  Elements are referenced as scalar values with
     element number in square brackets ([])
          @ refers to array as a whole, $ refers to elements
          First array element is [0]
          e.g. $array[2]refers to the third element in @array
  Range Operator – “..”
          Used to store all values between given arguments
          e.g. @array2 = (A..Z);
            • Creates array @array2 containing all capital letters in alphabet
              (all letters between A and Z)
INE1020: Introduction to Internet Engineering            4: Web Architecture   17
 3.1. Perl Data Types
  Example: to demonstrate arrays
       # Program to demonstrate arrays in Perl

       @array = ("Bill", "Bobby", "Sue", "Michelle");
       print "The array contains:\n\n";
       print "@array \n\n";
       print "Third element: $array[2]\n\n";

       @array2 = (A..Z);
       print "The range operator is used to store all\n";
       print "letters from capital A to Z:\n\n";
       print "@array2 \n";

       The array contains:

       Bill Bobby Sue Michelle

       Third element: Sue

       The range operator is used to store all
       letters from capital A to Z:

       A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

INE1020: Introduction to Internet Engineering                4: Web Architecture   18
 3.1. Perl Data Types
 •$array3[ 3 ] = "4th";
 •print( "Array with just one element initialized: @array3 \n\n" );
 •print( 'Printing literal using single quotes: ' );
 •print( '@array and \n', "\n" );
 •print( "Printing literal using backslashes: " );
 •print( "\@array and \\n\n" );


  • Array with just one element initialized:     4th
  • Printing literal using single quotes: @array and \n
  • Printing literal using backslashes: @array and \n

 • uninitialized elements of an array take the value undef
 • Eg, array3[0] = array3[1] = array3[2] = “ “ (empty string)
 • 3 spaces printed before printing “4th”
 • Perl interpreter interprets strings inside single quotes literally, eg „@array‟
 • use back slash to escape special characters, eg \@

INE1020: Introduction to Internet Engineering                         4: Web Architecture   19
 3.2. Perl String Processing
  Processing textual data easily and efficiently
     One of Perl‟s most powerful capabilities
     Usually done through use of regular expressions
            • Patterns of characters used to search through text files and
              databases
            • Allows large amounts of text to be searched using relatively
              simple expressions
  eq equality operator
          Tests whether two strings are equivalent
          eg. if ($hello eq “Good Morning”)…
  Keyword my
          Indicates designated variable only valid for block of code in
           which it is declared

INE1020: Introduction to Internet Engineering           4: Web Architecture   20
 3.2. Perl String Processing
  Example: to demonstrate string processing
       my $stringa = "Test";
       my $stringb = "Testing";

       if ($stringa eq "Test"){
          print "$stringa matches Test.\n";
       }
       else {
          print "$stringa does not match Test.\n";
       }

       if ($stringb eq "Test") {
          print "$stringb matches Test.\n";
       }
       else {
          print "$stringb does not match Test.\n";
       }


      Test matches Test.
      Testing does not match Test.


INE1020: Introduction to Internet Engineering        4: Web Architecture   21
    3.2 Perl String Processing
# Program to demonstrate the eq, ne, lt, gt operators.
@fruits = qw( apple orange banana ); # qw means quote word
foreach $item ( @fruits ) {
         if ( $item eq "banana" ) {
             print( "String '$item' matches string 'banana'\n" ); }
         if ( $item ne "banana" ) {
             print( "String '$item' does not match string 'banana'\n" );}
         if ( $item lt "banana" ) {
             print( "String '$item' is less than string 'banana'\n" );}
         if ( $item gt "banana" ) {
             print( "String '$item' is greater than string 'banana'\n" );}
}

        •String 'apple' does not match string 'banana'
        •String 'apple' is less than string 'banana'
        •String 'orange' does not match string 'banana'
        •String 'orange' is greater than string 'banana'
        •String 'banana' matches string 'banana'
INE1020: Introduction to Internet Engineering              4: Web Architecture   22
 3.2 Perl String Processing
 •# Searches using the matching operator and regular expressions.

 $search = "Now is is the time";
 print( "Test string is: '$search'\n\n" );

 if ( $search =~ /Now/ ) {
   print( "String 'Now' was found.\n" );}

 if ( $search =~ /^Now/ ) {
   print( "String 'Now' was found at the beginning of the line." );
   print( "\n" );}

 if ( $search =~ /Now$/ ) {
   print( "String 'Now' was found at the end of the line.\n" );}

 if ( $search =~ /\b ( \w+ ow ) \b/x ) {
   print( "Word found ending in 'ow': $1 \n" );}

 if ( $search =~ /\b ( \w+ ) \s ( \1 ) \b/x ) {
   print( "Repeated words found: $1 $2\n" );}

 @matches = ( $search =~ / \b ( t \w+ ) \b /gx );
 print( "Words beginning with 't' found: @matches\n" );
INE1020: Introduction to Internet Engineering                         4: Web Architecture   23
 3.2 Perl String Processing
 •Test string is: 'Now is is the time'


 •String 'Now' was found.
 •String 'Now' was found at the beginning of the line.
 •Word found ending in 'ow': Now
 •Repeated words found: is is
 •Words beginning with 't' found: the time

  •\w+ ow - indicates searching for pattern ending with “ow”
  • \b \b - word boudary
  • match result(s) stored in special Perl variables, eg, $1, $2, $3
  • x – indicates that whitespace in the regular expression are to be ignored
  eg, If the expression $search =~ /\b ( \w+ ow ) \b/
  then the script will search for
            • a word boundary,
            • 2 spaces,
            • one or more alphanumeric characters,
            • one space, the characters ow,
            • 2 spaces
            • word boundary.
INE1020: Introduction to Internet Engineering            4: Web Architecture   24
 3.3. Perl Packages
  In addition to core Perl package
          Add-ons called packages provide additional
           functionality
  The packages can be including using „use‟
   command
  Packages
        Often provide platform specific features
        Are available free of charge at
         http://www.activestate.com/packages



INE1020: Introduction to Internet Engineering   4: Web Architecture   25
 3.3. Perl Samples: Viewing Client/Server
 Environment Variables
  Knowing info about client very useful to system
     administrators
    CGI environment variables
          Contains info about client
            • Version of CGI server running
            • HTTP host, HTTP connection
            • Much more
          Note: In the following Perl example for Client/server
           environment variables, the purpose is to demonstrate how
           one can access the environment variables. The intention is
           not to study each and every of the environment variables.
  Use statement
          Allows inclusion of predefined library packages in programs

INE1020: Introduction to Internet Engineering        4: Web Architecture   26
 3.3 Perl Samples: Viewing Client/Server
 Environment Variables
    CGI Library
          Included to provide functionality that makes it easier to write
           HTML sent to Web browser
          Contains keywords that represent HTML tags
  foreach            loop
        Iterates through keys in given hashtable, performs indicated
         actions
       foreach $key (sort keys %ENV)
        Iterates through %ENV hashtable
          • Built-in table in Perl that contains names and values of all CGI
             environment variables
        sort function
          • returns list in alphabetical order
        Assigns current key to $key and performs indicated actions


INE1020: Introduction to Internet Engineering             4: Web Architecture   27
 3.3 Perl Samples: Viewing Client/Server
 Environment Variables           Line 2:
                                                   use instruct Perl to
                                                  include the contents
 1 #!/usr/local/bin/perl                          of predefined
                                                  functions
 2 use CGI qw (:standard);
                                                  :standard – import a
 3                                                standard set of pre-
 4 $dtd =                                         defined functions

 5 "-//W3C//DTD XHTML 1.0 Transitional//EN\"      Line 4-7:
 6    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-   Change the default
                                                  document type
 7    transitional.dtd";
                                                  definition from
 8                                                HTML‟s DTD to the
                                                  value in $dtd
 9 print( header() );
                                                  Line 9:
                                                  Instruct Perl to
                                                  print a valid HTTP
                                                  header using the
                                                  header() function
INE1020: Introduction to Internet Engineering      4: Web Architecture     28
 3.3 Perl Samples: Viewing Client/Server
 Environment Variables      Line 10:
                                                         start_html() is a CGI
                                                        function that prints the
                                                        document type definition, and
                                                        the opening tags such as
                                                        <html>, <head>, <title>
  10 print( start_html( { dtd => $dtd,
                                                     Line 16:
  11       title => "Environment Variables..." } ) );
                                                     Tr() and th() are CGI
  12                                                 functions that place arguments
  13 print( "<table style = \"border: 0; padding: 2; between Table row and table
                                                     header tags (ref, p 923,
  14     font-weight: bold\">" );                    Deitel)
  15
                                                        Line 19:
  16 print( Tr( th( "Variable Name" ),
                                                        td() is a CGI function that
  17         th( "Value" ) ) );                         prints <td> tags
  18                                                    hr() is a CGI function that
                                                        prints a horizontal line and a
  19 print( Tr( td( hr() ), td( hr() ) ) );
                                                        line break above and below the
                                                        horizontal line
INE1020: Introduction to Internet Engineering                    4: Web Architecture     29
      3.3 Perl Samples: Viewing Client/Server
      Environment Variables         Line 20:
                                                               %ENV    hash is a built-in
                                                               table in Perl that contains the
20   foreach $variable ( sort( keys( %ENV ) ) ) {              names and values of all the
21                                                             environment variables
                                                               each element in a hash is
22    print( Tr( td( { style => "background-color: #11bbff" }, accessed using a unique string
23               $variable ),                                  key that is associated with
                                                               that element‟s value.
24           td( { style => "font-size: 12pt" },
                                                               keys() is a function that
25                  $ENV{ $variable } ) ) );                   returns an unordered array
                                                               containing all keys in %ENV
26
                                                               foreach iterates sequentially
27    print( Tr( td( hr() ), td( hr() ) ) );                   through the array returns by
28   }                                                         sort

29                                                            Line 24:
30 print( "</table>" );                                       hash values are accessed using
                                                              the syntax
31 print( end_html() );                                       $hashName{keyName}, eg,
                                                              $ENV{ $variable }
     INE1020: Introduction to Internet Engineering                   4: Web Architecture     30
 3.3 Perl Samples: Viewing Client/Server
 Environment Variables
  Script output:




INE1020: Introduction to Internet Engineering   4: Web Architecture   31
 3.4 Perl Samples: Form Processing and
 Business Logic
  Two parts:
     client side: HTML forms
     server side: CGI programs, e.g. Perl script

  HTML FORMs
       1. Allow users to enter data
       2. Data sent to Web server for processing
       3. Program processes data
        Allows users to interact with server
        Vital to electronic commerce

  FORM element
          Indicates what action should occur when user submits form
          Attribute: ACTION = “cgi-bin/form.pl”
            • Directs server to execute form.pl Perl script
INE1020: Introduction to Internet Engineering          4: Web Architecture   32
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<!-- Fig. 27.20: form.html -->                                       Line 17:
3
4<HTML>
                                                                       Open FORM
5<HEAD>                                                                Define FORM
6<TITLE>Sample FORM to take user input in HTML</TITLE>                attributes
7</HEAD>
8                                                                      Specify the action
9<BODY BACKGROUND = "images/back.gif">                                 IMG SRC specify the
10<BASEFONT FACE = "ARIAL,SANS-SERIF" SIZE = 2>                       path to display the
11                                                                    image
12   <FONT SIZE = +2>
13       <STRONG>This is a sample registation form.</STRONG>
14   </FONT><BR>                                                      Line 23-30:
15   Please fill in all fields and click Register.                     Define form INPUT
16
17   <FORM METHOD = "POST" ACTION = "/cgi-bin/form.pl">
                                                                      elements
18       <IMG SRC = "images/user.gif"><BR>                            TYPE = “text”
19       <FONT COLOR = BLUE>                                          inserts a one-line
20          Please fill out the fields below.<BR>
21       </FONT>
                                                                      text box
22                                                                    NAME provides a
23       <IMG SRC = "images/fname.gif">                               unique
24       <INPUT TYPE = "TEXT" NAME = "FNAME"><BR>
25       <IMG SRC = "images/lname.gif">
                                                                      identification for
26       <INPUT TYPE = "TEXT" NAME = "LNAME"><BR>                     INPUT element
27       <IMG SRC = "images/email.gif">
28       <INPUT TYPE = "TEXT" NAME = "EMAIL"><BR>
29       <IMG SRC = "images/phone.gif">                               Line 33:
30       <INPUT TYPE = "TEXT" NAME = "PHONE"><BR>                      Specify correct
31
32       <FONT SIZE=-2>
                                                                      input format
33          Must be in the form (555)555-5555<BR><BR>
    INE1020: Introduction to Internet Engineering                 4: Web Architecture   33
34       </FONT>
35
36      <IMG SRC = "images/downloads.gif"><BR>
37      <FONT COLOR = BLUE>
38         Which book would you like information about?<BR>
39      </FONT>
40
41      <SELECT NAME = "BOOK">
42         <OPTION>Internet and WWW How to Program
43         <OPTION>C++ How to Program 2e
44         <OPTION>Java How to Program 3e
45         <OPTION>Visual Basic How to Program 1e
46      </SELECT>
47      <BR><BR>
48
49      <IMG SRC = "images/os.gif"><BR>                                     Line 55-64:
50      <FONT COLOR = BLUE>
51         Which operating system are you                                   Radio buttons
52         currently using?<BR>
53      </FONT>                                                             –similar in
54                                                                          function and
55      <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows NT"
56      CHECKED>                                                            usage to
57      Windows NT                                                          checkboxes
58      <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 95">
59      Windows 95                                                          –Only one radio
60
61
        <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 98">
        Windows 98<BR>
                                                                            button in a
62      <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Linux">                  group can be
63      Linux                                                               selected
64      <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Other">
65      Other<BR>
66      <INPUT TYPE = "SUBMIT" VALUE = "Register">
67   </FORM>
    INE1020: Introduction to Internet Engineering                 4: Web Architecture   34
68</BODY>
69</HTML>
 3.4 Perl Samples: Form Processing and
 Business Logic
  Script Output:




INE1020: Introduction to Internet Engineering   4: Web Architecture   35
 3.4 Perl Samples: Form Processing and
 Business Logic
  CGI Scripts written in Perl:
     Retrieving data from form output
            • Assign to variables
            • Example: Assign data from form INPUT OS to variable $OS
                $os = param(OS);
          Testing for correct form input
            • Example: Make sure phone number in format (555)555-5555
                  if ( $phone =~ / \( \d{3} \) \d{3} - \d{4} /x) { actions }
            • d{n} tests for n digits
            • \ is escape character
                – Close-bracket (“)”) character is used in Perl statements, needs
                  escape character “\” to appear as part of search test string



INE1020: Introduction to Internet Engineering              4: Web Architecture   36
                                                                 Line 2:
1 #!/usr/local/bin/perl                                           Use (include)
                                                                 standard CGI library
2 use CGI qw (:standard);
3 $os = param( "os" );
                                                                 Line 3-8:
4 $firstName = param( "fname" );                                  Assign form field
5 $lastName = param( "lname" );                                  values to variables
                                                                 param() is part of
6 $email = param( "email" );                                     the Perl CGI module
7 $phone = param( "phone" );                                     that retrieves values
                                                                 from a form field‟s
8 $book = param( "book" );                                       value
9 $dtd =
10 "-//W3C//DTD XHTML 1.0 Transitional//EN\"
11 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
12 print( header() );
13 print( start_html( { dtd => $dtd,
14                title => "Form Results" } ) );




     INE1020: Introduction to Internet Engineering          4: Web Architecture   37
                                                                      Line 15:
15 if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) {               Test for correct
                                                                      phone number input
16 print( "Hi " );
                                                                      form using if
17 print( span( { style => "color: blue; font-weight: bold" },        structure
18              $firstName ) );                                        Indicate actions to
                                                                      be performed if test
19 print( "!" );                                                      returns TRUE result
20                                                                     check if phone no.
                                                                      has the format (555)-
21 print( "\nThank you for completing the survey." );
                                                                      555-5555
22 print( br(), "You have been added to the " );                      \d{3} means 3 digits
23                                                                    ^ & $ ensure that
                                                                      there are no extra
24 print( span( { style => "color: blue; font-weight: bold" },        characters in front or
25              $book ) );                                            at the end

26 print( " mailing list.", br(), br() );
                                                                      Line 22:
27                                                                     br() function adds a
28 print( span( { style => "font-weight: bold" },                     break (ie ,<BR/>)
                                                                      Line 24:
29             "The following information has
                                                                       span() function adds
30              been saved in our database: " ), br() );              a <span> tag

     INE1020: Introduction to Internet Engineering               4: Web Architecture   38
31 print( table(                                                Line 32:
32        Tr( th( { style => "background-color: #ee82ee" },      Tr() and th() are
                                                                CGI functions that
33               "Name" ),
                                                                place arguments
34           th( { style => "background-color: #9370db" },      between Table row
                                                                and table header tags
35               "E-mail" ),
                                                                (ref, p 923, Deitel)
36           th( { style => "background-color: #4169e1" },
37               "Phone" ),                                     Line 42:
38           th( { style => "background-color: #40e0d0" },      td() is a CGI
                                                                function that prints
39               "OS" ) ),                                      <td> tags
40
41       Tr( { style => "background-color: #c0c0c0" },
42           td( "$firstName $lastName" ),
43           td( $email ),
44           td( $phone ),
45           td( $os ) ) ) );



     INE1020: Introduction to Internet Engineering            4: Web Architecture   39
46 print( br() );
47 print( div( { style => "font-size: x-small" },                 Line 47:
48          "This is only a sample form. You have not been        div() is a CGI
                                                                  function that
49          added to a mailing list." ) );                        generates a <div> tag
50 }
                                                                  Line 51:
51 else {
                                                                   Set actions to be
52 print( div( { style => "color: red; font-size: x-large" },     performed if the if
53          "INVALID PHONE NUMBER" ), br() );                     structure returns a
                                                                  FALSE value
54 print( "A valid phone number must be in the form " );
55 print( span( { style => "font-weight: bold" },                 Line 51:
56              "(555)555-5555." ) );                             end_html() returns
                                                                  the closing tags for
57 print( div( { style => "color: blue" },                        the page (</body> and
58          "Click the Back button, and enter a                   </html>)
59           valid phone number and resubmit." ) );
60 print( br(), br() );
61 print( "Thank you." );}
62 print( end_html() );

     INE1020: Introduction to Internet Engineering              4: Web Architecture   40
 3.4 Perl Samples: Form Processing and
 Business Logic
  Script Output 1: If phone number is valid




INE1020: Introduction to Internet Engineering   4: Web Architecture   41
 3.4 Perl Samples: Form Processing and
 Business Logic
  Script Output 2: If phone number is invalid




INE1020: Introduction to Internet Engineering   4: Web Architecture   42
 4. SSI
  SSI: Server-Side Include
        Commands embedded in HTML documents
        Provide for content creation
        Allow inclusion of current time, date or even
         contents of different html document
        Cf. Original CGI is executed by client commands.
            • http://www.mydomain.com/cgi-bin/<program name>
            • With SSI, the commands to execute CGI programs are
              embedded in HTML scripts.




INE1020: Introduction to Internet Engineering    4: Web Architecture   43
 4. SSI
    SSI commands
          Execute CGI scripts on a server
          Are capable of connecting to an ODBC data source
            • Use to create customized Web pages depending for certain
              conditions
          Document containing SSI commands has .shtml file
           extension
  EXEC CGI             command
          Issued to execute a Perl script before document sent to
           client
            Example: <!-- #EXEC CGI=“cgi-bin/counter.pl” -->
          Executes the Perl script counter.pl, located in the cgi-
           bin directory


INE1020: Introduction to Internet Engineering         4: Web Architecture   44
 4. SSI
  ECHO        command
          Used to display variable information
          Is followed by the keyword VAR and variable‟s constant name
            Example: <!-- #ECHO VAR=“DATE_LOCAL” -->
          Returns the current local time
  Other variables
    DATE_GMT
            • Contains current Greenwich Mean Time
          DOCUMENT_NAME
            • Contains name of current document
          Many more



INE1020: Introduction to Internet Engineering        4: Web Architecture   45
 4. SSI Samples
  Common usage:
          For tracking clients:
            • Where client coming from
            • What client views on your site
            • Where client goes after your site
          Tracking Web data important, allows Web masters
           to
            • Know which sites visited most frequently
            • Know how effective advertisements and products are




INE1020: Introduction to Internet Engineering     4: Web Architecture   46
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<!-- Fig. 27.22 counter.shtml -->
3
4<HTML>
5   <HEAD>
6       <TITLE>Using Server Side Includes</TITLE>
7   </HEAD>
8                                                                      Line 14:
9<BODY>
10   <CENTER>                                                           Execute Perl
11       <H3> Using Server Side Includes</H3>                          script counter.pl
12   </CENTER>
                                                                       using EXEC CGI
13
14   <!-- #EXEC CGI="/cgi-bin/counter.pl" --><BR>                      statement
15   The Greenwich Mean Date is
16   <FONT COLOR = BLUE>
17                                                                     Line 18:
18   <!-- #ECHO VAR="DATE_GMT" -->.                                     Use ECHO VAR
                                                                       statements to
19   </FONT><BR>
20   The name of this document is
21   <FONT COLOR = BLUE>                                               display
22                                                                     environmental
23   <!-- #ECHO VAR="DOCUMENT_NAME" -->
                                                                       variables
24   </FONT><BR>
25   The local date is
26   <FONT COLOR = BLUE>
27
28   <!-- #ECHO VAR="DATE_LOCAL" -->
29   </FONT><BR>
30   This document was last modified on
    INE1020: Introduction to Internet Engineering                 4: Web Architecture   47
31   <FONT COLOR = BLUE>
32
33   <!-- #ECHO VAR="LAST_MODIFIED" -->
34   </FONT><BR>
35   Your current IP Address is
36   <FONT COLOR = BLUE>
37
38   <!-- #ECHO VAR="REMOTE_ADDR" -->
39   </FONT><BR>
40   My server name is                                          Continue printing
                                                               environmental
41   <FONT COLOR = BLUE>
42
43   <!-- #ECHO VAR="SERVER_NAME" -->                          variables using
44
45
     </FONT><BR>
     And I am using the
                                                               ECHO VAR
46   <FONT COLOR = BLUE>                                       statements
47
48   <!-- #ECHO VAR="SERVER_SOFTWARE" -->
49   Web Server.</FONT><BR>
50   You are using
51   <FONT COLOR = BLUE>
52
53   <!-- #ECHO VAR="HTTP_USER_AGENT" -->.
54   </FONT><BR>
55   This server is using <FONT COLOR = BLUE>
56
57   <!-- #ECHO VAR="GATEWAY_INTERFACE" -->.
58   </FONT><BR>
59   <BR><BR>
60   <CENTER>
61   <HR>
62   <FONT SIZE = -5>This document was last modified on
63
64   <!-- #ECHO VAR="LAST_MODIFIED" --></FONT>
65
66   </CENTER>
    INE1020: Introduction to Internet Engineering         4: Web Architecture    48
67</BODY>
68</HTML>
     4. SSI Samples
      The Perl Script: counter.pl
                                                                                   Line 5-8:
1 #!/usr/local/bin/perl                                                             Open counter.dat,
2 # Program to track the number of times a Web page has been accessed.             assign to filehandle
3 # counter.cgi                                                                    COUNTREAD
4 use CGI qw( :standard );                                                         <> read 1 line from file
5 open( COUNTREAD, "counter.dat" );                                                referred by filehandler
6 $data = <COUNTREAD>;                                                             COUNTEREAD
7 $data++;                                                                          Increment data in
8 close( COUNTREAD );                                                              COUNTREAD
                                                                                    Close COUNTREAD
9 open( COUNTWRITE, ">counter.dat" );
10 print( COUNTWRITE $data );
11 close( COUNTWRITE );                                                            Line 9-11:
12 print( header(), "<div style = \"text-align: center; font-weight: bold\">" );    > means write mode,
13 print( "You are visitor number", br() );                                        open counter.dat for
                                                                                   writing, referred to by
14   for ( $count = 0; $count < length( $data ); $count++ )                        filehandler
15    {                                                                            COUNTERWRITE
16   $number = substr( $data, $count, 1 );                                          print indicates the
17   print( img( { src => "$number.gif" } ), "\n" );                               filehandler
18   }                                                                             COUNTERWRITE where
                                                                                   data is written
19 print( "</div>" );


  INE1020: Introduction to Internet Engineering                             4: Web Architecture       49
 4. SSI Samples
  Perl script uses built-in functions:
     open() and close() function
            • to open and close a file
          print() function
            • to redirect output to a file
          substr( x, y, z ) function
            • Similar to JavaScript‟s substr function
            • First argument (x)
                – Specifies string from which to take a substring
            • Second argument (y)
                – Specifies offset in characters from beginning of the string
            • Third argument (z)
                  – Specifies length of substring to return


INE1020: Introduction to Internet Engineering                    4: Web Architecture   50
 4. SSI Samples
  Script output:




INE1020: Introduction to Internet Engineering   4: Web Architecture   51
 Further Readings

  Note: This topic is designed with the objective of
   providing an introduction to CGI, Perl and SSI.
  Advanced features of CGI, Perl and SSI are beyond
   the scope of this course and will NOT be taught or
   discussed. Students who wish to invest more time
   on studying advanced features and topics of CGI,
   Perl and SSI are referred to the following
   resources:

          Deitel Chapter 27
          http://hoohoo.ncsa.uiuc.edu/cgi/overview.html - CGI info
          http://hoohoo.ncsa.uiuc.edu/docs/tutorials/includes.html - SSI
           info

INE1020: Introduction to Internet Engineering            4: Web Architecture   52
 Further Readings

  Students who wish to invest more time on
     studying Web servers are referred to the
     following resources:

          Deitel Chapter 24
          Apache:
            • http://Apache-Server.Com/tutorials/




INE1020: Introduction to Internet Engineering       4: Web Architecture   53

								
To top