Chapter 27 CGI Common Gateway Interface and Perl

  • Slides: 85
Download presentation
Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27. 1 Common

Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27. 1 Common Gateway Interface (CGI) 27. 2 Introduction to Perl 27. 3 Configuring Personal Web Server (PWS) for Perl/CGI 27. 4 String Processing and Regular Expressions 27. 5 Viewing Client/Server Environment Variables 27. 6 Form Processing and Business Logic 27. 7 Server-Side Includes 27. 8 Verifying a Username and Password 27. 9 Sending E-mail from a Web Browser 27. 10 Using ODBC to Connect to a Database 27. 11 Cookies and Perl 27. 12 Case Study: Building a Search Engine 2000 Deitel & Associates, Inc. All rights reserved.

27. 1 Common Gateway Interface (CGI) • Server-side programming – Process data on the

27. 1 Common Gateway Interface (CGI) • Server-side programming – Process data on the server to increase communication between clients and servers – Create interactive applications • Client-side scripting – Not always sufficient when building truly interactive Webbased applications • Hyper. Text Transfer Protocol (HTTP) – Used for communication between Web browsers and servers • Universal Resource Locator (URL) – Used by browsers (clients) to indicate name of Web server from which to request and retrieve information 2000 Deitel & Associates, Inc. All rights reserved.

27. 1 Common Gateway Interface (CGI) (II) • HTTP GET command – By issuing

27. 1 Common Gateway Interface (CGI) (II) • HTTP GET command – By issuing command, client directs server to send specific data to browser • CGI – Lets HTTP clients interact with programs across a network through a Web server – A standard for interfacing applications with a Web server – CGI applications • Can be written in many different programming languages • Reside in the directory /cgi-bin • Within Web server – Permission granted by Web master to allow specific programs to be executed on the server 2000 Deitel & Associates, Inc. All rights reserved.

27. 1 Common Gateway Interface (CGI) (III) • Interaction methods – Standard input –

27. 1 Common Gateway Interface (CGI) (III) • Interaction methods – Standard input – keyboard – Standard output – screen • Web browser – – Take info from user 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 2000 Deitel & Associates, Inc. All rights reserved.

27. 1 Common Gateway Interface (CGI) (IV) Data path of a typical CGI-based application

27. 1 Common Gateway Interface (CGI) (IV) Data path of a typical CGI-based application 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl • Perl (Practical Extraction and Report Language) – –

27. 2 Introduction to 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 Current version: Perl 5 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 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl (II) • Perl initially developed for UNIX platform –

27. 2 Introduction to Perl (II) • Perl initially developed for UNIX platform – Always intended to be a cross-platform computer language • Active. Perl – 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) 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl (III) Perl command line switches (case sensitive) 2000 Deitel

27. 2 Introduction to Perl (III) Perl command line switches (case sensitive) 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl (IV) • Comment Character - # – Goes at

27. 2 Introduction to Perl (IV) • 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 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 # Fig. 27. 4: first. pl # A first program

1 2 3 4 # Fig. 27. 4: first. pl # A first program in Perl. Outline print "Welcome to Perl!n"; 1. 1 Print Statement Welcome to Perl! 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl (V) • Perl contains set of data types –

27. 2 Introduction to Perl (V) • 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 • % - hash – Uses keys that are strings to reference individual array elements – 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 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # Fig. 27. 6: variable. pl # Program to illustrate the use of scalar variables. # using a variable in the context of a string print "Using a variable before initializing: $varn"; # using a variable in a numeric context $test = $num + 5; print "Adding uninitialized variable num to 5 yields: $test. n"; $a = 5; print "The value of variable a is: $an"; $a = $a + 5; print "Variable a after adding 5 is $a. n"; $b = "A string value"; $a = $a + $b; print "Adding a string to an integer yields: $an"; $number = 7; $b = $b + $number; print "Adding an integer to a string yields: $bn"; Using a variable before initializing: Adding uninitialized variable num to 5 yields: 5. The value of variable a is: 5 Variable a after adding 5 is 10. Adding a string to an integer yields: 10 Adding an integer to Inc. a string 2000 Deitel & Associates, All rightsyields: reserved. 7 Outline 1. 1 Demonstrate variable in string before initialization 1. 2 Demonstrate addition involving variable using print statements 1. 3 Add integer to string and print result

27. 2 Introduction to Perl (VI) • Perl can store arrays – Arrays divided

27. 2 Introduction to Perl (VI) • Perl can store arrays – Arrays divided into elements • Each can contain an individual scalar variable • Array definition @array. Name = (“element 1”, “element 2”, …, “element. N”); • First array element is [0] – Array index one number lower than expected • Eighth element in array has index of 7 2000 Deitel & Associates, Inc. All rights reserved.

27. 2 Introduction to Perl (VII) • Arrays – Elements are referenced as scalar

27. 2 Introduction to Perl (VII) • Arrays – Elements are referenced as scalar values with element number in square brackets ([]) • @ refers to array as a whole, $ refers to elements Example: $array[2] • Refers to the third element in @array • Range Operator – “. . ” – Used to store all values between given arguments Example: @array 2 = (A. . Z); – Creates array @array 2 containing all capital letters in alphabet (all letters between A and Z) 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 # Fig. 27. 7: arrays. pl # Program to demonstrate arrays in Perl @array = ("Bill", "Bobby", "Sue", "Michelle"); print "The array contains: nn"; print "@array nn"; print "Third element: $array[2]nn"; @array 2 = (A. . Z); print "The range operator is used to store alln"; print "letters from capital A to Z: nn"; print "@array 2 n"; Outline 1. 1 Define array @array 2. 1 Print contents of @array 2. 2 Print third element of @array 3. 1 Define array @array 2 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 2000 Deitel & Associates, Inc. All rights reserved. 3. 2 Explain and print contents of @array 2

