Based on material 2000 Deitel & Associates, Inc. 1 Chapter 27 – CGI (Common Gateway Interface)...

90
1 Based on material 2000 Deitel & Associates, Inc. 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

Transcript of Based on material 2000 Deitel & Associates, Inc. 1 Chapter 27 – CGI (Common Gateway Interface)...

1

Based on material 2000 Deitel & Associates, Inc.

Chapter 27 – CGI (Common Gateway Interface) and Perl 5

Outline27.1 Common Gateway Interface (CGI)27.2 Introduction to Perl27.3 Configuring Personal Web Server (PWS) for

Perl/CGI27.4 String Processing and Regular Expressions27.5 Viewing Client/Server Environment Variables27.6 Form Processing and Business Logic27.7 Server-Side Includes27.8 Verifying a Username and Password27.9 Sending E-mail from a Web Browser27.10 Using ODBC to Connect to a Database27.11 Cookies and Perl27.12 Case Study: Building a Search Engine

2

Based on material 2000 Deitel & Associates, Inc.

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 specify name of server from

which to request data

3

Based on material 2000 Deitel & Associates, Inc.

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• Often reside in the directory /cgi-bin

• Within Web server– Permission granted by webmaster to allow specific

programs to be executed on the server

4

Based on material 2000 Deitel & Associates, Inc.

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 client for rendering

• CGI is an interface– Cannot be directly programmed– Script or executable program must be used to interact with it

5

Based on material 2000 Deitel & Associates, Inc.

27.1 Common Gateway Interface (CGI) (IV)

Data path of a typical CGI-based application

6

Based on material 2000 Deitel & Associates, Inc.

27.2 Introduction to Perl Perl (Practical Extraction and Report Language)

– High-level programming language

– Developed by Larry Wall in 1987• Trained as a linguist

• A systems admin at NASA

– Rich, easy-to-use text-processing capabilities

– Alternative to the tricky C programming language

– Powerful alternative to Unix shell scripts• Lots of built-in functionality

• TMTOWTDI

7

Based on material 2000 Deitel & Associates, Inc.

27.2 Introduction to Perl• Current version: Perl 5.006

– Programming Perl (1st ed.) was about Perl 4

– Perl 5 is a complete rewrite

– An entirely new language

• Good choice for programming server side WWW– Most popular language for doing so today

– Is under continuous update by the online Perl community Stays competitive with newer server-side technologies

Programmer driven

Extensible by modular objects Can even search the online object-base to find newer versions

8

Based on material 2000 Deitel & Associates, Inc.

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 –w followed by filename of Perl source code at

command line (Unix or DOS prompt)

9

Based on material 2000 Deitel & Associates, Inc.

27.2 Introduction to Perl (III)Perl command line switches (case sensitive)

Command-line switch

Description

-e ’command’ Interpret one line of Perl code -S Search for the specified script using the PATH environment variable -U Allow unsafe operations to be executed -v Print the version of Perl -w Allow warnings to be displayed on compilation of the script -h Display all options for perl

10

Based on material 2000 Deitel & Associates, Inc.

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 sequences– E.g. \n, \t, \a– Newline, tab, alert

• Statements terminated with semicolons (;)– Exception: where braces ({}) used to denote block of code

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

Outline

1.1 Print Statement

1 # Fig. 27.4: first.pl2 # A first program in Perl.34 print "Welcome to Perl!\n";

Welcome to Perl!

12

Based on material 2000 Deitel & Associates, Inc.

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 (associative array)– Uses keys that are strings to reference individual array elements

– Variables should be initialized before being used

• Variable names in strings– Serve as place-holders for values they represent

– If have no declared value – set to undef (empty) value

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

5 print "Using a variable before initializing: $var\n";

6

7 # using a variable in a numeric context

8 $test = $num + 5;

9 print "Adding uninitialized variable num to 5 yields: $test.\n";

10

11 $a = 5;

12 print "The value of variable a is: $a\n";

13

14 $a = $a + 5;

15 print "Variable a after adding 5 is $a.\n";

16

17 $b = "A string value";

18 $a = $a + $b;

19

20 print "Adding a string to an integer yields: $a\n";

21

22 $number = 7;

23 $b = $b + $number;

24

25 print "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: 5Variable a after adding 5 is 10.Adding a string to an integer yields: 10Adding an integer to a string yields: 7

