Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2000 Deitel & Associates, Inc. All rights reserved. Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI)

Similar presentations


Presentation on theme: " 2000 Deitel & Associates, Inc. All rights reserved. Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI)"— Presentation transcript:

1  2000 Deitel & Associates, Inc. All rights reserved. Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI) 27.2Introduction to Perl 27.3Configuring Personal Web Server (PWS) for Perl/CGI 27.4String Processing and Regular Expressions 27.5Viewing Client/Server Environment Variables 27.6Form Processing and Business Logic 27.7Server-Side Includes 27.8Verifying a Username and Password 27.9Sending E-mail from a Web Browser 27.10Using ODBC to Connect to a Database 27.11 Cookies and Perl 27.12Case Study: Building a Search Engine

2  2000 Deitel & Associates, Inc. All rights reserved. 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 Web- based applications HyperText 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

3  2000 Deitel & Associates, Inc. All rights reserved. 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

4  2000 Deitel & Associates, Inc. All rights reserved. 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

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

6  2000 Deitel & Associates, Inc. All rights reserved. 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

7  2000 Deitel & Associates, Inc. All rights reserved. 27.2 Introduction to Perl (II) 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)

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

9  2000 Deitel & Associates, Inc. All rights reserved. 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

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

11  2000 Deitel & Associates, Inc. All rights reserved. 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

12  2000 Deitel & Associates, Inc. All rights reserved. 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 Add integer to string and print result 1# Fig. 27.6: variable.pl 2# Program to illustrate the use of scalar variables. 3 4# using a variable in the context of a string 5print "Using a variable before initializing: $var\n"; 6 7# using a variable in a numeric context 8$test = $num + 5; 9print "Adding uninitialized variable num to 5 yields: $test.\n"; 10 11$a = 5; 12print "The value of variable a is: $a\n"; 13 14$a = $a + 5; 15print "Variable a after adding 5 is $a.\n"; 16 17$b = "A string value"; 18$a = $a + $b; 19 20print "Adding a string to an integer yields: $a\n"; 21 22$number = 7; 23$b = $b + $number; 24 25print "Adding an integer to a string yields: $b\n"; 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 a string yields: 7

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

14  2000 Deitel & Associates, Inc. All rights reserved. 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: @array2 = (A..Z); –Creates array @array2 containing all capital letters in alphabet (all letters between A and Z )

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

16  2000 Deitel & Associates, Inc. All rights reserved. 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

17  2000 Deitel & Associates, Inc. All rights reserved. 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

18  2000 Deitel & Associates, Inc. All rights reserved. 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

19  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 1# Fig. 27.16: equals.pl 2# Program to demonstrate the eq operator 3 4my $stringa = "Test"; 5my $stringb = "Testing"; 6 7if ($stringa eq "Test") 8{8{ 9 print "$stringa matches Test.\n"; 10} 11else 12{ 13 print "$stringa does not match Test.\n"; 14} 15 16if ($stringb eq "Test") 17{ 18 print "$stringb matches Test.\n"; 19} 20else 21{ 22 print "$stringb does not match Test.\n"; 23} Test matches Test. Testing does not match Test.

20  2000 Deitel & Associates, Inc. All rights reserved. 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

21  2000 Deitel & Associates, Inc. All rights reserved. 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

22  2000 Deitel & Associates, Inc. All rights reserved. Outline 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 1# Fig 27.17: expression1.pl 2# searches using the matching operator and regular expressions 3 4$search = "Testing pattern matches"; 5 6if ( $search =~ /Test/ ) 7{7{ 8 print "Test was found.\n"; 9}9} 10 11if ( $search =~ /^Test/ ) 12{ 13 print "Test was found at the beginning of the line.\n"; 14} 15 16if ( $search =~ /Test$/ ) 17{ 18 print "Test was found at the end of the line.\n"; 19} 20 21if ( $search =~ / \b ( \w+ es ) \b /x ) 22{ 23 print "Word ending in es: $1 \n"; 24} Test was found. Test was found at the beginning of the line. Word ending in es: matches