27. 2 Introduction to Perl (VIII) • In addition to core Perl package –

27. 2 Introduction to Perl (VIII) • In addition to core Perl package – Add-ons called packages provide additional functionality • Packages – Often provide platform specific features – Are available free of charge at http: //www. activestate. com/packages 2000 Deitel & Associates, Inc. All rights reserved.

27. 3 Configuring Personal Web Server (PWS) for Perl/CGI • To run CGI with

27. 3 Configuring Personal Web Server (PWS) for Perl/CGI • To run CGI with PWS – Several modifications must be made in the Windows Registry • PWS must be enabled to execute Perl scripts – does not by default • For detailed instructions on procedure to update Windows Registry to handle Perl scripts – See section 27. 3 in your textbook 2000 Deitel & Associates, Inc. All rights reserved.

27. 4 String Processing and Regular Expressions • Processing textual data easily and efficiently

27. 4 String Processing and Regular Expressions • 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 example: if ($hello eq “Good Morning”)… • Keyword my – Indicates designated variable only valid for block of code in which it is declared 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # Fig. 27. 16: equals. pl # Program to demonstrate the eq operator 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 Testing does not match Test. 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Declare variables using my 2. 1 Test string variable-string equality 2. 2 Print appropriate result 3. 1 Test second variable 3. 2 Print appropriate result

27. 4 String Processing and Regular Expressions (II) • eq operator – Cannot be

27. 4 String Processing and Regular Expressions (II) • eq operator – Cannot be used to search through a series of words • Matching operator : =~ – Tests whether match for a string is found within a single string or series of words • Format $search =~ /Test/ • Searches for word test within indicate string 2000 Deitel & Associates, Inc. All rights reserved.

27. 4 String Processing and Regular Expressions (III) • Some meta/modifying characters – –

27. 4 String Processing and Regular Expressions (III) • Some meta/modifying characters – – ^ - indicates beginning of a line $ - indicates end of a line b…b – indicates word boundary w – matches any alphanumeric character • Other modifying characters 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 # Fig 27. 17: expression 1. pl # searches using the matching operator and regular expressions Outline $search = "Testing pattern matches"; if ( $search =~ /Test/ ) { print "Test was found. n"; } if ( $search =~ /^Test/ ) { print "Test was found at the beginning of the line. n"; } if ( $search =~ /Test$/ ) { print "Test was found at the end of the line. n"; } if ( $search =~ / b ( w+ es ) b /x ) { print "Word ending in es: $1 n"; } Test was found at the beginning of the line. Word ending in es: matches 2000 Deitel & Associates, Inc. All rights reserved. 1. 1 Test for word ‘Test’ in string, print result 2. 1 Test for word ‘Test’ at beginning on string, print result 3. 1 Test for word ‘Test’ at end of string, print result 4. 1 Test for word in string ending with letters ‘es’, print result

27. 5 Viewing Client/Server Environment Variables • Knowing info about client very useful to

27. 5 Viewing Client/Server Environment Variables • Knowing info about client very useful to system administrators • CGI environment variables – Contains info about client • • Web browser being used Version of CGI server running HTTP host, HTTP connection Much more • Use statement – Allows inclusion of predefined library packages in programs 2000 Deitel & Associates, Inc. All rights reserved.

27. 5 Viewing Client/Server Environment Variables (II) • CGI Library – Included to provide

27. 5 Viewing Client/Server Environment Variables (II) • 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 2000 Deitel & Associates, Inc. All rights reserved.

1 # Fig. 27. 19: environment. pl 2 # Program to display CGI environment

1 # Fig. 27. 19: environment. pl 2 # Program to display CGI environment variables 3 use CGI qw/: standard/; 1. 1 use standard CGI library 4 5 print header; 6 print "<HTML>"; 7 print " 8 print " 9 print " <HEAD>"; <TITLE>Environment Variables. . . </TITLE>"; 2. 1 Print top of HTML Table </HEAD>"; 10 print " <BODY TEXT = BLACK BGCOLOR = WHITE>"; 11 print " <BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 2>"; 12 print " <TABLE BORDER = 0 CELLPADDING = 2 CELLSPACING = 0"; 13 print " Outline WIDTH = 100%>"; 14 3. 1 Use foreach function to sort through keys in %ENV hashtable 15 foreach $key (sort keys %ENV) 16 { 17 print "<TR>"; 18 print "<TD BGCOLOR = #11 BBFF><STRONG>$key</STRONG></TD>"; 19 print "<TD><FONT COLOR = BLACK SIZE = 2>$ENV{$key}"; 20 print "</Font></TD>"; 21 print "</TR>"; 22 } 23 24 print " 25 print " </TABLE>"; </BODY>"; 2000 Deitel & Associates, Inc. All rights reserved. 26 print "</HTML>"; 3. 2 Print current keys in table 4. 1 Close table

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 6 Form Processing and Business Logic • HTML FORMs 1. Allow users to

27. 6 Form Processing and Business Logic • 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 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27. 20: form. html --> 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> 33 Must be in the form (555)555 -5555 <BR> 34 </FONT> 2000 Deitel & Associates, Inc. All rights reserved. 35 Outline 1. 1 Open FORM 1. 2 Define FORM attributes 1. 3 Insert and define form INPUT elements 1. 4 Specify correct input format

