Download presentation
Presentation is loading. Please wait.
Published byΦυλλίδος Αναγνώστου Modified over 6 years ago
1
Chapter 27 - Perl and CGI (Common Gateway Interface)
Outline Introduction Perl String Processing and Regular Expressions Viewing Client/Server Environment Variables Form Processing and Business Logic Server-Side Includes Verifying a Username and Password Using DBI to Connect to a Database Cookies and Perl Operator Precedence Chart Internet and World Wide Web Resources
2
27.1 Introduction Fig Data path of a typical CGI-based application.
3
Function print writes the string “Welcome to Perl!/n” to the screen.
1 #!/usr/bin/perl 2 # Fig. 27.2: fig27_02.pl 3 # A first program in Perl. 4 5 print( "Welcome to Perl!\n" ); The “shebang” construct (#!) indicates the path to the Perl interpreter on Unix systems. Single-line comment. Fig27_02.pl Program Output Function print writes the string “Welcome to Perl!/n” to the screen. Newline escape sequence. Welcome to Perl!
4
27.2 Perl
5
Create scalar variable $number and set its value to 5.
1 #!/usr/bin/perl 2 # Fig. 27.4: fig27_04.pl 3 # Program to illustrate the use of scalar variables. 4 5 $number = 5; 6 print( "The value of variable \$number is: $number\n\n" ); 7 8 $number += 5; 9 print( "Variable \$number after adding 5 is: $number\n" ); 10 11 $number *= 2; 12 print( "Variable \$number after multiplying by 2 is: " ); 13 print( "$number\n\n\n" ); 14 15 # using an uninitialized variable in the context of a string 16 print( "Using a variable before initializing: $variable\n\n" ); 17 18 # using an uninitialized variable in a numeric context 19 $test = $undefined + 5; 20 print( "Adding uninitialized variable \$undefined " ); 21 print( "to 5 yields: $test\n" ); 22 23 # using strings in numeric contexts 24 $string = "A string value"; 25 $number += $string; 26 print( "Adding a string to an integer yields: $number\n" ); 27 28 $string2 = "15charactersand1"; 29 $number2 = $number + $string2; 30 print( "Adding $number to string \"$string2\" yields: " ); 31 print( "$string2\n" ); Fig27_04.pl Create scalar variable $number and set its value to 5. Use the addition assignment operator (+=) to add 5 to variable $number. Use the multiplication assignment operator (*=) to multiply variable $number by 2. Using an uninitialized variable ($variable) in the context of a string evaluates to an empty string (“”). Using an uninitialized variable ($undefined) in numeric context evaluates to 0. Adding a string that begins with numbers to an integer evaluates the string to every character up to, but not including, the first nondigit character. Adding a string to an integer evaluates to undef unless it begins with a digit.
6
Program Output The value of variable $number is: 5
The value of variable $number is: 5 Variable $number after adding 5 is: 10 Variable $number after multiplying by 2 is: 20 Using a variable before initializing: Adding uninitialized variable $undefined to 5 yields: 5 Adding a string to an integer yields: 20 Adding 20 to string "15charactersand1" yields: 15charactersand1 Program Output
7
Initializing array @array.
1 #!/usr/bin/perl 2 # Fig. 27.5: fig27_05.pl 3 # Program to demonstrate arrays in Perl. 4 5 @array = ( "Bill", "Bobby", "Sue", "Michelle" ); 6 7 print( "The array ); 8 print( "Printing array outside of quotes: "\n\n" ); 9 10 print( "Third element: $array[ 2 ]\n" ); 11 12 $number = 3; 13 print( "Fourth element: $array[ $number ]\n\n" ); 14 15 @array2 = ( 'A' .. 'Z' ); 16 print( "The range operator is used to create a list of\n" ); 17 print( "all capital letters from A to Z:\n" ); 18 print( \n\n" ); 19 20 $array3[ 3 ] = "4th"; 21 print( "Array with just one element \n\n" ); 22 23 print( 'Printing literal using single quotes: ' ); 24 print( and \n', "\n" ); 25 26 print( "Printing literal using backslashes: " ); 27 print( and \\n\n" ); Fig27_05.pl Initializing Printing an array outside of double quotes prints the element values without inserting spaces between them. Individual array elements are accessed by using square brackets ([]). Initializing to contain the capital letters A to Z inclusive. Assign a value to the fourth element of uninitialized The backslash character may also be used to escape special characters. Enclosing special characters in single quotes prints the literal string.
8
Program Output The array contains: Bill Bobby Sue Michelle
The array contains: Bill Bobby Sue Michelle Printing array outside of quotes: BillBobbySueMichelle Third element: Sue Fourth element: Michelle The range operator is used to create a list of all capital letters from 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 Array with just one element initialized: 4th Printing literal using single and \n Printing literal using and \n Program Output
9
1 #!/usr/bin/perl 2 # Fig. 27.6: fig27_06.pl 3 # Program to demonstrate the eq, ne, lt, gt operators. 4 5 @fruits = qw( apple orange banana ); 6 7 foreach $item ) { 8 if ( $item eq "banana" ) { print( "String '$item' matches string 'banana'\n" ); } 12 if ( $item ne "banana" ) { print( "String '$item' does not match string 'banana'\n" ); } 16 if ( $item lt "banana" ) { print( "String '$item' is less than string 'banana'\n" ); } 20 if ( $item gt "banana" ) { print( "String '$item' is greater than string 'banana'\n" ); } 24 } Fig27_06.pl Program Output The foreach structure iterates sequentially through the elements Operators eq, lt, and gt test strings for equality, less-than and greater –than, respectively. The if structure tests a condition and executes the block of code if the condition evaluates to true. String 'apple' does not match string 'banana' String 'apple' is less than string 'banana' String 'orange' does not match string 'banana' String 'orange' is greater than string 'banana' String 'banana' matches string 'banana'
10
The $ metacharacter searches the end of a string for a pattern.
1 #!/usr/bin/perl 2 # Fig 27.7: fig27_07.pl 3 # Searches using the matching operator and regular expressions. 4 5 $search = "Now is is the time"; 6 print( "Test string is: '$search'\n\n" ); 7 8 if ( $search =~ /Now/ ) { print( "String 'Now' was found.\n" ); 10 } 11 12 if ( $search =~ /^Now/ ) { print( "String 'Now' was found at the beginning of the line." ); print( "\n" ); 15 } 16 17 if ( $search =~ /Now$/ ) { print( "String 'Now' was found at the end of the line.\n" ); 19 } 20 21 if ( $search =~ /\b ( \w+ ow ) \b/x ) { print( "Word found ending in 'ow': $1 \n" ); 23 } 24 25 if ( $search =~ /\b ( \w+ ) \s ( \1 ) \b/x ) { print( "Repeated words found: $1 $2\n" ); 27 } 28 29 @matches = ( $search =~ / \b ( t \w+ ) \b /gx ); 30 print( "Words beginning with 't' ); The binding operator (=~) binds whatever is on the left side to the regular-expression operator on its right Fig27_07.pl The match operator (m//) uses regular expressions to search a string for a specified pattern. The $ metacharacter searches the end of a string for a pattern. The caret metacharacter (^) matches the beginning of a string. Parentheses indicate that the text matching the pattern is to be saved in a special Perl variable (e.g., $1, etc.) \w matches any alphanumeric character. The + modifier matches the preceding character one or more times. Modifying character x indicates that all whitespace characters should be ignored in the string. \b matches any word boundary \s ignores the newline character and treats it as whitespace. is assigned the value of a list of all matching words. \1 evaluates to the word that was matched in the first parenthetical expression. Modifying character g indicates a global search that does not stop after the first match is found.
11
Program Output Test string is: 'Now is is the time'
Test string is: 'Now is is the time' String 'Now' was found. String 'Now' was found at the beginning of the line. Word found ending in 'ow': Now Repeated words found: is is Words beginning with 't' found: the time Program Output
12
27.3 String Processing and Regular Expressions
13
27.3 String Processing and Regular Expressions
14
Function sort orders the array of keys alphabetically.
1 #!/usr/bin/perl 2 # Fig : fig27_11.pl 3 # Program to display CGI environment variables. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 10 11 print( header() ); 12 13 print( start_html( { dtd => $dtd, title => "Environment Variables..." } ) ); 15 16 print( "<table style = \"border: 0; padding: 2; font-weight: bold\">" ); 18 19 print( Tr( th( "Variable Name" ), th( "Value" ) ) ); 21 22 print( Tr( td( hr() ), td( hr() ) ) ); 23 24 foreach $variable ( sort( keys( %ENV ) ) ) { 25 print( Tr( td( { style => "background-color: #11bbff" }, $variable ), td( { style => "font-size: 12pt" }, $ENV{ $variable } ) ) ); 30 print( Tr( td( hr() ), td( hr() ) ) ); 32 } 33 34 print( "</table>" ); 35 print( end_html() ); Fig27_11.pl The import tag :standard imports a predefined set of standard functions. The use statement instructs Perl programs to include the contents (e.g., functions) of predefined packages called modules. Instruct the Perl script to print a valid HTTP header, using function header from the CGI library. The start_html function prints the document type definition for this document, as well as several opening XHTML tags (<html>, <head>, <title>, etc., up to the opening <body> tag). Functions Tr and th place their arguments between table row and table header tags, respectively Function Tr is called again with the hr and td functions, in order to print a row of horizontal rules within <td> tags. The foreach loop iterates sequentially through the array returned by sort, repeatedly assigning the current key’s value to scalar $variable. Function sort orders the array of keys alphabetically. Function keys returns an unordered array containing all the keys in the %ENV hash. The %ENV hash is a built-in table in Perl that contains the names and values of all the environment variables. Hash values are accessed using the syntax $hashName{ keyName }. In this example, each key in hash %ENV is the name of an environment variable name (e.g., HTTP_HOST). Specifies the value for the attribute style. The name of the attribute is specified on the left, followed by its value on the right. Function end_html returns the closing tags for the page (</body> and </html>).
15
Program Output
16
A unique name is assigned to each form field.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : fig27_12.html --> 5 6 <html> <head> <title>Sample form to take user input in XHTML</title> </head> 10 <body style = "font-face: arial; font-size: 12pt"> 12 <div style = "font-size: 14pt; font-weight: bold"> This is a sample registration form. </div> 16 <br /> Please fill in all fields and click Register. 19 <form method = "post" action = "/cgi-bin/fig27_13.pl"> 21 <img src = "images/user.gif" /><br /> 23 <div style = "color: blue" > Please fill out the fields below.<br /> </div> 27 <img src = "images/fname.gif" /> <input type = "text" name = "fname" /><br /> <img src = "images/lname.gif" /> <input type = "text" name = "lname" /><br /> <img src = "images/ .gif" /> <input type = "text" name = " " /><br /> <img src = "images/phone.gif" /> <input type = "text" name = "phone" /><br /> Fig27_12.html Form element which indicates that, when the user clicks Register, the form information is posted to the server. The statement action = "cgi-bin/ fig27_13.pl" directs the server to execute the fig27_13.pl Perl script (located in the cgi-bin directory) to process the posted form data. A unique name is assigned to each form field.
17
Fig27_12.html 36 37 <div style = "font-size: 10pt">
Must be in the form (555) <br /><br /> </div> 40 <img src = "images/downloads.gif" /><br /> <div style = "color: blue"> Which book would you like information about?<br /> </div> 45 <select name = "book"> <option>Internet and WWW How to Program 2e</option> <option>C++ How to Program 3e</option> <option>Java How to Program 4e</option> <option>XML How to Program 1e</option> </select><br /><br /> 52 <img src = "images/os.gif" /><br /> <div style = "color: blue"> Which operating system are you currently using? </div><br /> 57 <input type = "radio" name = "os" value = "Windows NT" checked /> Windows NT<input type = "radio" name = "os" value = "Windows 2000" /> Windows 2000<input type = "radio" name = "os" value = "Windows 98/me" /> Windows 98/me<br /><input type = "radio" name = "os" value = "Linux" /> Linux<input type = "radio" name = "os" value = "Other" /> Other<br /><input type = "submit" value = "Register" /> </form> Fig27_12.html
18
Fig27_12.html Program Output
</body> 72 </html> Fig27_12.html Program Output
19
The br function adds a line break (<br />) to the XHTML page
1 #!/usr/bin/perl 2 # Fig : fig27_13.pl 3 # Program to read information sent to the server 4 # from the form in the fig27_12.html document. 5 6 use CGI qw( :standard ); 7 8 $os = param( "os" ); 9 $firstName = param( "fname" ); 10 $lastName = param( "lname" ); 11 $ = param( " " ); 12 $phone = param( "phone" ); 13 $book = param( "book" ); 14 15 $dtd = 16 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 18 19 print( header() ); 20 21 print( start_html( { dtd => $dtd, title => "Form Results" } ) ); 23 24 if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) { print( "Hi " ); print( span( { style => "color: blue; font-weight: bold" }, $firstName ) ); print( "!" ); 29 print( "\nThank you for completing the survey." ); print( br(), "You have been added to the " ); 32 print( span( { style => "color: blue; font-weight: bold" }, $book ) ); print( " mailing list.", br(), br() ); Fig27_13.pl Function param is part of the Perl CGI module and retrieves values from a form field’s value. The if condition uses a regular expression to validate the phone number. The expression “\(” matches the opening parenthesis of the phone number. This sequence must be followed by three digits (\d{3}), a closing parenthesis, three digits, a hyphen and finally, four more digits. The br function adds a line break (<br />) to the XHTML page
20
36 print( span( { style => "font-weight: bold" }, "The following information has been saved in our database: " ), br() ); 40 print( table( Tr( th( { style => "background-color: #ee82ee" }, "Name" ), th( { style => "background-color: #9370db" }, " " ), th( { style => "background-color: #4169e1" }, "Phone" ), th( { style => "background-color: #40e0d0" }, "OS" ) ), 50 Tr( { style => "background-color: #c0c0c0" }, td( "$firstName $lastName" ), td( $ ), td( $phone ), td( $os ) ) ) ); 56 print( br() ); 58 print( div( { style => "font-size: x-small" }, "This is only a sample form. You have not been added to a mailing list." ) ); 62 } 63 else { print( div( { style => "color: red; font-size: x-large" }, "INVALID PHONE NUMBER" ), br() ); 66 print( "A valid phone number must be in the form " ); print( span( { style => "font-weight: bold" }, "(555) " ) ); 70 Methods span and div add <span> and <div> tags to the page, respectively. Fig27_13.pl If the phone number is not valid an error message is printed to the client
21
71 print( div( { style => "color: blue" },
"Click the Back button, and enter a valid phone number and resubmit." ) ); print( br(), br() ); print( "Thank you." ); 76 } 77 78 print( end_html() ); Fig27_13.pl Program Output
22
Program Output
23
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" 3 4 <!-- Fig : fig27_14.shtml --> 5 6 <html> <head> <title>Using Server Side Includes</title> </head> 10 <body> <h3 style = "text-align: center"> Using Server Side Includes </h3> 15 <!--#EXEC CGI="/cgi-bin/fig27_15.pl" --><br /> 17 The Greenwich Mean Time is <span style = "color: blue"> <!--#ECHO VAR="DATE_GMT" -->. </span><br /> 22 The name of this document is <span style = "color: blue"> <!--#ECHO VAR="DOCUMENT_NAME" -->. </span><br /> 27 The local date is <span style = "color: blue"> <!--#ECHO VAR="DATE_LOCAL" -->. </span><br /> 32 Fig27_14.shtml The command EXEC can be used to run CGI scripts and embed their output directly into a Web page. The ECHO command displays variable information. The ECHO command is followed by the keyword VAR and the name of the variable. For example, variable DATE_GMT contains the current date and time in Greenwich Mean Time (GMT).
24
Fig27_14.shtml 33 This document was last modified on
<span style = "color: blue"> <!--#ECHO VAR="LAST_MODIFIED" -->. </span><br /> 37 Your current IP Address is <span style = "color: blue"> <!--#ECHO VAR="REMOTE_ADDR" -->. </span><br /> 42 My server name is <span style = "color: blue"> <!--#ECHO VAR="SERVER_NAME" -->. </span><br /> 47 And I am using the <span style = "color: blue"> <!--#ECHO VAR="SERVER_SOFTWARE" --> Web Server. </span><br /> 53 You are using <span style = "color: blue"> <!--#ECHO VAR="HTTP_USER_AGENT" -->. </span><br /> 58 This server is using <span style = "color: blue"> <!--#ECHO VAR="GATEWAY_INTERFACE" -->. </span><br /> 63 <br /><br /> <div style = "text-align: center; font-size: xx-small"> <hr /> Fig27_14.shtml
25
Fig27_14.shtml Program Output
This document was last modified on <!--#ECHO VAR="LAST_MODIFIED" -->. </div> </body> 72 </html> Fig27_14.shtml Program Output
26
Write the counter number back to the file counter.dat.
1 #!/usr/bin/perl 2 # Fig : fig27_15.pl 3 # Program to track the number of times 4 # a Web page has been accessed. 5 6 use CGI qw( :standard ); 7 8 open( COUNTREAD, "counter.dat" ); 9 $data = <COUNTREAD>; 10 $data++; 11 close( COUNTREAD ); 12 13 open( COUNTWRITE, ">counter.dat" ); 14 print( COUNTWRITE $data ); 15 close( COUNTWRITE ); 16 17 print( header(), "<div style = \"text-align: center; font-weight: bold\">" ); 19 print( "You are visitor number", br() ); 20 21 for ( $count = 0; $count < length( $data ); $count++ ) { $number = substr( $data, $count, 1 ); print( img( { src => "images/$number.gif" } ), "\n" ); 24 } 25 26 print( "</div>" ); Fig27_15.pl The diamond operator <> reads one line of the file referred to by filehandle COUNTREAD and assigns it to the variable $data. The file counter.dat, which contains the number of hits to date for the fig27_14.shtml Web page, is opened for input. Function open is called to create a filehandle to refer to the file during the execution of the script. Increment $data by 1. Open the counter.dat file for writing by preceding the file name with a > character (this is called write mode) Write the counter number back to the file counter.dat. The for structure iterates through each digit of the number scalar $data. Function length returns the length of a character string. For each iteration, we obtain the current digit by calling function substr. Each digit’s corresponding image is displayed using the img function.
27
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" 3 4 <!-- Fig : fig27_16.html --> 5 6 <html> <head> <title>Verifying a username and a password</title> </head> 10 <body> <p> <div style = "font-family = arial"> Type in your username and password below. </div><br /> 16 <div style = "color: #0000ff; font-family: arial; font-weight: bold; font-size: x-small"> Note that the password will be sent as plain text. </div> </p> 22 <form action = "/cgi-bin/fig27_17.pl" method = "post"> 24 <table style = "background-color: #dddddd"> <tr> <td style = "font-face: arial; font-weight: bold">Username:</td> </tr> <tr> <td> <input name = "username" /> </td> </tr> Fig27_16.html The username and password are posted to fig27_17.pl upon submission of the form.
28
Fig27_16.html 35 <tr> 36 <td style = "font-face: arial;
font-weight: bold">Password:</td> </tr> <tr> <td> <input name = "password" type = "password" /> </td> </tr> <tr> <td> <input type = "submit" value = "Enter" /> </td> </tr> </table> </form> </body> 52 </html> Fig27_16.html
29
Program Output
30
Function chomp removes the newline character at the end of the line.
1 #!/usr/bin/perl 2 # Fig : fig27_17.pl 3 # Program to search a database for usernames and passwords. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 10 11 $testUsername = param( "username" ); 12 $testPassword = param( "password" ); 13 14 open( FILE, "password.txt" ) or die( "The database could not be opened." ); 16 17 while ( $line = <FILE> ) { chomp( $line ); ( $username, $password ) = split( ",", $line ); 20 if ( $testUsername eq $username ) { $userVerified = 1; 23 if ( $testPassword eq $password ) { $passwordVerified = 1; last; } } 29 } 30 31 close( FILE ); 32 33 print( header() ); 34 print( start_html( { dtd => $dtd, title => "Password Analyzed" } ) ); Fig27_17.pl Operator or returns true if either the left condition or the right condition evaluates to true. If the condition on the left evaluates to true, then the condition on the right is not evaluated. Function die displays an error message and terminates program execution. The while structure repeatedly executes the code enclosed in curly braces until the condition in parentheses evaluates to false. When the end of the file is reached, <FILE> returns false and the loop terminates. Function chomp removes the newline character at the end of the line. Function split is called to divide the string into substrings at the specified separator or delimiter (in this case, a comma). The last statement, used to exit a repetition structure prematurely, allows us to exit the while loop immediately.
31
Tests whether the user was verified, but the password was not.
36 37 if ( $userVerified && $passwordVerified ) { accessGranted(); 39 } 40 elsif ( $userVerified && !$passwordVerified ) { wrongPassword(); 42 } 43 else { accessDenied(); 45 } 46 47 print( end_html() ); 48 49 sub accessGranted 50 { print( div( { style => "font-face: arial; color: blue; font-weight: bold" }, "Permission has been granted, $username.", br(), "Enjoy the site." ) ); 56 } 57 58 sub wrongPassword 59 { print( div( { style => "font-face: arial; color: red; font-weight: bold" }, "You entered an invalid password.", br(), "Access has been denied." ) ); 65 } 66 Checks if both the username and password were verified, by using the Perl logical AND operator (&&) Function accessGranted is called if true, which sends a Web page to the client, indicating a successful login. Fig27_17.pl The unary logical negation operator (!) is used to negate the value of $passwordVerified and test if it is false. Tests whether the user was verified, but the password was not. Function wrongPassword is called if true, which sends a Web page to the client, indicating that the password entered is invalid. If the user is not recognized, function accessDenied is called, and a message indicating that permission has been denied is sent to the client
32
Fig27_17.pl Program Output 67 sub accessDenied 68 {
68 { print( div( { style => "font-face: arial; color: red; font-size: larger; font-weight: bold" }, "You have been denied access to this site." ) ); 74 } Fig27_17.pl Program Output
33
Fig. 27.18 Database password.txt containing usernames and passwords.
1 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 Fig Database password.txt containing usernames and passwords.
34
The Perl DBI module and the MySQL driver, DBD::mysql are required.
1 #!/usr/bin/perl 2 # Fig : fig27_19.pl 3 # CGI program that generates a list of authors. 4 5 use CGI qw( :standard ); 6 use DBI; 7 use DBD::mysql; 8 9 $dtd = 10 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 12 13 print( header() ); 14 15 print( start_html( { dtd => $dtd, title => "Authors" } ) ); 17 18 # connect to "books" database, no password needed 19 $databaseHandle = DBI->connect( "DBI:mysql:books", "root", "", { RaiseError => 1 } ); 21 22 # retrieve the names and IDs of all authors 23 $query = "SELECT FirstName, LastName, AuthorID FROM Authors ORDER BY LastName"; 25 26 # prepare the query for execution, then execute it 27 # a prepared query can be executed multiple times 28 $statementHandle = $databaseHandle->prepare( $query ); 29 $statementHandle->execute(); 30 31 print( h2( "Choose an author:" ) ); 32 33 print( start_form( { action => 'fig27_20.pl' } ) ); 34 35 print( "<select name = \"author\">\n" ); Fig27_19.pl The Perl DBI module and the MySQL driver, DBD::mysql are required. Connect to the database by calling DBI method connect. Argument ({ RaiseError => 1 }) is used for error checking. If an error occurs when trying to connect to the database, function die is called and passed an error message. The database handle is used to prepare the query (using the method prepare). This method prepares the database driver for a statement, which can be executed multiple times. If the connection succeeds, function connect returns a database handle that is assigned to $databaseHandle. Method execute executes the query.
35
Each row is returned as an array and assigned to @row.
36 37 # drop-down list contains the author and ID number 38 # method fetchrow_array returns a single row from the result 39 while = $statementHandle->fetchrow_array() ) { print( "<option>" ); print( "$row[ 2 ]. $row[ 1 ], $row[ 0 ]" ); print( "</option>" ); 43 } 44 45 print( "</select>\n" ); 46 47 print( submit( { value => 'Get Info' } ) ); 48 print( end_form(), end_html() ); 49 50 # clean up -- close the statement and database handles 51 $databaseHandle->disconnect(); 52 $statementHandle->finish(); Fig27_19.pl Program Output Each row is returned as an array and assigned Each value is printed as a list option. Method fetchrow_array accesses the results of the query. Each call to this function returns the next set of data in the resulting table until there are no data sets left. Close the database connection (using method disconnect), and specify that the query is finished by calling method finish
36
Retrieve the author’s name.
1 #!/usr/bin/perl 2 # Fig : fig27_20.pl 3 # CGI program to query a MySQL database. 4 5 use CGI qw( :standard ); 6 use DBI; 7 use DBD::mysql; 8 9 $dtd = 10 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 12 13 print( header() ); 14 15 # retrieve author's ID and name from the posted form 16 $authorID = substr( param( "author" ), 0, 1 ); 17 $authorName = substr( param( "author" ), 3 ); 18 19 print( start_html( { dtd => $dtd, title => "Books by $authorName" } ) ); 21 22 $databaseHandle = DBI->connect( "DBI:mysql:books", "root", "", { RaiseError => 1 } ); 24 25 # use AuthorID to find all the ISBNs related to this author 26 $query1 = "SELECT ISBN FROM AuthorISBN WHERE AuthorID = $authorID"; 28 29 $statementHandle1 = $databaseHandle->prepare( $query1 ); 30 $statementHandle1->execute(); 31 32 print( h2( "$authorName" ) ); 33 34 print( "<table border = 1>" ); 35 print( th( "Title" ), th( "ISBN" ), th( "Publisher" ) ); Fig27_20.pl Retrieve author’s ID posted by fig27_19.pl. Method substr returns the first character in the string (an offset of zero indicates the beginning of the string), which contains the ID value. Retrieve the author’s name. Query the database to retrieve all the ISBN numbers for the specified author
37
while loop that iterates through each row matched by the query.
36 37 while = $statementHandle1->fetchrow_array() ) { print( "<tr>\n" ); 39 # use ISBN to find the corresponding title $query2 = "SELECT Title, PublisherID FROM titles WHERE ISBN = \'$isbn[ 0 ]\'"; $statementHandle2 = $databaseHandle->prepare( $query2 ); $statementHandle2->execute(); @title_publisherID = $statementHandle2->fetchrow_array(); 46 # use PublisherID to find the corresponding PublisherName $query3 = "SELECT PublisherName FROM Publishers WHERE PublisherID = \'$title_publisherID[ 1 ]\'"; 50 $statementHandle3 = $databaseHandle->prepare( $query3 ); $statementHandle3->execute(); @publisher = $statementHandle3->fetchrow_array(); 54 55 # print resulting values print( td( $title_publisherID[ 0 ] ), "\n" ); print( td( $isbn[ 0 ] ), "\n" ); print( td( $publisher[ 0 ] ), "\n" ); 60 print( "</tr>" ); 62 $statementHandle2->finish(); $statementHandle3->finish(); 65 } 66 67 print( "</table>" ); 68 69 print( end_html() ); 70 while loop that iterates through each row matched by the query. fetchrow_array returns the current data set as an array. Fig27_20.pl Query that uses the ISBN value to determine the book’s title and the publisher’s ID number. Query that uses the publisher’s ID to determine the name of the publisher. Each value is printed.
38
Fig27_20.pl Program Output 71 $databaseHandle->disconnect();
72 $statementHandle1->finish(); Fig27_20.pl Program Output
39
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" 3 4 <!-- Fig : fig27_21.html --> 5 6 <html> <head> <title>Writing a cookie to the client computer</title> </head> 10 <body style = "font-face: arial"> <div style = "font-size: large; font-weight: bold"> Click Write Cookie to save your cookie data. </div><br /> 16 <form method = "post" action = "cgi-bin/fig27_22.pl" style = "font-weight: bold"> Name:<br /> <input type = "text" name = "name" /><br /> Height:<br /> <input type = "text" name = "height" /><br /> Favorite Color:<br /> <input type = "text" name = "color" /><br /> <input type = "submit" value = "Write Cookie" /> </form> </font> </body> 29 </html> Fig27_21.html When the user clicks the Write Cookie button, the fig27_22.pl script is executed.
40
Program Output
41
Read the data sent by the client.
1 #!/usr/bin/perl 2 # Fig : fig27_22.pl 3 # Program to write a cookie to a client’s machine. 4 5 use CGI qw( :standard ); 6 7 $name = param( "name" ); 8 $height = param( "height" ); 9 $color = param( "color" ); 10 11 $expires = "Monday, 11-JUN-01 16:00:00 GMT"; 12 13 print( "Set-Cookie: Name=$name; expires=$expires; path=\n" ); 14 print( "Set-Cookie: Height=$height; expires=$expires; path=\n" ); 15 print( "Set-Cookie: Color=$color; expires=$expires; path=\n" ); 16 17 $dtd = 18 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 20 21 print( header() ); 22 print( start_html( { dtd => $dtd, title => "Cookie Saved" } ) ); 24 25 print <<End_Data; 26 <div style = "font-face: arial; font-size: larger"> The cookie has been set with the following data: 28 </div><br /><br /> 29 30 <span style = "color: blue"> 31 Name: <span style = "color: black">$name</span><br /> 32 Height: <span style = "color: black">$height</span><br /> 33 Favorite Color:</span> 34 Fig27_22.pl Read the data sent by the client. Function print outputs the cookie information. The Set-Cookie: header indicates that the browser should store the incoming data in a cookie. Instructs the Perl interpreter to print the subsequent lines verbatim (after variable interpolation) until it reaches the End_Data label.
42
The Perl interpreter stops printing subsequent lines here.
35 <span style = "color: $color"> $color</span><br /> 36 <br />Click <a href = "fig27_25.pl">here</a> 37 to read saved cookie. 38 End_Data 39 40 print( end_html() ); Fig27_22.pl Program Output The Perl interpreter stops printing subsequent lines here.
43
27.9 Cookies and Perl Fig Cookies directory before a cookie is written.
44
27.9 Cookies and Perl Fig Cookies directory after a cookie is written.
45
1 #!/usr/bin/perl 2 # Fig : fig27_25.pl 3 # program to read cookies from the client's computer. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 10 11 print( header() ); 12 print( start_html( { dtd => $dtd, title => "Read Cookies" } ) ); 14 15 print( div( { style => "font-face: arial; font-size: larger; font-weight: bold" }, "The following data is saved in a cookie on your computer." ), br() ); 20 21 print( "<table style = \"background-color: #aaaaaa\" border = 5 cellpadding = 10 cellspacing = 0>" ); 24 25 %cookies = readCookies(); 26 $color = $cookies{ Color }; 27 28 foreach $cookieName ( "Name", "Height", "Color" ) { print( Tr( td( { style => "background-color: $color" }, $cookieName ), td( $cookies{ $cookieName } ) ) ); 32 } 33 34 print( "<table>" ); 35 print( end_html() ); Fig27_25.pl Call subroutine readCookies and place the returned value into hash %cookies. The foreach loop iterates through the hash with the given key names, printing the key and value for the data from the cookie in an XHTML table.
46
36 37 sub readCookies 38 { @cookieArray = split( "; ", $ENV{ 'HTTP_COOKIE' } ); 40 foreach ) { ( $cookieName, $cookieValue ) = split( "=", $_ ); $cookieHash{ $cookieName } = $cookieValue; } 45 return %cookieHash; 47 } The user-defined subroutine readCookies splits the environment variable containing the cookie information into separate cookies (using split) and stores the cookies as distinct elements . Fig27_25.pl Program Output For each cookie we call split again to obtain the original name–value pair—which, in turn, is stored in %cookieHash. Once %cookieHash has been created, it is returned from the function using the return keyword and %cookies is assigned this value.
47
27.10 Operator Precedence Chart
48
27.10 Operator Precedence Chart
49
27.10 Operator Precedence Chart
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.