14

Based on material 2000 Deitel & Associates, Inc.

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]– Just like C, C++, etc.– Could be changed in Perl 4 but should not in Perl 5

15

Based on material 2000 Deitel & Associates, Inc.

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)

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

6 print "The array contains:\n\n";

7 print "@array \n\n";

8 print "Third element: $array[2]\n\n";

9

10 @array2 = (A..Z);

11

12 print "The range operator is used to store all\n";

13 print "letters from capital A to Z:\n\n";

14 print "@array2 \n";

The array contains:

Bill Bobby Sue Michelle

Third element: Sue

The 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

17

Based on material 2000 Deitel & Associates, Inc.

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 at http://www.cpan.org http://www.activestate.com/packages

18

Based on material 2000 Deitel & Associates, Inc.

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 Deitel, et al.

19

Based on material 2000 Deitel & Associates, Inc.

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– Designates variable only valid for block of code in which it is

declared

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

4 my $stringa = "Test";

5 my $stringb = "Testing";

6

7 if ($stringa eq "Test")

8 {

9 print "$stringa matches Test.\n";

10 }

11 else

12 {

13 print "$stringa does not match Test.\n";

14 }

15

16 if ($stringb eq "Test")

17 {

18 print "$stringb matches Test.\n";

19 }

20 else

21 {

22 print "$stringb does not match Test.\n";

23 }

Test matches Test.Testing does not match Test.

21

Based on material 2000 Deitel & Associates, Inc.

27.4 my and local

• Keyword my– Designates variable only valid for block of code in which it is

declared

– In Perl 4 was done by local

• my creates local variables

• local creates local copy & then restores it on exit

• See program …

22

Based on material 2000 Deitel & Associates, Inc.

my and local (program)$lo = 'global'; $m = ‘global'; A();sub A { local $lo = 'string'; my $m = 'string'; B();}sub B { print "B can", ($lo eq 'string' ?'can' :'cannot'), " see the value of lo set by A.\n"; print "B can", ($m eq 'string' ?'can' :'cannot'), " see the value of m set by A.\n";}------------------------------------------------------------

-B can see the value of lo set by A.B cannot see the value of m set by A.

23

Based on material 2000 Deitel & Associates, Inc.

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

24

Based on material 2000 Deitel & Associates, Inc.

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

Modifying Character

Purpose

/g Search everywhere for the expression (global search). /i Ignores the case of the search string. /m The string is evaluated as if it had multiple lines (i.e., contains

multiple newline characters) of text. /s Ignore the newline character and treat it as whitespace. The text

is seen as a single line. /x All whitespace characters are ignored when searching the string.

2000 Deitel & Associates, Inc. All rights reserved. 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.pl2 # searches using the matching operator and regular expressions34 $search = "Testing pattern matches";56 if ( $search =~ /Test/ )7 {8 print "Test was found.\n";9 }1011 if ( $search =~ /^Test/ )12 {13 print "Test was found at the beginning of the line.\n";14 }1516 if ( $search =~ /Test$/ )17 {18 print "Test was found at the end of the line.\n";19 }2021 if ( $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

26

Based on material 2000 Deitel & Associates, Inc.

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

27

Based on material 2000 Deitel & Associates, Inc.

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. 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

3 use CGI qw/:standard/;

4

5 print header;

6 print "<HTML>";

7 print " <HEAD>";

8 print " <TITLE>Environment Variables...</TITLE>";

9 print " </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 " WIDTH = 100%>";

14

15 foreach $key (sort keys %ENV)