36 <IMG SRC = "images/downloads. gif"><BR> 37 <FONT COLOR = BLUE> 38 Which book

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 2 e 44 <OPTION>Java How to Program 3 e 45 <OPTION>Visual Basic How to Program 1 e 46 </SELECT> 47 <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" 56 CHECKED> 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"> 65 Other<BR> 66 <INPUT TYPE = "SUBMIT" VALUE = "Register"> 67 </FORM> 68</BODY> 2000 Deitel & Associates, Inc. All rights reserved. 69</HTML> Outline 1. 5 Continue inserting and defining form INPUT element 1. 6 Close FORM element

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 6 Form Processing and Business Logic (II) • Retrieving data from form output

27. 6 Form Processing and Business Logic (II) • 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{3} /x) { actions } – d{n} tests for n characters – is escape character • Close-bracket (“)”) character is used in Perl statements, needs escape character “” to appear as part of search test string 2000 Deitel & Associates, Inc. All rights reserved.

1 # Fig. 27. 21: form. pl 2 # Program to read information sent

1 # Fig. 27. 21: form. pl 2 # Program to read information sent to the server 3 # from the FORM in the form. html document. 4 5 use CGI qw/: standard/; 6 7 $os = param(OS); 8 $firstname = param(FNAME); 9 $lastname = param(LNAME); 10 $email = param(EMAIL); 11 $phone = param(PHONE); 12 $book = param(BOOK); 13 14 print header; 15 print "<BODY BACKGROUND = "/images/back. gif">"; 16 print "<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 3>"; 17 18 if ( $phone =~ / ( d{3} ) d{3} - d{4} /x ) 19 { 20 print "Hi <FONT COLOR = BLUE><B>$firstname</B></FONT>"; 21 print ". Thank you for completing the survey. <BR>"; 22 print "You have been added to the "; 23 print "<FONT COLOR = BLUE><STRONG>$book </STRONG></FONT>"; 24 print "mailing list. <BR>"; 25 print "<STRONG>The following information has been saved "; 26 print "in our database: </STRONG><BR>"; 27 print "<TABLE BORDER = 0 CELLPADDING = 0"; 28 print " CELLSPACING = 10>"; 29 print "<TR><TD BGCOLOR = #FFFFAA>Name </TD>"; 30 print " <TD BGCOLOR = #FFFFBB>Email</TD>"; 31 print " <TD BGCOLOR = #FFFFCC>Phone</TD>"; 2000 Deitel & Associates, All rights 32 print " <TD Inc. BGCOLOR = reserved. #FFFFDD>OS</TD></TR>"; Outline 1. 1 use standard CGI library 2. 1 Assign form field values to variables 3. 1 Test for correct phone number input form using if structure 3. 2 Indicate actions to be performed if test returns TRUE result

33 print "<TR><TD>$firstname $lastname</TD><TD>$email</TD>"; 34 print "<TD>$phone</TD><TD>$os</TD></TR>"; 35 print "</TABLE>"; 36 print "<BR><BR>"; 37

33 print "<TR><TD>$firstname $lastname</TD><TD>$email</TD>"; 34 print "<TD>$phone</TD><TD>$os</TD></TR>"; 35 print "</TABLE>"; 36 print "<BR><BR>"; 37 print "<CENTER><FONT SIZE = -3>"; 38 print "This is only a sample form. "; 39 print "You have not been added to a mailing list. "; 40 print "</FONT></CENTER>"; 41 } 42 else 43 { 44 print "<FONT COLOR = RED SIZE = +2>"; 45 print "INVALID PHONE NUMBER</FONT><BR>"; 46 print " A valid phone number must be in the form"; 47 print "<STRONG>(555)555 -5555</STRONG>"; 48 print "<FONT COLOR = BLUE> Click the Back button, "; 49 print "enter a valid phone number and resubmit. <BR>"; 50 print "Thank You. "; 51 } 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. 3 Finish inputting if structure actions and close structure 4. 1 Set actions to be performed if if structure returns a FALSE value

Script Output 1 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 1 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2 2000 Deitel & Associates, Inc. All rights reserved.

27. 7 Server-Side Includes • Web offers ability to track – Where client coming

27. 7 Server-Side Includes • Web offers ability to track – 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 • Server-side includes (SSIs) – Commands embedded in HTML documents – Provide for content creation – Allow inclusion of current time, date or even contents of different html document 2000 Deitel & Associates, Inc. All rights reserved.

27. 7 Server-Side Includes (II) • SSI commands – Execute CGI scripts on a

27. 7 Server-Side Includes (II) • 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: <!-- #EXEX CGI=“cgi-bin/counter. pl” --> – Executes the Perl script counter. pl, located in the cgibin directory 2000 Deitel & Associates, Inc. All rights reserved.

27. 7 Server-Side Includes (III) • ECHO command – Used to display variable information

27. 7 Server-Side Includes (III) • 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 2000 Deitel & Associates, Inc. All rights reserved.

27. 7 Server-Side Includes (IV) • Perl scripts can access and modify other files

27. 7 Server-Side Includes (IV) • Perl scripts can access and modify other files – open() function • Form: open(file. Handle, “>file. Name”); – > - discards any data in file, creates new file if does not exist – >> - append mode – While file open, referenced using file. Handle – Close file using the close() statement • Format: close(file. Handle); – While accessing file, print statement can redirect output to a file print COUNTWRITE $data; • Assigns $data to file pointed to by COUNTWRITE 2000 Deitel & Associates, Inc. All rights reserved.

27. 7 Server-Side Includes (V) • length() function – Returns length of string •