23  2000 Deitel & Associates, Inc. All rights reserved. 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

24  2000 Deitel & Associates, Inc. All rights reserved. 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

25  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use standard CGI library 2.1 Print top of HTML Table 3.1 Use foreach function to sort through keys in %ENV hashtable 3.2 Print current keys in table 4.1 Close table 1# Fig. 27.19: environment.pl 2# Program to display CGI environment variables 3use CGI qw/:standard/; 4 5print header; 6print " "; 7print " "; 8print " Environment Variables... "; 9print " "; 10print " "; 11print " "; 12print " <TABLE BORDER = 0 CELLPADDING = 2 CELLSPACING = 0"; 13print " WIDTH = 100%>"; 14 15foreach $key (sort keys %ENV) 16{ 17 print " "; 18 print " $key "; 19 print " $ENV{$key}"; 20 print " "; 21 print " "; 22} 23 24print " "; 25print " "; 26print " ";

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

27  2000 Deitel & Associates, Inc. All rights reserved. 27.6 Form Processing and Business Logic HTML FORM s 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

28  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open FORM 1.2 Define FORM attributes 1.3 Insert and define form INPUT elements 1.4 Specify correct input format 1 2 3 4 5 6 Sample FORM to take user input in HTML 7 8 9 10 11 12 13 This is a sample registation form. 14 15 Please fill in all fields and click Register. 16 17 18 19 20 Please fill out the fields below. 21 22 23 24 25 26 27 28 29 30 31 32 33 Must be in the form (555)555-5555 34 35

29  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.5 Continue inserting and defining form INPUT element 1.6 Close FORM element 36 37 38 Which book would you like information about? 39 40 41 42 Internet and WWW How to Program 43 C++ How to Program 2e 44 Java How to Program 3e 45 Visual Basic How to Program 1e 46 47 48 49 50 51 Which operating system are you 52 currently using? 53 54 55 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows NT" 56 CHECKED> 57 Windows NT 58 59 Windows 95 60 61 Windows 98 62 63 Linux 64 65 Other 66 67 68 69

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

31  2000 Deitel & Associates, Inc. All rights reserved. 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

32  2000 Deitel & Associates, Inc. All rights reserved. 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 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 5use 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 14print header; 15print " "; 16print " "; 17 18if ( $phone =~ / \( \d{3} \) \d{3} - \d{4} /x ) 19{ 20 print "Hi $firstname "; 21 print ". Thank you for completing the survey. "; 22 print "You have been added to the "; 23 print " $book "; 24 print "mailing list. "; 25 print " The following information has been saved "; 26 print "in our database: "; 27 print "<TABLE BORDER = 0 CELLPADDING = 0"; 28 print " CELLSPACING = 10>"; 29 print " Name "; 30 print " Email "; 31 print " Phone "; 32 print " OS ";

33  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 33 print " $firstname $lastname $email "; 34 print " $phone $os "; 35 print " "; 36 print " "; 37 print " "; 38 print "This is only a sample form. "; 39 print "You have not been added to a mailing list."; 40 print " "; 41} 42else 43{ 44 print " "; 45 print "INVALID PHONE NUMBER "; 46 print " A valid phone number must be in the form"; 47 print " (555)555-5555 "; 48 print " Click the Back button, "; 49 print "enter a valid phone number and resubmit. "; 50 print "Thank You."; 51}

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

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

36  2000 Deitel & Associates, Inc. All rights reserved. 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

37  2000 Deitel & Associates, Inc. All rights reserved. 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: –Executes the Perl script counter.pl, located in the cgi- bin directory

38  2000 Deitel & Associates, Inc. All rights reserved. 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: –Returns the current local time Other variables –DATE_GMT Contains current Greenwich Mean Time –DOCUMENT_NAME Contains name of current document –Many more

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

40  2000 Deitel & Associates, Inc. All rights reserved. 27.7 Server-Side Includes (V) length() function –Returns length of string 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