16 {

17 print "<TR>";

18 print "<TD BGCOLOR = #11BBFF><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 " </TABLE>";

25 print " </BODY>";

26 print "</HTML>";

29

Based on material 2000 Deitel & Associates, Inc.

Script Output

30

Based on material 2000 Deitel & Associates, Inc.

27.6 Form Processing and Business Logic

• HTML FORMs1. 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. 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<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2<!-- Fig. 27.20: form.html --> 34<HTML>5<HEAD>6<TITLE>Sample FORM to take user input in HTML</TITLE>7</HEAD>89<BODY BACKGROUND = "images/back.gif">10<BASEFONT FACE = "ARIAL,SANS-SERIF" SIZE = 2>1112 <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><BR>34 </FONT>35

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

Outline

1.5 Continue inserting and defining form INPUT element

1.6 Close FORM element

36 <IMG SRC = "images/downloads.gif"><BR>37 <FONT COLOR = BLUE>38 Which book would you like information about?<BR>39 </FONT>4041 <SELECT NAME = "BOOK">42 <OPTION>Internet and WWW How to Program43 <OPTION>C++ How to Program 2e44 <OPTION>Java How to Program 3e45 <OPTION>Visual Basic How to Program 1e46 </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>5455 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows NT" 56 CHECKED> 57 Windows NT58 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 95"> 59 Windows 9560 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows 98"> 61 Windows 98<BR>62 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Linux"> 63 Linux64 <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Other"> 65 Other<BR>66 <INPUT TYPE = "SUBMIT" VALUE = "Register">67 </FORM>68</BODY>69</HTML>

33

Based on material 2000 Deitel & Associates, Inc.

Script Output

34

Based on material 2000 Deitel & Associates, Inc.

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-5555if ( $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. 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.pl2 # Program to read information sent to the server3 # from the FORM in the form.html document.45 use CGI qw/:standard/;67 $os = param(OS);8 $firstname = param(FNAME);9 $lastname = param(LNAME);10 $email = param(EMAIL);11 $phone = param(PHONE);12 $book = param(BOOK);1314 print header;15 print "<BODY BACKGROUND = \"/images/back.gif\">";16 print "<BASEFONT FACE = \"ARIAL,SANS-SERIF\" SIZE = 3>";1718 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><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>";32 print " <TD BGCOLOR = #FFFFDD>OS</TD></TR>";

2000 Deitel & Associates, Inc. All rights reserved. 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 "<TR><TD>$firstname $lastname</TD><TD>$email</TD>";

34 print "<TD>$phone</TD><TD>$os</TD></TR>";

35 print "</TABLE>";

36 print "<BR><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><BR>";

50 print "Thank You.";

51 }

37

Based on material 2000 Deitel & Associates, Inc.

Script Output 1

38

Based on material 2000 Deitel & Associates, Inc.

Script Output 2

39

Based on material 2000 Deitel & Associates, Inc.

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

40

Based on material 2000 Deitel & Associates, Inc.

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 cgi-bin directory

41

Based on material 2000 Deitel & Associates, Inc.

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

42

Based on material 2000 Deitel & Associates, Inc.

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);

– print statement can redirect output to a file print COUNTWRITE $data;

• Assigns $data to file pointed to by COUNTWRITE• If the file is open for writing already

43

Based on material 2000 Deitel & Associates, Inc.

27.7 Server-Side Includes (V)

• length() function– Returns length of string

• substr( expr, len, offset ) function– Similar to JavaScript’s substr function

– First argument (expr)• Specifies string from which to take a substring

– Second argument (offset)• Specifies offset in characters from beginning of the string

– Third argument (len)• Specifies length of substring to return

2000 Deitel & Associates, Inc. All rights reserved. 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<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2<!-- Fig. 27.22 counter.shtml -->34<HTML>5 <HEAD>6 <TITLE>Using Server Side Includes</TITLE>7 </HEAD>89<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

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

Outline

2.2 Continue printing environmental variables using ECHO VAR statements

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><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>68</HTML>

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

5 open(COUNTREAD, "counter.dat");

6 my $data = <COUNTREAD>;

7 $data++;

8 close(COUNTREAD);

9

10 open(COUNTWRITE, ">counter.dat");

11 print COUNTWRITE $data;

12 close(COUNTWRITE);

13

14 print "<CENTER>";

15 print "<STRONG>You are visitor number</STRONG><BR>";

16

17 for ($count = 0; $count < length($data);$count++)

18 {

19 $number = substr( $data, $count, 1 );

20 print "<IMG SRC=\"images/counter/$number.jpg\">";

21 }

22

23 print "</CENTER>";

47

Based on material 2000 Deitel & Associates, Inc.

Script Output

48

Based on material 2000 Deitel & Associates, Inc.

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)

49

Based on material 2000 Deitel & Associates, Inc.

27.8 Verifying a Username and Password (II)

• If file cannot be opened– Use function die to exit program and print message

• while <fileHandle>– 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 partsforeach $entry (@data) {…}– Performs indicated action on every entry in array @data– Subsequently assigns entry information to $entry