27. 7 Server-Side Includes (V) • length() function – Returns length of string • substr( x, y, z ) function – Similar to Java. Script’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 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27.

1<!DOCTYPE html PUBLIC "-//W 3 C//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 <H 3> Using Server Side Includes </H 3> 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> 2000 Deitel & Associates, Inc. All rights reserved. 32 Outline 1. 1 Execute Perl script counter. pl using EXEC CGI statement 2. 1 Use ECHO VAR statements to display environmental variables

33 <!-- #ECHO VAR="LAST_MODIFIED" --> 34 </FONT><BR> 35 Your current IP Address is 36

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 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> 60 <CENTER> 61 <HR> 62 <FONT SIZE = -5>This document was last modified on 63 64 <!-- #ECHO VAR="LAST_MODIFIED" --> </FONT> 65 66 </CENTER> 67</BODY> 2000 Deitel & Associates, Inc. All rights reserved. 68</HTML> Outline 2. 2 Continue printing environmental variables using ECHO VAR statements

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # Counter. pl # Program to track the number of times a web page # has been accessed. Outline open(COUNTREAD, "counter. dat"); my $data = <COUNTREAD>; $data++; close(COUNTREAD); 1. 1 Open counter. dat, assign to filehandle COUNTREAD open(COUNTWRITE, ">counter. dat"); print COUNTWRITE $data; close(COUNTWRITE); 1. 2 Increment data in COUNTREAD print "<CENTER>"; print "<STRONG>You are visitor number</STRONG><BR>"; 1. 3 Close COUNTREAD for ($count = 0; $count < length($data); $count++) { $number = substr( $data, $count, 1 ); print "<IMG SRC="images/counter/$number. jpg">"; } 2. 1 Assign data contained in file counter. dat to variable $data print "</CENTER>"; 3. 1 Use for structure to output number of page hits using number images 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 8 Verifying a Username and Password • Often desirable to have private Web

27. 8 Verifying a Username and Password • Often desirable to have private Web site – Developers often employ username and password authentication to implement privacy • Upcoming files – verify. html – HTML document client browser displays – password. pl – Perl script that verifies username and password inputted by client and performs appropriate actions – data. txt – Text file containing username and password combinations (unencrypted for simplicity) 2000 Deitel & Associates, Inc. All rights reserved.

27. 8 Verifying a Username and Password (II) • If file cannot be opened

27. 8 Verifying a Username and Password (II) • If file cannot be opened – Use function die to exit program and print message • while<file. Handle> – Executes structure while still information in file. Handle • split function – Read contents of a file into an array @array. Name = split(/n/) – Creates array. Name, creates new array entry after every n character • Access array elements and split into two parts foreach $entry (@data) {…} – Performs indicated action on every entry in array @data – Subsequently assigns entry information to $entry 2000 Deitel & Associates, Inc. All rights reserved.

27. 8 Verifying a Username and Password (III) • Split array into two parts

27. 8 Verifying a Username and Password (III) • Split array into two parts ($name, $pass) = split(/, /, $entry) – Assigns username string of current entry to $name – Assigns password string of current entry to $pass • Perl accepts logical and (&&) and or (||) operators – Same format as other languages Example: if ($userverified && $passwordverified) {…} – Evaluates to TRUE if both variable values are TRUE • TRUE: any string or non-zero number • sub function. Name {…} – Sets actions of user-defined function. Name – User-defined functions accessed: &function. Name 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27. 24: verify. html --> 3 4<HTML> 5<HEAD> 6<TITLE>Verifying a username and a password. </TITLE> 7</HEAD> 8 9<BODY BACKGROUND = "images/back. gif"> 10 <P> 11 <FONT FACE = Arial> 12 Type in your username and password below. 13 </FONT><BR> 14 <FONT COLOR = #0000 FF FACE = Arial SIZE = 1> 15 <STRONG> 16 Note that password will be sent as plain text 17 </STRONG> 18 </FONT> 19 </P> 20 21 <FORM ACTION = "/cgi-bin/password. pl" METHOD = "post"> 22 <BR> 23 24 <TABLE BORDER = "0" CELLSPACING = "0" STYLE = "HEIGHT: 90 px; 25 WIDTH: 123 px" CELLPADING = "0"> 26 <TR> 27 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 28 <FONT FACE = Arial SIZE = 2> 29 <STRONG>Username: </STRONG> 30 </FONT> 31 </TD> 2000 Deitel & 32 </TR>Associates, Inc. All rights reserved. Outline 1. 1 Print instructions 2. 1 Open FORM and define ACTION attribute 3. 1 Open HTML TABLE

33 <TR> 34 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 35 <INPUT SIZE =

33 <TR> 34 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 35 <INPUT SIZE = "40" NAME = "USERNAME" 36 37 STYLE = "HEIGHT: 22 px; WIDTH: 115 px" > </TD> 38 </TR> 39 <TR> 40 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 41 <FONT FACE = Arial SIZE = 2> 42 <STRONG>Password: </STRONG> 43 </FONT></TD> 44 </TR> 45 <TR> 46 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 47 <INPUT SIZE = "40" NAME = "PASSWORD" 48 STYLE = "HEIGHT: 22 px; WIDTH: 115 px" 49 TYPE = PASSWORD> 50 <BR></TD> 51 </TR> 52 <TR> 53 <TD COLSPAN = 3> 54 <INPUT TYPE = "submit" VALUE = "Enter" 55 56 STYLE = "HEIGHT: 23 px; WIDTH: 47 px" > </TD> 57 </TR> 58 </TABLE> 59 </FORM> 60</BODY> 2000 Deitel & Associates, Inc. All rights reserved. 61</HTML> Outline 3. 2 Insert and define INPUT elements for username and password 3. 3 Insert INPUT submit button 3. 4 Close TABLE and FORM elements

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 # Fig. 27. 25: password. pl # Program to search a database for usernames and passwords. use CGI qw/: standard/; my $username = param(USERNAME); my $password = param(PASSWORD); open(FILE, "data. txt") || die "The database could not be opened"; while(<FILE>) { @data = split(/n/); foreach $entry (@data) { ($name, $pass) = split(/, /, $entry); if($name eq "$username") { $userverified = 1; if ($pass eq "$password") { $passwordverified = 1; } } 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Open data. txt and assign to FILE 1. 2 Enter text to be printed if the file cannot be accessed using die function 2. 1 Open while structure 3. 1 Create @data array using FILE 3. 2 Split each entry into NAME and PASS entries 3. 3 Use if structure to verify username and password and perform appropriate actions