41  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Execute Perl script counter.pl using EXEC CGI statement 2.1 Use ECHO VAR statements to display environmental variables 1 2 3 4 5 6 Using Server Side Includes 7 8 9 10 11 Using Server Side Includes 12 13 14 15 The Greenwich Mean Date is 16 17 18. 19 20 The name of this document is 21 22 23 24 25 The local date is 26 27 28 29 30 This document was last modified on 31 32

42  2000 Deitel & Associates, Inc. All rights reserved. Outline 2.2 Continue printing environmental variables using ECHO VAR statements 33 34 35 Your current IP Address is 36 37 38 39 40 My server name is 41 42 43 44 45 And I am using the 46 47 48 49 Web Server. 50 You are using 51 52 53. 54 55 This server is using 56 57. 58 59 60 61 62 This document was last modified on 63 64 65 66 67 68

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

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

45  2000 Deitel & Associates, Inc. All rights reserved. 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)

46  2000 Deitel & Associates, Inc. All rights reserved. 27.8 Verifying a Username and Password (II) If file cannot be opened –Use function die to exit program and print message while –Executes structure while still information in fileHandle split function –Read contents of a file into an array @arrayName = split(/\n/) –Creates array arrayName, 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

47  2000 Deitel & Associates, Inc. All rights reserved. 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 functionName {…} –Sets actions of user-defined function functionName –User-defined functions accessed: &functionName

48  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Print instructions 2.1 Open FORM and define ACTION attribute 3.1 Open HTML TABLE 1 2 3 4 5 6 Verifying a username and a password. 7 8 9 10 11 12 Type in your username and password below. 13 14 15 16 Note that password will be sent as plain text 17 18 19 20 21 22 23 24 <TABLE BORDER = "0" CELLSPACING = "0" STYLE = "HEIGHT: 90px; 25 WIDTH: 123px" CELLPADING = "0"> 26 27 28 29 Username: 30 31 32

49  2000 Deitel & Associates, Inc. All rights reserved. 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 33 34 35 <INPUT SIZE = "40" NAME = "USERNAME" 36 STYLE = "HEIGHT: 22px; WIDTH: 115px"> 37 38 39 40 41 42 Password: 43 44 45 46 47 <INPUT SIZE = "40" NAME = "PASSWORD" 48 STYLE = "HEIGHT: 22px; WIDTH: 115px" 49 TYPE = PASSWORD> 50 51 52 53 54 <INPUT TYPE = "submit" VALUE = "Enter" 55 STYLE = "HEIGHT: 23px; WIDTH: 47px"> 56 57 58 59 60 61

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

51  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 1# Fig. 27.25: password.pl 2# Program to search a database for usernames and passwords. 3use CGI qw/:standard/; 4 5my $username = param(USERNAME); 6my $password = param(PASSWORD); 7 8open(FILE, "data.txt") || 9 die "The database could not be opened"; 10 11 while( ) 12 { 13 @data = split(/\n/); 14 15 foreach $entry (@data) 16 { 17 ($name, $pass) = split(/,/, $entry); 18 19 if($name eq "$username") 20 { 21 $userverified = 1; 22 if ($pass eq "$password") 23 { 24 $passwordverified = 1; 25 } 26 } 27 } 28 } 29

52  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 33 { 34 &accessgranted; 35 } 36 elsif ($userverified && !$passwordverified) 37 { 38 &wrongpassword; 39 } 40 else 41 { 42 &accessdenied; 43 } 44 45sub accessgranted 46{ 47 print header; 48 print " Thank You "; 49 print " "; 50 print " Permission has been granted $username."; 51 print " Enjoy the site. "; 52} 53 30 close(FILE); 31 32 if ($userverified && $passwordverified)

53  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 65sub accessdenied 66{ 67 print header; 68 print " Access Denied "; 69 print " "; 70 print "You were denied access to this server."; 71 print " "; 72 exit; 73} 54sub wrongpassword 55{ 56 print header; 57 print " Access Denied "; 58 print " "; 59 print "You entered an invalid password. "; 60 print "Access has been denied. "; 61 exit; 62 63} 64