50

Based on material 2000 Deitel & Associates, Inc.

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

51

Based on material 2000 Deitel & Associates, Inc.

27.8 Verifying a Username and Password (III)

• Perl has logical and (&&) and or (||) operators– Same format as other languages

Example:

if ($userverified && $passwordverified) {…}– Evaluates to true if both variable values are true

– Short-circuit evaluation

• String context: true is any non-empty string

• Numeric context: true is any non-zero number

• String "0" is false!

52

Based on material 2000 Deitel & Associates, Inc.

27.8 Verifying a Username and Password (III)

sub functionName {…}– Sets actions of user-defined function functionName– User-defined functions accessed: &functionName

2000 Deitel & Associates, Inc. All rights reserved. 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<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2<!-- Fig. 27.24: verify.html --> 34<HTML>5<HEAD>6<TITLE>Verifying a username and a password.</TITLE>7</HEAD>89<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 = #0000FF FACE = Arial SIZE = 1>15 <STRONG>16 Note that password will be sent as plain text17 </STRONG>18 </FONT>19 </P>2021 <FORM ACTION = "/cgi-bin/password.pl" METHOD = "post">22 <BR>23 24 <TABLE BORDER = "0" CELLSPACING = "0" STYLE = "HEIGHT: 90px;25 WIDTH: 123px" CELLPADING = "0">26 <TR>27 <TD BGCOLOR = #DDDDDD COLSPAN = 3>28 <FONT FACE = Arial SIZE = 2>29 <STRONG>Username:</STRONG>30 </FONT>31 </TD>32 </TR>

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

34 <TD BGCOLOR = #DDDDDD COLSPAN = 3>

35 <INPUT SIZE = "40" NAME = "USERNAME"

36 STYLE = "HEIGHT: 22px; WIDTH: 115px">

37 </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: 22px; WIDTH: 115px"

49 TYPE = PASSWORD>

50 <BR></TD>

51 </TR>

52 <TR>

53 <TD COLSPAN = 3>

54 <INPUT TYPE = "submit" VALUE = "Enter"

55 STYLE = "HEIGHT: 23px; WIDTH: 47px">

56 </TD>

57 </TR>

58 </TABLE>

59 </FORM>

60</BODY>

61</HTML>

55

Based on material 2000 Deitel & Associates, Inc.

Script Output

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

3 use CGI qw/:standard/;

4

5 my $username = param(USERNAME);

6 my $password = param(PASSWORD);

7

8 open(FILE, "data.txt") ||

9 die "The database could not be opened";

10

11 while(<FILE>)

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