30 close(FILE); 31 32 if ($userverified && $passwordverified) 33 { 34 &accessgranted; 35 }

30 close(FILE); 31 32 if ($userverified && $passwordverified) 33 { 34 &accessgranted; 35 } 36 elsif ($userverified && !$passwordverified) 37 { 38 &wrongpassword; 39 } 40 else 41 { 42 &accessdenied; 43 } 44 45 sub accessgranted 46 { 47 print header; 48 print "<TITLE>Thank You</TITLE>"; 49 print "<FONT FACE = Arial SIZE = 2 COLOR = BLUE>"; 50 print "<STRONG>Permission has been granted $username. "; 51 print "<BR> Enjoy the site. </STRONG></FONT>"; 52 } 53 2000 Deitel & Associates, Inc. All rights reserved. Outline 3. 4 Close while structure 4. 1 Use if structures to call user-defined programs depending on outcome of password verification 5. 1 Define accessgranted function 5. 2 Print ‘permission granted’ message

54 55 56 57 58 59 60 61 62 63 64 65 66 67

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 sub wrongpassword { print header; print "<TITLE>Access Denied</TITLE>"; print "<FONT FACE=Arial SIZE=2 COLOR=Red><STRONG>"; print "You entered an invalid password. "; print "Access has been denied. </STRONG></FONT>"; exit; } sub accessdenied { print header; print "<TITLE>Access Denied</TITLE>"; print "<FONT FACE=Arial SIZE=3 COLOR=Red><STRONG>"; print "You were denied access to this server. "; print "</STRONG></FONT>"; exit; } 2000 Deitel & Associates, Inc. All rights reserved. Outline 6. 1 Define wrongpassword function 6. 2 Print ‘invalid password’ message 7. 1 Define accessdenied function 7. 2 Print ‘access denied’ message

1 account 1, password 1 2 account 2, password 2 3 account 3, password

1 account 1, password 1 2 account 2, password 2 3 account 3, password 3 4 account 4, password 4 5 account 5, password 5 6 account 6, password 6 7 account 7, password 7 8 account 8, password 8 9 account 9, password 9 10 account 10, password 10 Outline Data. txt 1. 1 Input username and password combinations using format: username, password/n 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 9 Sending E-Mail From a Web Browser • Email – One of most

27. 9 Sending E-Mail From a Web Browser • Email – One of most frequently used capabilities of the Internet – Can be sent directly from browser using Perl script • Net package’s Simple Mail Transfer Protocol (SMTP) – Use this SMTP functionality to send email code: use Net: : SMTP; • Email cannot be sent without a valid smtp server – Server name client uses is usually text after the”@” in your client’s email address 2000 Deitel & Associates, Inc. All rights reserved.

27. 9 Sending E-Mail From a Web Browser • Create a new instance of

27. 9 Sending E-Mail From a Web Browser • Create a new instance of a mail server object smtp = Net: : SMTP->new($mailserver); • -> is Perl’s scope operator – Equivalent to “. ” in Java. Script • datasend function – Tells mail server that a command is being issued • smtp->quit; – Closes connection to smtp server 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27:

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27: email. html --> 3<HTML> 4<HEAD> 5 <TITLE>Web-based email interface. </TITLE> 6</HEAD> 7 8<BODY BACKGROUND = "images/back. gif"> 9 <FORM ACTION = "cgi-bin/mail. pl" METHOD = "POST"> 10 <TABLE BORDER = "0" CELLSPACING = "0" CELLPADING = "0"> 11 12 <TR> 13 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 14 <INPUT SRC = "images/send. gif" TYPE = "IMAGE"> 15 <IMG SRC = "images/bar. gif"> 16 </TD> 17 </TR> 18 19 <TR> 20 <TD BGCOLOR = #DDDDDD WIDTH = "10%"><STRONG> 21 <FONT FACE = "Arial" SIZE = "2">To:   </FONT> 22 </STRONG> 23 </TD> 24 <TD BGCOLOR = #DDDDDD><INPUT NAME = "TO"> 25 </TD> 26 </TR> 27 28 <TR> 29 <TD BGCOLOR = #DDDDDD> 30 <P><FONT FACE = Arial SIZE = 2> 31 <STRONG>From: </STRONG> 2000 Deitel & Associates, Inc. All rights reserved. 32 </FONT></P> Outline 1. 1 Open FORM and define ACTION attribute 2. 1 Inset and define INPUT submit image 2. 2 Insert text INPUTs for other email field categories

33 </TD> 34 <TD BGCOLOR = #DDDDDD><INPUT NAME = "FROM"> 35 </TD> 36 </TR>