54  2000 Deitel & Associates, Inc. All rights reserved. Outline 1account1,password1 2account2,password2 3account3,password3 4account4,password4 5account5,password5 6account6,password6 7account7,password7 8account8,password8 9account9,password9 10account10,password10 Data.txt 1.1 Input username and password combinations using format: username,password/n

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

56  2000 Deitel & Associates, Inc. All rights reserved. 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

57  2000 Deitel & Associates, Inc. All rights reserved. 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 JavaScript datasend function –Tells mail server that a command is being issued smtp->quit; –Closes connection to smtp server

58  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open FORM and define ACTION attribute 2.1 Inset and define INPUT submit image 2.2 Insert text INPUT s for other email field categories 1 2 3 4 5 Web-based email interface. 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 To: 22 23 24 25 26 27 28 29 30 31 From: 32

59  2000 Deitel & Associates, Inc. All rights reserved. Outline 2.3 Insert and define remaining INPUT elements for email fields 2.4 Insert and define TEXTAREA for body of email message 33 34 35 36 37 38 39 40 41 Subject: 42 43 44 45 46 47 48 49 50 Mail 51 Server: 52 53 54 55 56 57 58 59 60 Message: 61 62 63 <TEXTAREA COLS = 50 NAME = "MESSAGE" ROWS = 6 64 STYLE = "HEIGHT: 170px; WIDTH: 538px">

60  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Close TABLE and FORM tags 65 66 67 68 69 70 71 Script Output

61  2000 Deitel & Associates, Inc. All rights reserved. Outline 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 4.1 Connect to SMTP server 4.2 Form email message using data(), datasend() and dataend() functions 4.3 quit smtp server 1# Fig. 27.28: mail.pl 2# Program to send email from a Web-based form. 3 4use Net::SMTP; 5use CGI qw/:standard/; 6 7my $to = param("TO"); 8my $from = param("FROM"); 9my $subject = param("SUBJECT"); 10my $message = param("MESSAGE"); 11my $mailserver = param("MAILSERVER"); 12 13print header; 14print " The request has been Processed. "; 15print "Thank You $from "; 16 17$smtp = Net::SMTP->new($mailserver); 18 19$smtp->mail($ENV{USER}); 20$smtp->to("$to"); 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"); 27$smtp->dataend(); 28 29$smtp->quit;

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

63  2000 Deitel & Associates, Inc. All rights reserved. 27.10 Using ODBC to Connect to a Database Databases allow companies to –Enter world of e-commerce –Maintain crucial data Perl package Win32-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

64  2000 Deitel & Associates, Inc. All rights reserved. 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 Win32::ODBC object. $Data = new Win32::ODBC($DSN) new specifies that a new instance of the object is to be created –Win32::ODBC::Error Returns error that occurred Query string sent to database $Data->Sql($querystring) –If fails, error message is returned

65  2000 Deitel & Associates, Inc. All rights reserved. 27.10 Using ODBC to Connect to a Database (III) Method DataHash –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

66  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open and define FORM 1.2 Insert and define text INPUT for entering SQL query 1.3 Insert INPUT button 1 2 3 4 5 6 Sample Database Query 7 8 9 10 11 12 13 Querying an ODBC database. 14 15 16 17 <INPUT TYPE = "TEXT" NAME = "QUERY" SIZE = 40 18 VALUE = "SELECT * FROM AUTHORS"> 19 20 21 22

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

68  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use Win32::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 1# Fig. 27.31: data.pl 2# Program to query a database and send 3# results to the client. 4 5use Win32::ODBC; 6use CGI qw/:standard/; 7 8my $querystring = param(QUERY); 9$DSN = "Products"; 10 11print header; 12 13if (!($Data = new Win32::ODBC($DSN))) 14{ 15 print "Error connecting to $DSN\n"; 16 print "Error: ". Win32::ODBC::Error(). "\n"; 17 exit; 18} 19 20if ($Data->Sql($querystring)) 21{ 22 print "SQL failed.\n"; 23 print "Error: ". $Data->Error(). "\n"; 24 $Data->Close(); 25 exit; 26} 27 28print " "; 29print " "; 30print " Search Results "; 31 32$counter = 0;