2000 Deitel & Associates, Inc. All rights reserved. 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 else41 {42 &accessdenied;43 }4445 sub accessgranted46 {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

30 close(FILE);3132 if ($userverified && $passwordverified)

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

65 sub accessdenied66 {67 print header;68 print "<TITLE>Access Denied</TITLE>";69 print "<FONT FACE=Arial SIZE=3 COLOR=Red><STRONG>";70 print "You were denied access to this server.";71 print "</STRONG></FONT>";72 exit;73 }

54 sub wrongpassword55 {56 print header;57 print "<TITLE>Access Denied</TITLE>";58 print "<FONT FACE=Arial SIZE=2 COLOR=Red><STRONG>";59 print "You entered an invalid password.<br> ";60 print "Access has been denied.</STRONG></FONT>";61 exit;6263 }64

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

Outline1 account1,password1

2 account2,password2

3 account3,password3

4 account4,password4

5 account5,password5

6 account6,password6

7 account7,password7

8 account8,password8

9 account9,password9

10 account10,password10

Data.txt

1.1 Input username and password combinations using format:

username,password/n

60

Based on material 2000 Deitel & Associates, Inc.

Script Output

61

Based on material 2000 Deitel & Associates, Inc.

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

62

Based on material 2000 Deitel & Associates, Inc.

27.9 Sending E-Mail From a Web Browser

• Create a new instance of a mail server objectsmtp = 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

2000 Deitel & Associates, Inc. All rights reserved. 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 INPUTs for other email field categories

1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2<!-- Fig. 27.27: email.html --> 3<HTML>4<HEAD>5 <TITLE>Web-based email interface.</TITLE>6</HEAD>78<BODY BACKGROUND = "images/back.gif">9 <FORM ACTION = "cgi-bin/mail.pl" METHOD = "POST">10 <TABLE BORDER = "0" CELLSPACING = "0" CELLPADING = "0">1112 <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>1819 <TR>20 <TD BGCOLOR = #DDDDDD WIDTH = "10%"><STRONG>21 <FONT FACE = "Arial" SIZE = "2">To:&nbsp;</FONT>22 </STRONG>23 </TD>24 <TD BGCOLOR = #DDDDDD><INPUT NAME = "TO">25 </TD>26 </TR>2728 <TR>29 <TD BGCOLOR = #DDDDDD>30 <P><FONT FACE = Arial SIZE = 2>31 <STRONG>From:</STRONG>32 </FONT></P>

2000 Deitel & Associates, Inc. All rights reserved. 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 </TD>34 <TD BGCOLOR = #DDDDDD><INPUT NAME = "FROM">35 </TD>36 </TR>3738 <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>4748 <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>5657 <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 64 STYLE = "HEIGHT: 170px; WIDTH: 538px"></TEXTAREA>

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

Outline

1.1 Close TABLE and FORM tags

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

Script Output

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

4 use Net::SMTP;

5 use CGI qw/:standard/;

6

7 my $to = param("TO");

8 my $from = param("FROM");

9 my $subject = param("SUBJECT");

10 my $message = param("MESSAGE");

11 my $mailserver = param("MAILSERVER");

12

13 print header;

14 print "<H3>The request has been Processed. ";

15 print "Thank You $from</H3>";

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;

67

Based on material 2000 Deitel & Associates, Inc.

Script Output

68

Based on material 2000 Deitel & Associates, Inc.

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 browser1. 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

69

Based on material 2000 Deitel & Associates, Inc.

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

70

Based on material 2000 Deitel & Associates, Inc.

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

2000 Deitel & Associates, Inc. All rights reserved. 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<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

2<!-- Fig. 27.30: data.html -->

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>

11

12 <FONT SIZE = +2>

13 <STRONG>Querying an ODBC database.</STRONG>

14 </FONT><BR>

15

16 <FORM METHOD = "POST" ACTION = "cgi-bin/data.pl">

17 <INPUT TYPE = "TEXT" NAME = "QUERY" SIZE = 40

18 VALUE = "SELECT * FROM AUTHORS"><BR><BR>

19 <INPUT TYPE = "SUBMIT" VALUE = "Send Query">

20 </FORM>

21</BODY>

22</HTML>

72

Based on material 2000 Deitel & Associates, Inc.

Script Output

2000 Deitel & Associates, Inc. All rights reserved. 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.pl2 # Program to query a database and send 3 # results to the client.45 use Win32::ODBC;6 use CGI qw/:standard/;78 my $querystring = param(QUERY);9 $DSN = "Products";1011 print header;1213 if (!($Data = new Win32::ODBC($DSN)))14 {15 print "Error connecting to $DSN\n";16 print "Error: " . Win32::ODBC::Error() . "\n";17 exit;18 }1920 if ($Data->Sql($querystring))21 {22 print "SQL failed.\n";23 print "Error: " . $Data->Error() . "\n";24 $Data->Close();25 exit;26 }2728 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>";3132 $counter = 0;

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

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

35

36 while($Data->FetchRow())

37 {

38

39 %Data = $Data->DataHash();

40

41

42 print "<TR>";

43

44 foreach $key( keys( %Data ) )

45 {

46 print "<TD BGCOLOR = #9999CC>$Data{$key}</TD>";

47 }

48 print "</TR>";

49 $counter++;

50 }

51 print "</TABLE>";

52 print "<BR>Your search yielded <B>$counter</B> results.";

53 print "<BR><BR>";

54 print "<FONT SIZE = 2>";

55 print "Please email comments to ";

56 print "<A href = \"mailto:deitel\@deitel.com\">Deitel ";

57 print "and Associates, Inc.</A>.";

58 print end_html;

59

60 $Data->Close();

75

Based on material 2000 Deitel & Associates, Inc.

Script Output

76

Based on material 2000 Deitel & Associates, Inc.

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

77

Based on material 2000 Deitel & Associates, Inc.

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:[email protected]

2000 Deitel & Associates, Inc. All rights reserved. 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<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2<!-- Fig. 27.32: cookies.html --> 34<HTML>5 <HEAD>6 <TITLE>Writing a cookie to the client computer</TITLE>7 </HEAD>89<BODY BACKGROUND = "images/back.gif">10<BASEFONT FACE = "ARIAL,SANS-SERIF" SIZE = 2>1112 <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>

79

Based on material 2000 Deitel & Associates, Inc.

Script Output

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

Outline1 # Fig. 27.33: cookies.pl2 # Program to write a cookie to a client’s machine34 use CGI qw/:standard/;56 my $name = param(NAME);7 my $height = param(HEIGHT);8 my $color = param(COLOR);910 $expires = "Monday, 20-Dec-99 16:00:00 GMT";11 $path = ""; 12 $server_domain = "127.0.0.1";1314 print "Set-Cookie: ";15 print "Name", "=", $name, "; expires=", $expires, 16 "; path=", $path, "; domain=", $server_domain, "\n";1718 print "Set-Cookie: ";19 print "Height", "=", $height, "; expires=", $expires, 20 "; path=", $path, "; domain=", $server_domain, "\n";2122 print "Set-Cookie: ";23 print "Color", "=", $color, "; expires=", $expires, 24 "; path=", $path, "; domain=", $server_domain, "\n";2526 print header;27 print "<BODY BACKGROUND = \"/images/back.gif\">";28 print "<BASEFONT FACE = \"ARIAL,SANS-SERIF\" SIZE = 3>";29 print "The cookie has been set with the folowing data:";30 print "<BR><BR>";31 print "<FONT COLOR=BLUE>Name:</FONT> $name <BR>";32 print "<FONT COLOR = BLUE>Height:</FONT> $height<BR>";33 print "<FONT COLOR = BLUE>Favorite Color:</FONT> ";34 print "<FONT COLOR = $color> $color<BR>";

81

Based on material 2000 Deitel & Associates, Inc.

Script Output

82

Based on material 2000 Deitel & Associates, Inc.

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

2000 Deitel & Associates, Inc. All rights reserved. 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.pl2 # Program to read cookies from the client’s computer34 use CGI qw/:standard/;56 print header;7 print "<BODY BACKGROUND = \"/images/back.gif\">";8 print "<BASEFONT FACE = \"ARIAL,SANS-SERIF\" SIZE = 3>";9 print "<STRONG>The following data is saved in a cookie on your ";

10 print "computer.</STRONG><BR><BR>";1112 my %cookie = &readCookies; 1314 print ("<TABLE ",15 "BORDER = \"5\" ",16 "CELLSPACING = \"0\" ",17 "CELLPADDING = \"10\">");1819 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>";2728 sub readCookies29 {30 my @cookie_values = split (/; /,$ENV{’HTTP_COOKIE’});31 32 foreach (@cookie_values)

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

85

Based on material 2000 Deitel & Associates, Inc.

Script Output

86

Based on material 2000 Deitel & Associates, Inc.

27.12 Case Study: Building a Search Engine

• Search engines– Allow clients to search through catalogs of info for data

• Typical search process1. 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. 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.pl2 # Program to search for Web pages34 use CGI qw/:standard/;56 my $search = param(SEARCH);7 my $counter = 0;89 print header;10 print "<BASEFONT FACE = \"ARIAL,SANS-SERIF\" SIZE = 3>";1112 open(FILE, "urls.txt") || 13 die "The URL database could not be opened";1415 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><BR></STRONG>";28 }29 30 print "<A HREF=\"http://$url/\">";31 print "http://$url/";32 print "</A>";

2000 Deitel & Associates, Inc. All rights reserved. 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 "<BR>$data<BR><BR>";34 $counter++;35 }36 }37 }38 close FILE;3940 if ($counter == 0)41 {42 print "<B>Sorry, no results were found matching </B>";43 print "<FONT COLOR = BLUE>$search</FONT>. ";44 }45 else46 {47 print "<STRONG>$counter matches found for </STRONG>";48 print "<FONT COLOR = BLUE>$search</FONT>";49 }

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 Win32 platform;www.activestate.com

54 The Perl Mongers Web page;www.pm.org

55 Monthly online Perl periodical;www.perlmonth.com

89

Based on material 2000 Deitel & Associates, Inc.

Script Output

90

Based on material 2000 Deitel & Associates, Inc.

Script Output