33 </TD> 34 <TD BGCOLOR = #DDDDDD><INPUT NAME = "FROM"> 35 </TD> 36 </TR> 37 38 <TR> 39 <TD BGCOLOR = #DDDDDD> 40 <P><FONT FACE = Arial SIZE = 2> 41 <STRONG>Subject: </STRONG> 42 </FONT></P> 43 </TD> 44 <TD BGCOLOR = #DDDDDD><INPUT NAME = "SUBJECT"> 45 </TD> 46 </TR> 47 48 <TR> 49 <TD BGCOLOR = #DDDDDD> 50 <P><FONT FACE = "Arial" SIZE = 2><STRONG><EM>Mail 51 Server: </EM></STRONG></FONT></P> 52 </TD> 53 <TD BGCOLOR = #DDDDDD><INPUT NAME = "MAILSERVER"> 54 </TD> 55 </TR> 56 57 <TR> 58 <TD BGCOLOR = #DDDDDD COLSPAN = 3> 59 <P> 60 <STRONG><FONT FACE = "Arial" SIZE = "2"><BR>Message: 61 </FONT> 62 </STRONG><BR> 63 <TEXTAREA COLS = 50 NAME = "MESSAGE" ROWS = 6 2000 Deitel & Associates, Inc. All rights reserved. 64 STYLE = "HEIGHT: 170 px; WIDTH: 538 px" ></TEXTAREA> Outline 2. 3 Insert and define remaining INPUT elements for email fields 2. 4 Insert and define TEXTAREA for body of email message

65 </P><P> </P> 66 </TD> 67 </TR> 68 69 </TABLE> 70 </FORM> 71 </HTML>

65 </P><P> </P> 66 </TD> 67 </TR> 68 69 </TABLE> 70 </FORM> 71 </HTML> Outline 1. 1 Close TABLE and FORM tags Script Output 2000 Deitel & Associates, Inc. All rights reserved.

1 # Fig. 27. 28: mail. pl 2 # Program to send email from

1 # Fig. 27. 28: mail. pl 2 # Program to send email from a Web-based form. Outline 3 4 use Net: : SMTP; 5 use CGI qw/: standard/; 6 7 my $to = param("TO"); 8 my $from 9 my $subject = param("SUBJECT"); 10 my $message = param("MESSAGE"); = param("FROM"); 11 my $mailserver = param("MAILSERVER"); 12 13 print header; 14 print "<H 3>The request has been Processed. "; 15 print "Thank You $from</H 3>"; 16 1. 1 use SMTP 1. 2 use CGI standard library 2. 1 Set local variable values to user form inputs 3. 1 print ‘request processed’ message 17 $smtp = Net: : SMTP->new($mailserver); 18 19 $smtp->mail($ENV{USER}); 20 $smtp->to("$to"); 4. 1 Connect to SMTP server 21 $smtp->data(); 22 $smtp->datasend("To: $to n"); 23 $smtp->datasend("From: $from n"); 24 $smtp->datasend("Subject: $subject n"); 25 $smtp->datasend("n"); 26 $smtp->datasend("$message n"); 4. 2 Form email message using data(), datasend() and dataend() functions 27 $smtp->dataend(); 28 2000 Deitel & Associates, Inc. All rights reserved. 29 $smtp->quit; 4. 3 quit smtp server

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 10 Using ODBC to Connect to a Database • Databases allow companies to

27. 10 Using ODBC to Connect to a Database • Databases allow companies to – Enter world of e-commerce – Maintain crucial data • Perl package Win 32 -ODBC – Enables Perl programs to connect to ODBC data sources – Data source must first be defined using Data Source Administrator in MS Windows (see Section 25. 5) • From Web browser 1. Client enters SQL query string 2. String sent to Web server 3. Perl script executed • Database queried 4. Record set in HTML form sent back to client 2000 Deitel & Associates, Inc. All rights reserved.

27. 10 Using ODBC to Connect to a Database (II) • Script connects to

27. 10 Using ODBC to Connect to a Database (II) • Script connects to ODBC Data source – By passing the Data Source Name, $DSN, to the constructor for the Win 32: : ODBC object. $Data = new Win 32: : ODBC($DSN) • new specifies that a new instance of the object is to be created – Win 32: : ODBC: : Error • Returns error that occurred • Query string sent to database $Data->Sql($querystring) – If fails, error message is returned 2000 Deitel & Associates, Inc. All rights reserved.

27. 10 Using ODBC to Connect to a Database (III) • Method Data. Hash

27. 10 Using ODBC to Connect to a Database (III) • Method Data. Hash – Retrieves the fields in a row from the record set • Coding HTML in Perl – Open HTML area with print header; – Close HTML area with print end_html; • Use tables to output fields in a database – Organizes information neatly 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27. 30: data. html --> Outline 3 4<HTML> 5<HEAD> 6<TITLE>Sample Database Query</TITLE> 7</HEAD> 8 9<BODY BACKGROUND = "images/back. gif"> 10<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 2> 1. 1 Open and define FORM 1. 2 Insert and define text INPUT for entering SQL query 11 12 13 14 <FONT SIZE = +2> <STRONG>Querying an ODBC database. </STRONG> </FONT><BR> 15 16 17 <FORM METHOD = "POST" ACTION = "cgi-bin/data. pl"> <INPUT TYPE = "TEXT" NAME = "QUERY" SIZE = 40 18 19 20 VALUE = "SELECT * FROM AUTHORS"><BR> <INPUT TYPE = "SUBMIT" VALUE = "Send Query"> </FORM> 21</BODY> 22</HTML> 2000 Deitel & Associates, Inc. All rights reserved. 1. 3 Insert INPUT button

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