69  2000 Deitel & Associates, Inc. All rights reserved. Outline 5.1 Insert records into array and execute DataHash 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 33 34print " "; 35 36while($Data->FetchRow()) 37{ 38 39 %Data = $Data->DataHash(); 40 41 42 print " "; 43 44 foreach $key( keys( %Data ) ) 45 { 46 print " $Data{$key} "; 47 } 48 print " "; 49 $counter++; 50} 51print " "; 52print " Your search yielded $counter results."; 53print " "; 54print " "; 55print "Please email comments to "; 56print " Deitel "; 57print "and Associates, Inc.."; 58print end_html; 59 60$Data->Close();

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

71  2000 Deitel & Associates, Inc. All rights reserved. 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

72  2000 Deitel & Associates, Inc. All rights reserved. 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

73  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 1 2 3 4 5 6 Writing a cookie to the client computer 7 8 9 10 11 12 13 Click Write Cookie to save your cookie data. 14 15 16 17 Name: 18 19 Height: 20 21 Favorite Color 22 23 24 25 26

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

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

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

77  2000 Deitel & Associates, Inc. All rights reserved. 27.11 Cookies and Perl (III) Cookies are read from client machine using Perl –Function &readCookies 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

78  2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use CGI standard library 1.2 print header 2.1 Call function readCookies to and store info in %cookie 3.1 Use foreach structure to output cookie info 4.1 Define function readCookies 4.2 Put cookie information into an array 1# Fig. 27.36: read_cookies.pl 2# Program to read cookies from the client’s computer 3 4use CGI qw/:standard/; 5 6print header; 7print " "; 8print " "; 9print " The following data is saved in a cookie on your "; 10print "computer. "; 11 12my %cookie = &readCookies; 13 14print ("<TABLE ", 15 "BORDER = \"5\" ", 16 "CELLSPACING = \"0\" ", 17 "CELLPADDING = \"10\">"); 18 19foreach $cookie_name (keys %cookie) 20{ 21 print " "; 22 print " $cookie_name "; 23 print " $cookie{$cookie_name} "; 24 print " "; 25} 26print " "; 27 28sub readCookies 29{ 30 my @cookie_values = split (/; /,$ENV{’HTTP_COOKIE’}); 31 32 foreach (@cookie_values)

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

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

81  2000 Deitel & Associates, Inc. All rights reserved. 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

82  2000 Deitel & Associates, Inc. All rights reserved. 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 1# Fig. 27.38: search.pl 2# Program to search for Web pages 3 4use CGI qw/:standard/; 5 6my $search = param(SEARCH); 7my $counter = 0; 8 9print header; 10print " "; 11 12open(FILE, "urls.txt") || 13 die "The URL database could not be opened"; 14 15while( ) 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 " Search Results: "; 28 } 29 30 print " "; 31 print "http://$url/"; 32 print " ";

83  2000 Deitel & Associates, Inc. All rights reserved. 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 33 print " $data "; 34 $counter++; 35 } 36 } 37} 38close FILE; 39 40if ($counter == 0) 41{ 42 print " Sorry, no results were found matching "; 43 print " $search. "; 44} 45else 46{ 47 print " $counter matches found for "; 48 print " $search "; 49} 50This site contains information about Perl and CGI;www.perl.com 51The Deitel and Deitel Web Site;www.deitel.com 52Purchase books on this web site;www.amazon.com 53Perl for the Win32 platform;www.activestate.com 54The Perl Mongers Web page;www.pm.org 55Monthly online Perl periodical;www.perlmonth.com

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

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


Download ppt " 2000 Deitel & Associates, Inc. All rights reserved. Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI)"

Similar presentations


Ads by Google