530 likes | 691 Views
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. Internet.
E N D
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 4: Web Architecture
Internet Client computers with web browsers Database server Web server HTTP request HTTP response Data and service level Content level Presentation level 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. 4: Web Architecture
Internet Database server Client computers with web browsers HTTP request Web server Billing system HTTP response Application server Data and service level Content level Application level Presentation level 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. 4: Web Architecture
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 4: Web Architecture
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/ 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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) 4: Web Architecture
1 # Fig. 27.4: first.pl 2 # A first program in Perl. 3 4 print "Welcome to Perl!\n"; 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 Welcome to Perl! 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 “” 4: Web Architecture
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"); 4: Web Architecture
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 4: Web Architecture
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) 4: Web Architecture
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 MichelleThird element: SueThe range operator is used to store allletters 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 4: Web Architecture
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 \@ 4: Web Architecture
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 4: Web Architecture
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. 4: Web Architecture
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' 4: Web Architecture
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" ); 4: Web Architecture
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. 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
3.3 Perl Samples: Viewing Client/Server Environment Variables Line 2: • useinstruct Perl to include the contents of predefined functions • :standard – import a standard set of pre-defined functions Line 4-7: • Change the default document type definition from HTML’s DTD to the value in $dtd Line 9: • Instruct Perl to print a valid HTTP header using theheader()function 1 #!/usr/local/bin/perl 2 use CGI qw (:standard); 3 4 $dtd = 5 "-//W3C//DTD XHTML 1.0 Transitional//EN\" 6 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1- 7 transitional.dtd"; 8 9 print( header() ); 4: Web Architecture
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> Line 16: • Tr() and th() are CGI functions that place arguments between Table row and table header tags (ref, p 923, Deitel) Line 19: • td() is a CGI function that prints <td> tags • hr() is a CGI function that prints a horizontal line and a line break above and below the horizontal line 10 print( start_html( { dtd => $dtd, 11 title => "Environment Variables..." } ) ); 12 13 print( "<table style = \"border: 0; padding: 2; 14 font-weight: bold\">" ); 15 16 print( Tr( th( "Variable Name" ), 17 th( "Value" ) ) ); 18 19 print( Tr( td( hr() ), td( hr() ) ) ); 4: Web Architecture
3.3 Perl Samples: Viewing Client/Server Environment Variables Line 20: • %ENVhash is a built-in table in Perl that contains the names and values of all the environment variables • each element in a hash is accessed using a unique string key that is associated with that element’s value. • keys()is a function that returns an unordered array containing all keys in %ENV • foreach iterates sequentially through the array returns by sort Line 24: hash values are accessed using the syntax $hashName{keyName}, eg, $ENV{ $variable } 20 foreach $variable ( sort( keys( %ENV ) ) ) { 21 22 print( Tr( td( { style => "background-color: #11bbff" }, 23 $variable ), 24 td( { style => "font-size: 12pt" }, 25 $ENV{ $variable } ) ) ); 26 27 print( Tr( td( hr() ), td( hr() ) ) ); 28 } 29 30 print( "</table>" ); 31 print( end_html() ); 4: Web Architecture
3.3 Perl Samples: Viewing Client/Server Environment Variables • Script output: 4: Web Architecture
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 4: Web Architecture
33Must be in the form (555)555-5555<BR><BR> 1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 34</FONT> 2<!-- Fig. 27.20: form.html --> 35 3 4<HTML> 5<HEAD> 6<TITLE>Sample FORM to take user input in HTML</TITLE> 7</HEAD> 8 9<BODY BACKGROUND = "images/back.gif"> 10<BASEFONT FACE = "ARIAL,SANS-SERIF" SIZE = 2> 11 12<FONT SIZE = +2> 13<STRONG>This is a sample registation form.</STRONG> 14</FONT><BR> 15 Please fill in all fields and click Register. 16 17<FORM METHOD = "POST" ACTION = "/cgi-bin/form.pl"> 18<IMG SRC = "images/user.gif"><BR> 19<FONT COLOR = BLUE> 20 Please fill out the fields below.<BR> 21</FONT> 22 23 <IMG SRC = "images/fname.gif"> 24 <INPUT TYPE = "TEXT" NAME = "FNAME"><BR> 25 <IMG SRC = "images/lname.gif"> 26 <INPUT TYPE = "TEXT" NAME = "LNAME"><BR> 27 <IMG SRC = "images/email.gif"> 28 <INPUT TYPE = "TEXT" NAME = "EMAIL"><BR> 29 <IMG SRC = "images/phone.gif"> 30 <INPUT TYPE = "TEXT" NAME = "PHONE"><BR> 31 32<FONT SIZE=-2> Line 17: Open FORM Define FORM attributes Specify the action IMG SRC specify the path to display the image Line 23-30: Define form INPUT elements TYPE = “text” inserts a one-line text box NAME provides a unique identification for INPUT element Line 33: Specify correct input format 4: Web Architecture
65 Other<BR> 66<INPUT TYPE = "SUBMIT" VALUE = "Register"> 67 </FORM> 68</BODY> 36<IMG SRC = "images/downloads.gif"><BR> 37<FONT COLOR = BLUE> 69</HTML> 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> 50 <FONT COLOR = BLUE> 51 Which operating system are you 52 currently using?<BR> 53 </FONT> 54 55 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows NT" 56CHECKED> 57 Windows NT 58 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 95"> 59 Windows 95 60 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 98"> 61 Windows 98<BR> 62<INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Linux"> 63 Linux 64<INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Other"> Line 55-64: Radio buttons • similar in function and usage to checkboxes • Only one radio button in a group can be selected 4: Web Architecture
3.4 Perl Samples: Form Processing and Business Logic • Script Output: 4: Web Architecture
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 INPUTOS 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 ndigits • \ is escape character • Close-bracket (“)”) character is used in Perl statements, needs escape character “\” to appear as part of search test string 4: Web Architecture
1 #!/usr/local/bin/perl 2 use CGI qw (:standard); 3 $os = param( "os" ); 4 $firstName = param( "fname" ); 5 $lastName = param( "lname" ); 6 $email = param( "email" ); 7 $phone = param( "phone" ); 8 $book = param( "book" ); 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" } ) ); Line 2: Use (include) standard CGI library Line 3-8: Assign form field values to variables param() is part of the Perl CGI module that retrieves values from a form field’s value 4: Web Architecture
15 if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) { 16 print( "Hi " ); 17 print( span( { style => "color: blue; font-weight: bold" }, 18 $firstName ) ); 19 print( "!" ); 20 21 print( "\nThank you for completing the survey." ); 22 print( br(), "You have been added to the " ); 23 24 print( span( { style => "color: blue; font-weight: bold" }, 25 $book ) ); 26 print( " mailing list.", br(), br() ); 27 28 print( span( { style => "font-weight: bold" }, 29 "The following information has 30 been saved in our database: " ), br() ); Line 15: Test for correct phone number input form using if structure Indicate actions to be performed if test returns TRUE result check if phone no. has the format (555)-555-5555 \d{3} means 3 digits ^ & $ ensure that there are no extra characters in front or at the end Line 22: br() function adds a break (ie ,<BR/>) Line 24: span() function adds a <span> tag 4: Web Architecture
31 print( table( 32 Tr( th( { style => "background-color: #ee82ee" }, 33 "Name" ), 34 th( { style => "background-color: #9370db" }, 35 "E-mail" ), 36 th( { style => "background-color: #4169e1" }, 37 "Phone" ), 38 th( { style => "background-color: #40e0d0" }, 39 "OS" ) ), 40 41 Tr( { style => "background-color: #c0c0c0" }, 42 td( "$firstName $lastName" ), 43 td( $email ), 44 td( $phone ), 45 td( $os ) ) ) ); Line 32: Tr() and th() are CGI functions that place arguments between Table row and table header tags (ref, p 923, Deitel) Line 42: td() is a CGI function that prints <td> tags 4: Web Architecture
46 print( br() ); 47 print( div( { style => "font-size: x-small" }, 48 "This is only a sample form. You have not been 49 added to a mailing list." ) ); 50 } 51 else { 52 print( div( { style => "color: red; font-size: x-large" }, 53 "INVALID PHONE NUMBER" ), br() ); 54 print( "A valid phone number must be in the form " ); 55 print( span( { style => "font-weight: bold" }, 56 "(555)555-5555." ) ); 57 print( div( { style => "color: blue" }, 58 "Click the Back button, and enter a 59 valid phone number and resubmit." ) ); 60 print( br(), br() ); 61 print( "Thank you." );} 62 print( end_html() ); Line 47: div() is a CGI function that generates a <div> tag Line 51: Set actions to be performed if the if structure returns a FALSE value Line 51: end_html() returns the closing tags for the page (</body> and </html>) 4: Web Architecture
3.4 Perl Samples: Form Processing and Business Logic • Script Output 1: If phone number is valid 4: Web Architecture
3.4 Perl Samples: Form Processing and Business Logic • Script Output 2: If phone number is invalid 4: Web Architecture
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. 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 4: Web Architecture
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 9<BODY> 10 <CENTER> 11<H3> Using Server Side Includes</H3> 12 </CENTER> 13 14<!-- #EXEC CGI="/cgi-bin/counter.pl" --><BR> 15 The Greenwich Mean Date is 16<FONT COLOR = BLUE> 17 18<!-- #ECHO VAR="DATE_GMT" -->. 19</FONT><BR> 20 The name of this document is 21<FONT COLOR = BLUE> 22 23<!-- #ECHO VAR="DOCUMENT_NAME" --> 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 31<FONT COLOR = BLUE> 32 Line 14: Execute Perl script counter.pl using EXEC CGI statement Line 18: Use ECHO VAR statements to display environmental variables 4: Web Architecture
65 33<!-- #ECHO VAR="LAST_MODIFIED" --> 66 </CENTER> 34</FONT><BR> 35 Your current IP Address is 67</BODY> 68</HTML> 36<FONT COLOR = BLUE> 37 38<!-- #ECHO VAR="REMOTE_ADDR" --> 39</FONT><BR> 40 My server name is 41<FONT COLOR = BLUE> 42 43<!-- #ECHO VAR="SERVER_NAME" --> 44</FONT><BR> 45 And I am using the 46<FONT COLOR = BLUE> 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> Continue printing environmental variables using ECHO VAR statements 4: Web Architecture
4. SSI Samples Line 5-8: • Open counter.dat, assign to filehandle COUNTREAD • <>read 1 line from file referred by filehandler COUNTEREAD • Increment data in COUNTREAD • Close COUNTREAD Line 9-11: • > means write mode, open counter.dat for writing, referred to by filehandler COUNTERWRITE • printindicates the filehandler COUNTERWRITE where data is written • The Perl Script: counter.pl 1 #!/usr/local/bin/perl 2 # Program to track the number of times a Web page has been accessed. 3 # counter.cgi 4 use CGI qw( :standard ); 5 open( COUNTREAD, "counter.dat" ); 6 $data = <COUNTREAD>; 7 $data++; 8 close( COUNTREAD ); 9 open( COUNTWRITE, ">counter.dat" ); 10 print( COUNTWRITE $data ); 11 close( COUNTWRITE ); 12 print( header(), "<div style = \"text-align: center; font-weight: bold\">" ); 13 print( "You are visitor number", br() ); 14 for ( $count = 0; $count < length( $data ); $count++ ) 15 { 16 $number = substr( $data, $count, 1 ); 17 print( img( { src => "$number.gif" } ), "\n" ); 18 } 19 print( "</div>" ); 4: Web Architecture
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 4: Web Architecture