1 # Fig. 27. 31: data. pl 2 # Program to query a database

1 # Fig. 27. 31: data. pl 2 # Program to query a database and send 3 # results to the client. 4 5 use Win 32: : ODBC; 6 use CGI qw/: standard/; 7 8 my $querystring = param(QUERY); 9 $DSN = "Products"; 10 11 print header; 12 13 if (!($Data = new Win 32: : ODBC($DSN))) 14 { 15 print "Error connecting to $DSNn"; 16 print "Error: ". Win 32: : ODBC: : Error(). "n"; 17 exit; 18 } 19 20 if ($Data->Sql($querystring)) 21 { 22 print "SQL failed. n"; 23 print "Error: ". $Data->Error(). "n"; 24 $Data->Close(); 25 exit; 26 } 27 28 print "<BODY BACKGROUND = "/images/back. gif">"; 29 print "<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 3>"; 30 print "<FONT COLOR = BLUE SIZE = 4> Search Results </FONT>"; 31 2000 Deitel & =Associates, Inc. All rights reserved. 32 $counter 0; Outline 1. 1 use Win 32: : ODBC; 1. 2 use CGI standard library 1. 3 print header (open HTML coding) 2. 1 Query database and assign to $Data and set actions if query failed 3. 1 Assign record set generated by SQL statement to $Data and set error actions 4. 1 Initialize counter variable

33 34 print "<TABLE BORDER = 0 CELLPADDING = 5 CELLSPACING = 0>"; 35

33 34 print "<TABLE BORDER = 0 CELLPADDING = 5 CELLSPACING = 0>"; 35 36 while($Data->Fetch. Row()) 37 { 38 39 %Data = $Data->Data. Hash(); 40 41 42 43 44 print "<TR>"; 45 46 { 47 48 49 } print "</TR>"; $counter++; foreach $key( keys( %Data ) ) print "<TD BGCOLOR = #9999 CC>$Data{$key}</TD>"; 50 } 51 print "</TABLE>"; 52 print "<BR>Your search yielded <B>$counter</B> results. "; 53 54 55 56 57 58 print print "<BR>"; "<FONT SIZE = 2>"; "Please email comments to "; "<A href = "mailto: deitel@deitel. com">Deitel "; "and Associates, Inc. </A>. "; end_html; 59 60 $Data->Close(); 2000 Deitel & Associates, Inc. All rights reserved. Outline 5. 1 Insert records into array and execute Data. Hash 5. 2 Use foreach statement to output results 5. 3 Print number of results and closing comments 6. 1 print end_html; (close HTML coding area) 6. 2 Close data source

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 11 Cookies and Perl • Cookies – Used to maintain state information for

27. 11 Cookies and Perl • Cookies – Used to maintain state information for a particular client – May contain • Username • Password • Specific information that will be helpful when user return to same site – Are small text files saved on client’s machine – Sent back to Web server whenever user requests a Web page – Can be written to client machines using Perl scripts 2000 Deitel & Associates, Inc. All rights reserved.

27. 11 Cookies and Perl (II) • To set a cookie using Perl –

27. 11 Cookies and Perl (II) • To set a cookie using Perl – Set variable values to user input strings – Set cookie setup info • $expires – expiration date of cookie • $path – location on clients computer to store cookie • $server_domain – IP address of your server – print “set-cookie: “; … set information to be stored in cookie using print statement – Repeat as needed to store all information in cookie • After cookie written – Text file added to Temporary Internet Files directory • Filename: Cookie: administrator@ip. number 2000 Deitel & Associates, Inc. All rights reserved.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27.

1<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN" > 2<!-- Fig. 27. 32: cookies. html --> 3 4<HTML> 5 <HEAD> 6 <TITLE>Writing a cookie to the client computer </TITLE> 7 </HEAD> 8 9<BODY BACKGROUND = "images/back. gif"> 10<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 2> 11 12 <FONT SIZE = +2> 13 <B>Click Write Cookie to save your cookie data. </B> 14 </FONT><BR> 15 16 <FORM METHOD = "POST" ACTION = "cgi-bin/cookies. pl"> 17 <STRONG>Name: </STRONG><BR> 18 <INPUT TYPE = "TEXT" NAME = "NAME"><BR> 19 <STRONG>Height: </STRONG><BR> 20 <INPUT TYPE = "TEXT" NAME = "HEIGHT"><BR> 21 <STRONG>Favorite Color</STRONG><BR> 22 <INPUT TYPE = "TEXT" NAME = "COLOR"><BR> 23 <INPUT TYPE = "SUBMIT" VALUE = "Write Cookie"> 24 </FORM> 25</BODY> 26</HTML> 2000 Deitel & Associates, Inc. All rights reserved. Outline 1. 1 Enter text instructions 2. 1 Open FORM and define ACTION attribute 2. 2 Insert and define INPUT fields 2. 3 Insert INPUT submit button 2. 4 Close FORM area

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 # Fig. 27. 33: cookies. pl # Program to write a cookie to a client’s machine use CGI qw/: standard/; my $name = param(NAME); my $height = param(HEIGHT); my $color = param(COLOR); $expires = "Monday, 20 -Dec-99 16: 00 GMT"; $path = ""; $server_domain = "127. 0. 0. 1"; print "Set-Cookie: "; print "Name", "=", $name, "; expires=", $expires, "; path=", $path, "; domain=", $server_domain, "n"; print "Set-Cookie: "; print "Height", "=", $height, "; expires=", $expires, "; path=", $path, "; domain=", $server_domain, "n"; print "Set-Cookie: "; print "Color", "=", $color, "; expires=", $expires, "; path=", $path, "; domain=", $server_domain, "n"; print header; print "<BODY BACKGROUND = "/images/back. gif">"; print "<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 3>"; print "The cookie has been set with the folowing data: "; print "<BR>"; print "<FONT COLOR=BLUE>Name: </FONT> $name <BR>"; print "<FONT COLOR = BLUE>Height: </FONT> $height<BR>"; print "<FONT COLOR = BLUE>Favorite Color: </FONT> "; print "<FONT COLOR = $color> $color<BR>"; 2000 Deitel & Associates, Inc. All rights reserved. Outline

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 11 Cookies and Perl (III) • Cookies are read from client machine using

27. 11 Cookies and Perl (III) • Cookies are read from client machine using Perl – Function &read. Cookies returns the information stored in cookies sent to client from server ip address • Information read with statement $ENV{‘HTTP_COOKIE’} – Cookie information can be read by • Storing information in hash array • Splitting fields • Displaying information • Display cookie output in table for organization 2000 Deitel & Associates, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 # Fig. 27. 36: read_cookies.

1 2 3 4 5 6 7 8 9 # Fig. 27. 36: read_cookies. pl # Program to read cookies from the client’s computer use CGI qw/: standard/; print header; "<BODY BACKGROUND = "/images/back. gif">"; "<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 3>"; "<STRONG>The following data is saved in a cookie on your "; 10 print "computer. </STRONG><BR>"; 11 12 my %cookie = &read. Cookies; 13 14 print ("<TABLE ", 15 "BORDER = "5" ", 16 "CELLSPACING = "0" ", 17 "CELLPADDING = "10">"); 18 19 foreach $cookie_name (keys %cookie) 20 { 21 print "<TR>"; 22 print " <TD BGCOLOR=#AAAAFF>$cookie_name</TD>"; 23 print " <TD BGCOLOR=#AAAAAA>$cookie{$cookie_name}</TD>"; 24 print "</TR>"; 25 } 26 print "</TABLE>"; 27 28 sub read. Cookies 29 { 30 my @cookie_values = split (/; /, $ENV{’HTTP_COOKIE’}); 31 2000 foreach Deitel & Associates, Inc. All rights reserved. 32 (@cookie_values) Outline 1. 1 use CGI standard library 1. 2 print header 2. 1 Call function read. Cookies to and store info in %cookie 3. 1 Use foreach structure to output cookie info 4. 1 Define function read. Cookies 4. 2 Put cookie information into an array

33 34 35 36 37 38 { my ($cookie_name, $cookie_value) = split ( /=/,

33 34 35 36 37 38 { my ($cookie_name, $cookie_value) = split ( /=/, $_ ); $cookies{$cookie_name} = $cookie_value; } return %cookies; Outline 4. 3 Split cookie entry names and values 39 } 4. 4 Return information for output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

27. 12 Case Study: Building a Search Engine • Search engines – Allow clients

27. 12 Case Study: Building a Search Engine • Search engines – Allow clients to search through catalogs of info for data • Typical search process 1. Usually, search string entered by client using Web browser 2. Program executed on Web server that searches through database 3. Database typically contains URL’s to specific Web sites and descriptions of site contents • Info sometimes entered by administrators • Info also gathered by programs running on Web server 2000 Deitel & Associates, Inc. All rights reserved.

1 # Fig. 27. 38: search. pl 2 # Program to search for Web

1 # Fig. 27. 38: search. pl 2 # Program to search for Web pages 3 4 use CGI qw/: standard/; 5 6 my $search = param(SEARCH); 7 my $counter = 0; 8 9 print header; 10 print "<BASEFONT FACE = "ARIAL, SANS-SERIF" SIZE = 3>"; 11 12 open(FILE, "urls. txt") || 13 die "The URL database could not be opened"; 14 15 while(<FILE>) 16 { 17 my @data = split(/n/); 18 19 foreach $entry (@data) 20 { 21 my ($data, $url) = split(/; /, $entry); 22 23 if ($data =~ /$search/i) 24 { 25 if ($counter == 0) 26 { 27 print "<STRONG>Search Results: <BR></STRONG>"; 28 } 29 30 print "<A HREF="http: //$url/">"; 31 print "http: //$url/"; 2000 Deitel & Associates, Inc. All rights reserved. 32 print "</A>"; Outline 1. 1 use Cgi standard library 2. 1 Open database file 3. 1 Use while structure to search through file 3. 2 split array into hash, search for matches to search string 3. 3 Test to see if first result, if yes, enter output header 3. 4 Output results as they are found

33 34 35 36 37 38 39 40 41 42 43 44 45 46

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 print "<BR>$data<BR>"; $counter++; } } } close FILE; if ($counter == 0) { print "<B>Sorry, no results were found matching </B>"; print "<FONT COLOR = BLUE>$search</FONT>. "; } else { print "<STRONG>$counter matches found for </STRONG>"; print "<FONT COLOR = BLUE>$search</FONT>"; } Outline 3. 5 Increment counter 3. 6 Close FILE 4. 1 Test to see if no matches found fro search string 4. 2 Set final actions 5. 1 Write database file: urls. txt 50 This site contains information about Perl and CGI; www. perl. com 51 The Deitel and Deitel Web Site; www. deitel. com 52 Purchase books on this web site; www. amazon. com 53 Perl for the Win 32 platform; www. activestate. com 54 The Perl Mongers Web page; www. pm. org 55 Monthly online Perl periodical; www. perlmonth. com 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.

Script Output 2000 Deitel & Associates, Inc. All rights reserved.