Documente Academic
Documente Profesional
Documente Cultură
Chapter 26 - PHP
Outline
26.1 26.2 26.3 26.4 26.5 26.6 26.7 26.8 26.9 26.10 26.11 Introduction PHP String Processing and Regular Expressions Viewing Client/Server Environment Variables Form Processing and Business Logic Verifying a Username and Password Connecting to a Database Cookies Dynamic Content in PHP Operator Precedence Web Resources
Platform independent
1 2 3 4 5 6 7 8 9 10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 26.1: first.php --> <!-- Our first PHP script -->
Outline
first.php (1 of 1)
Scripting delimiters
<?php $name = "LunaTic"; ?> // declaration
11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 14 15 16 17 18 19 20 21 22 23 24 </p> </body> <!-- print variable names value --> Welcome to PHP, <?php print( "$name" ); ?>! </strong> <body style = "font-size: 2em"> <p> <strong> <head> <title>A simple PHP document</title>Single-line </head>
comment
25 </html>
26.2 PHP
Fig. 26.1 Simple PHP program.
26.2 PHP
Description int, integer Whole numbers (i.e., numbers without a decimal point). float, double Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single ('') or double ("") quotes. bool, Boolean True or false. array Group of elements of the same type. object Group of associated data and methods. Resource An external data source. NULL No value. Fig. 26.2 PHP data types. Data type
10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.3: data.php -->
11
Outline
data.php (1 of 3)
<!-- Demonstration of PHP data types --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>PHP data types</title> </head> <body> <?php // declare a string, double and integer $testString = "3.5 seconds"; $testDouble = 79.2; $testInteger = 12; ?>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<!-- print each variables value --> <?php print( $testString ); ?> is a string.<br /> <?php print( $testDouble ); ?> is a double.<br /> <?php print( $testInteger ); ?> is an integer.<br /> <br /> Now, converting to other types:<br /> <?php // call function settype to convert variable // testString to different data types print( "$testString" ); settype( $testString, "double" ); print( " as a double is $testString <br />" ); print( "$testString" ); settype( $testString, "integer" ); print( " as an integer is $testString <br />" ); settype( $testString, "string" ); print( "Converting back to a string results in $testString <br /><br />" ); $data = "98.6 degrees";
12
Outline
data.php Print each variables(2 value of 3)
44 45 46 47 48 49 50 51 52 ?> </body> // use type casting to cast variables to a // different type print( "Now using type casting instead: <br /> As a string - " . (string) $data . "<br />As a double - " . (double) $data . "<br />As an integer - " . (integer) $data );
13
Outline
data.php (3 of 3) Use type casting to cast variable $data to different types
53 </html>
14
26.2 PHP
Fig. 26.3 Type conversion.
15
Arithmetic operators
Operator Name Description Example Result
x+y
x-y x*y x/y
Addition
Subtraction Multiplication Division
Sum of x and y
Difference of x and y Product of x and y Quotient of x and y
2+2
5-2 5*2 15 / 5
4
3 10 3
x%y
Modulus
-x a.b
Negation Concatenation
1 2 0
HiHa
16
Assignment operators
Assignment
x=y x += y x -= y x *= y x /= y x %= y a .= b
Same as...
x=y x=x+y x=x-y x=x*y x=x/y x=x%y a=a.b
Description
The left operand gets set to the value of the expression on the right Addition Subtraction Multiplication Division Modulus Concatenate two strings
17
18
Comparison Operators
Operator x == y x === y x != y x <> y x !== y x>y x<y x >= y x <= y Name Equal Identical Not equal Not equal Not identical Greater than Less than Description True if x is equal to y True if x is equal to y, and they are of same type True if x is not equal to y True if x is not equal to y True if x is not equal to y, or they are not of same type True if x is greater than y True if x is less than y Example 5==8 returns false 5==="5" returns false 5!=8 returns true 5<>8 returns true 5!=="5" returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true
Greater than or equal True if x is greater than or equal to y to Less than or equal to True if x is less than or equal to y
19
26.2 PHP Constants - A way of associating a scalar value with a string taken - Defined by the define construct define(myconstant, 12); - Same rules apply for naming variable names - No $ before the constant name - Once defined their values cannot be changed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.4: operators.php -->
20
Outline
operators.php (1 of 3)
<!-- Demonstration of operators --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using arithmetic operators</title> </head> <body> <?php $a = 5;
print( "The value of variable a is $a <br />" ); // define constant VALUE define( "VALUE", 5 );
// add constant VALUE to variable $a $a = $a + VALUE; print( "Variable a after adding constant VALUE is $a <br />" );
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// multiply variable $a by 2 $a *= 2; print( "Multiplying variable a by 2 yields $a <br />" ); // test if variable $a is less than 50 if ( $a < 50 ) print( "Variable a is less than 50 <br />" ); // add 40 to variable $a $a += 40; print( "Variable a after adding 40 is $a <br />" ); // test if variable $a is 50 or less if ( $a < 51 ) print( "Variable a is still 50 or less<br />" ); // test if variable $a is between 50 and 100, inclusive elseif ( $a < 101 ) print( "Variable a is now between 50 and 100, inclusive<br />" ); else print( "Variable a is now greater than 100 <br />" );
21
Outline
operators.php (2 of 3)
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ?>
// print an uninitialized variable print( "Using a variable before initializing: $nothing <br />" ); // add constant VALUE to an uninitialized variable $test = $num + VALUE; print( "An uninitialized variable plus constant VALUE yields $test <br />" ); // add a string to an integer $str = "3 dollars"; $a += $str; print( "Adding a string to variable a yields $a <br />" ); </body>
22
Outline
operators.php (3 of 3)
65 </html>
23
26.2 PHP
Fig. 26.4 Using PHPs arithmetic operators.
24
IF statement
Syntax
25
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } else { echo "Have a nice day!"; } ?> </body> </html>
26
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } elseif ($d=="Sun") { echo "Have a nice Sunday!"; } else { echo "Have a nice day!"; } ?> /body> </html>
2004 Prentice Hall, Inc. All rights reserved.
27
28
29
Syntax
while (condition) { code to be executed; }
Example: $i=0; while ($i<10){ echo $i; $i++; }
2004 Prentice Hall, Inc. All rights reserved.
30
Example <html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>
31
Syntax
for (init; condition; increment) { code to be executed; } Example <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html>
32
Arrays Not like the arrays of any other programming language A PHP array is a generalization of the arrays of other languages A PHP array is really a mapping of keys to values, where the keys can be numbers (to get a traditional array) or strings.
33
Array Creation
Use the array() construct, which takes one or more key => value pairs as parameters and returns an array of them The keys are non-negative integer literals or string literals The values can be anything
$list1 = array(); $list2 = array (17, 24, 45, 90); $list3 = array(0 => "apples",1 => "oranges", 2 => "grapes")
$list4 = array(Joe => 42, Mary => 41, Jan => 17);
$list5 = $list2;
34
Numeric Arrays
A numeric array stores each array element with a numeric index. There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota"); 2. In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota";
35
Numeric Arrays
Example In the following example you access the variable values by referring to the array name and index: <?php $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?> The code above will output: Saab and Volvo are Swedish cars.
36
Associative Arrays
An associative array, each ID key is associated with a value. Example 1 In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, John"=>30, "Joe"=>34); Example 2 This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; The ID keys can be used in a script: <?php $ages['Peter'] = "32"; $ages[John'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>
2004 Prentice Hall, Inc. All rights reserved.
37
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on
Example In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array ( "Griffin"=>array( "Peter", "Lois", "Megan"), "Quagmire"=>array ( "Glenn"), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
2004 Prentice Hall, Inc. All rights reserved.
38
39
Sequential Acces to Array elements foreach statement to build loops that process all of the elements in an array foreach (array as key=>value) loop body E.g. foreach ($highs as $day=>$temp) print(The low temperature on $day was $temp <br />);
40
foreach loops
41
26.2 PHP
PHP keywords
and break case class continue default do else elseif extends false for foreach function global if include list new not or require return static switch this true var virtual xor while
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.6: arrays.php --> <!-- Array manipulation -->
42
Outline
arrays.php (1 of 3)
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Array manipulation</title> </head> <body> <?php // create array first print( "<strong>Creating the first array</strong> <br />" ); $first[ 0 ] = "zero"; $first[ 1 ] = "one"; $first[ 2 ] = "two"; $first[] = "three";
Use a for loop to print out each elements index and value. Function count returns the total number of elements in the array.
// print each elements index and value for ( $i = 0; $i < count( $first ); $i++ ) print( "Element $i is $first[$i] <br />" );
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // assign values to non-numerical indices $third[ "ArtTic" ] = 21; $third[ "LunaTic" ] = 18; $third[ "GalAnt" ] = 23; print( "<br /><strong>Creating the third array </strong><br />" ); // call function $second = array( print( "<br /><strong>Creating the second array </strong><br />" );
43
Call function array to create an array that contains the arguments passed to it. Store the array in variable arrays.php array to create array $second second . (2 of 3) "zero", "one", "two", "three" );
Outline
for ( $i = 0; $i < count( $second ); $i++ ) print( "Element $i is $second[$i] <br />" );
Function reset sets the internal pointer to the first element of the array.
// iterate through the array elements and print each // elements name and value for ( reset( $third ); $element = key( $third ); next( $third ) ) print( "$element is $third[$element] <br />" );
Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element.
2004 Prentice Hall, Inc.
All rights reserved.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 ?>
print( "<br /><strong>Creating the fourth array </strong><br />" ); // call function array to create array fourth using // string indices $fourth = array( "January" "March" "May" "July" "November" ); // print each elements name and value foreach ( $fourth as $element => $value ) print( "$element is the $value month <br />" ); </body> => "first", => "third", => => => "February" => "second", "April" => "fourth",
44
Outline
arrays.php (3 of 3)
"September" =>
is "sixth", used in function array to assign each "fifth", Operator "June" =>=> a string index. The value to the left of the "seventh",element "August" => "eighth", is the index, and the value to the right is "ninth", operator "October" => array "tenth", the elements value. "eleventh","December" => "twelfth"
68 </html>
45
26.2 PHP
Fig. 26.6 Array manipulation.
46
Relational operators
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.7: compare.php --> <!-- String Comparison -->
47
Outline
compare.php (1 of 2)
// create array fruits $fruits = array( "apple", "orange", "banana" ); // iterate through each array element for ( $i = 0; $i < count( $fruits ); $i++ ) { // call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " );
Function strcmp compares two strings. If the first string alphabetically precedes the second, then 1 is returned. If the strings are equal, 0 is returned. If the first string 2004 Prentice Hall, Inc. All rights reserved. alphabetically follows the second, then 1 is returned.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 ?> </body> }
elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) print( $fruits[ $i ]. " is greater than banana " ); else
48
Outline
to compare each array compare.php element to string apple. (2 of 2)
43 </html>
49
50
Brackets [ ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.8: expression.php --> <!-- Using regular expressions --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Regular expressions</title> </head> <body> <?php
51
Outline
expression.php (1 of 3)
Function ereg searches for the literal characters Now inside variable $search.
$search = "Now is the time"; print( "Test string is: '$search'<br /><br />" ); // call function ereg to search for pattern 'Now' // in variable search if ( ereg( "Now", $search ) ) print( "String 'Now' was found.<br />" );
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// search for pattern 'Now' in the beginning of // the string if ( ereg( "^Now", $search ) ) print( "String 'Now' found at beginning of the line.<br />" ); // search for pattern 'Now' at the end of the string if ( ereg( "Now$", $search ) ) (now ile balayan varm diye bakyor ^) print( "String 'Now' was found at the end of the line.<br />" ); // search for any word ending in 'ow' if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) ) print( "Word found ending in 'ow': " . $match[ 1 ] . "<br />" ); // search for any words beginning with 't' print( "Words beginning with 't' found: "); // eregi( "[[:<:]](t[[a-zA-Z]]+)[[:>:]]", yerine alpha yazabiliriz. while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", $search, $match ) ) { print( $match[ 1 ] . " " );
52
Outline
expression.php (2 of 3)
46 47 48 49 50 51 52 53 ?> </body> }
// remove the first occurrence of a word beginning // with 't' to find other instances in the string $search = ereg_replace( $match[ 1 ], "", $search );
53
Outline
54 </html>
expression.php After printing a match of a word beginning with t, function (3 of 3) ereg_replace is called to remove the word from the string. This is necessary be because to find multiple instances of a given pattern, the first matched instance must first be removed. Function ereg_replace takes three arguments: the pattern to match, a string to replace the matched string and the string to search.
54
55
Quantifier
{n} {m,n} {n,} + * ?
Matches
Exactly n times. Between m and n times inclusive. n or more times. One or more times (same as {1,}). Zero or more times (same as {0,}). Zero or one time (same as {0,1}).
Fig. 26.9
56
Character class
alnum alpha digit space lower upper
Description
Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]). Word characters (i.e., letters [a-zA-Z]). Digits. Whitespace. Lowercase letters. Uppercase letters.
Fig. 26.10
57
58
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.11: env.php -->
59
Outline
env.php (1 of 1)
<!-- Program to display environment variables --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Environment Variables</title> </head> <body> <table border = "0" cellpadding = "2" cellspacing = "0" width = "100%"> <?php // print the key and value for each element // in the $_ENV array foreach ( $_ENV as $key => $value ) print( "<tr><td bgcolor = \"#11bbff\"> <strong>$key</strong></td> <td>$value</td></tr>" ); ?> </table> </body>
26 </html>
60
61
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.13: form.html -->
62
Outline
form.html (1 of 4)
<!-- Form for use with the form.php program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample form to take user input in XHTML</title> </head> <body> <h1>This is a sample registration form.</h1> Please fill in all fields and click Register. <!-- post form data to form.php --> <form method = "post" action = "form.php"> <img src = "images/user.gif" alt = "User" /><br /> <span style = "color: blue"> Please fill out the fields below.<br /> </span>
The action attribute of the form element indicates that when the user clicks Register, the form data will be posted to form.php.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<!-- create four text boxes for user input --> <img src = "images/fname.gif" alt = "First Name" /> <input type = "text" name = "fname" /><br /> <img src = "images/lname.gif" alt = "Last Name" /> <input type = "text" name = "lname" /><br /> <img src = "images/email.gif" alt = "Email" /> <input type = "text" name = "email" /><br /> <img src = "images/phone.gif" alt = "Phone" /> <input type = "text" name = "phone" /><br /> <span style = "font-size: 10pt"> Must be in the form (555)555-5555</span> <br /><br /> <img src = "images/downloads.gif" alt = "Publications" /><br /> <span style = "color: blue"> Which book would you like information about? </span><br />
63
Outline
form.html (2 of 4)
A unique name (e.g., email) is assigned to eac of the forms input fields. When Register is clicked, each fields name and value are sent the Web server.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
<!-- create drop-down list containing book names --> <select name = "book"> <option>Internet and WWW How to Program 3e</option> <option>C++ How to Program 4e</option> <option>Java How to Program 5e</option> <option>XML How to Program 1e</option> </select> <br /><br /> <img src = "images/os.gif" alt = "Operating System" /> <br /><span style = "color: blue"> Which operating system are you currently using? <br /></span> <!-- create five radio buttons --> <input type = "radio" name = "os" value = "Windows XP" checked = "checked" /> Windows XP <input type = "radio" name = "os" value = "Windows 2000" /> Windows 2000 <input type = "radio" name = "os" value = "Windows 98" /> Windows 98<br />
64
Outline
form.html (3 of 4)
74 75 76 77 78 79 80 81 82 83 84 85 </body> 86 </html> <!-- create a submit button --> <input type = "submit" value = "Register" /> </form> <input type = "radio" name = "os" value = "Other" /> Other<br /> <input type = "radio" name = "os" value = "Linux" /> Linux
65
Outline
form.html (4 of 4)
66
67
Ending a script
die function Remember to close all HTML tags
2004 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.14: form.php -->
68
Outline
form.php (1 of 4)
<!-- Read information sent from form.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Form Validation</title> </head> <body style = "font-family: arial,sans-serif"> <?php extract( $_POST ); // determine whether phone number is valid and print // an error message if not if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ){
We access the phone fields value from form.html by using variable $phone.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <p>Hi ?> }
print( "<p><span style = \"color: red; font-size: 2em\"> INVALID PHONE NUMBER</span><br /> A valid phone number must be in the form <strong>(555)555-5555</strong><br /> <span style = \"color: blue\"> Click the Back button, enter a valid phone number and resubmit.<br /><br /> Thank You.</span></p></body></html>" ); die(); // terminate script execution
69
Outline
form.php (2 of 4)
<span style = "color: blue"> <strong> <?php print( "$fname" ); ?> </strong> </span>. Thank you for completing the survey.<br />
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
You have been added to the <span style = "color: blue"> <strong> <?php print( "$book " ); ?> </strong> </span> mailing list. </p> <strong>The following information has been saved in our database:</strong><br /> <table border = "0" cellpadding = "0" cellspacing = "10"> <tr> <td bgcolor = "#ffffaa">Name </td> <td bgcolor = "#ffffbb">Email</td> <td bgcolor = "#ffffcc">Phone</td> <td bgcolor = "#ffffdd">OS</td> </tr> <tr> <?php
70
Outline
form.php (3 of 4)
// print each form fields value print( "<td>$fname $lname</td> <td>$email</td> <td>$phone</td> <td>$os</td>" );
71
Outline
form.php (4 of 4)
<br /><br /><br /> <div style = "font-size: 10pt; text-align: center"> This is only a sample form. You have not been added to a mailing list. </div> </body>
81 </html>
72
73
74
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.15: password.html -->
75
Outline
password.html (1 of 4)
<!-- XHTML form sent to password.php for verification --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Verifying a username and a password.</title> <style type = "text/css"> td { background-color: #DDDDDD } </style> </head> <body style = "font-family: arial"> <p style = "font-size: 13pt"> Type in your username and password below. <br /> <span style = "color: #0000FF; font-size: 10pt; font-weight: bold"> Note that password will be sent as plain text </span> </p>
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<!-- post form data to password.php --> <form action = "password.php" method = "post"> <br />
76
Outline
password.html (2 of 4)
<table border = "0" cellspacing = "0" style = "height: 90px; width: 123px; font-size: 10pt" cellpadding = "0"> <tr> <td colspan = "3"> <strong>Username:</strong> </td> </tr> <tr> <td colspan = "3"> <input size = "40" name = "USERNAME" style = "height: 22px; width: 115px" /> </td> </tr>
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
<tr> <td colspan = "3"> <strong>Password:</strong> </td> </tr> <tr> <td colspan = "3"> <input size = "40" name = "PASSWORD" style = "height: 22px; width: 115px" type = "password" /> <br/></td> </tr> <tr> <td colspan = "1"> <input type = "submit" name = "Enter" value = "Enter" style = "height: 23px; width: 47px" /> </td> <td colspan = "2"> <input type = "submit" name = "NewUser" value = "New User" style = "height: 23px" /> </td>
77
Outline
password.html (3 of 4)
72 73 74 75
78
Outline
password.html (4 of 4)
76 </html>
79
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.16: password.php -->
80
Outline
password.php (1 of 7)
<!-- Searching a database for usernames and passwords. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <?php extract( $_POST ); // check if user has left USERNAME or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); } // check if the New User button was clicked if ( isset( $NewUser ) ) { // open password.txt for writing using append mode if ( !( $file = fopen( "password.txt", "a" ) ) ) {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 } } }
// print error message and terminate script // execution if file cannot be opened print( "<title>Error</title></head><body> Could not open password file </body></html>" ); die();
81
Outline
password.php (2 of 7)
// write username and password to file and // call function userAdded fputs( $file, "$USERNAME,$PASSWORD\n" ); userAdded( $USERNAME ); else { // if a new user is not being added, open file // for reading if ( !( $file = fopen( "password.txt", "r" ) ) ) { print( "<title>Error</title></head> <body>Could not open password file </body></html>" ); die();
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
$userVerified = 0;
82
Outline
// read each line in file and check username // and password while ( !feof( $file ) && !$userVerified ) { // read line from file $line = fgets( $file, 255 ); // remove newline character from end of line $line = chop( $line ); // split username and password $field = split( ",", $line, 2 ); // verify username if ( $USERNAME == $field[ 0 ] ) { $userVerified = 1; // call function checkPassword to verify // users password if ( checkPassword( $PASSWORD, $field ) == true ) accessGranted( $USERNAME ); else wrongPassword();
password.php (3 of 7)
Function checkPassword is called to verify the users password. Variable $PASSWORD and array $field are passed to the function. 2004 Prentice Hall, Inc.
All rights reserved.
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 } } }
83
Outline
password.php (4 of 7)
// close text file fclose( $file ); // call function accessDenied if username has // not been verified if ( !$userVerified ) accessDenied();
// verify user password and return a boolean function checkPassword( $userpassword, $filedata ) { if ( $userpassword == $filedata[ 1 ] ) return true; else return false;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
// print a message indicating the user has been added function userAdded( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>You have been added to the user list, $name. <br />Enjoy the site.</strong>" ); } // print a message indicating permission // has been granted function accessGranted( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>Permission has been granted, $name. <br /> Enjoy the site.</strong>" ); }
84
Outline
password.php (5 of 7)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
// print a message indicating password is invalid function wrongPassword() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong>You entered an invalid password.<br />Access has been denied.</strong>" ); } // print a message indicating access has been denied function accessDenied() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> You were denied access to this server. <br /></strong>" ); }
85
Outline
password.php (6 of 7)
142 143 144 145 146 147 148 149 150 151 152 153 154 ?>
// print a message indicating that fields // have been left blank function fieldsBlank() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> Please fill in all form fields. <br /></strong>" ); } </body>
86
Outline
password.php (7 of 7)
155 </html>
87
1 2 3 4 5 6 7 8 9
88
Outline
password.txt (1 of 1)
10 account10,password10
89
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.18: data.html -->
90
Outline
data.html (1 of 2)
<!-- Querying a MySQL Database --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample Database Query</title> </head> <body style = "background-color: #F0E68C"> <h2 style = "font-family: arial color: blue"> Querying a MySQL database. </h2> <form method = "post" action = "database.php"> <p>Select a field to display: <!-- add a select box containing options --> <!-- for SELECT query -->
22 23 24 25 26 27 28 29 30 31 32 33 34 35 </body>
<select name = "select"> <option selected = "selected">*</option> <option>ID</option> <option>Title</option> <option>Category</option> <option>ISBN</option> </select> </p> <input type = "submit" value = "Send Query" style = "background-color: blue; color: yellow; font-weight: bold" /> </form>
91
Outline
data.html (2 of 2)
36 </html>
92
93
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.19: database.php <!-- send results to the client. --> -->
94
Outline
database.php (1 of 3)
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Search Results</title> </head> <body style = "font-family: arial, sans-serif" style = "background-color: #F0E68C"> <?php extract( $_POST ); // build SELECT query $query = "SELECT " . $select . " // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" );
Function mysql_connect returns a database handle which represents PHPs connection to a database. If this connection is not made, function FROM Books"; die is called to terminate script execution.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // fetch each record in result set for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ <?php <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Search Results</h3> ?> } // query Products database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() ); // open Products database if ( !mysql_select_db( "Products", $database ) ) die( "Could not open Products database" );
95
Outline
database.php (2 of 3)
Function mysql_fetch_row returns an array containing the elements of each row in the result set of our query ($result).
2004 Prentice Hall, Inc.
All rights reserved.
// build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" );
96
Outline
database.php (3 of 3)
mysql_close( $database );
<br />Your search yielded <strong> <?php print( "$counter" ) ?> results.<br /><br /></strong> <h5>Please email comments to <a href = "mailto:deitel@deitel.com"> Deitel and Associates, Inc. </a>
97
98
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.20: cookies.html --> <!-- Writing a Cookie -->
99
Outline
cookies.html (1 of 2)
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Writing a cookie to the client computer</title> </head> <body style = "font-family: arial, sans-serif; background-color: #99CCFF"> <h2>Click Write Cookie to save your cookie data.</h2>
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<form method = "post" action = "cookies.php" style = "font-size: 10pt"> <strong>Name:</strong><br /> <input type = "text" name = "NAME" /><br /> <strong>Height:</strong><br /> <input type = "text" name = "HEIGHT" /><br /> <strong>Favorite Color:</strong><br /> <input type = "text" name = "COLOR" /><br /> <input type = "submit" value = "Write Cookie" style = "background-color: #F0E86C; color: navy; font-weight: bold" /></p> </form> </body>
100
Outline
Form data is posted to cookies.php. cookies.html (2 of 2)
33 </html>
101
26.8 Cookies
Fig. 26.20 Gathering data to be written as a cookie.
1 2 3 4 5 6 7 8 9 10
<?php // Fig. 26.21: cookies.php // Program to write a cookie to a client's machine extract( $_POST ); // write each form fields value to a cookie and set the // cookies expiration date setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
102
Outline
cookies.php (1 of 2)
11 ?> 12 13 14 15
Function setcookie takes the name of the cookie to be set as the first argument, <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" followed by the value to be stored in the "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> cookie. The optional third argument specifies the expiration date of the cookie.
<head> <title>Cookie Saved</title> </head> <body style = "font-family: arial, sans-serif"> <p>The cookie has been set with the following data:</p>
24 25 26 27 28 29 30 31 32 33 34 35 36 37
<!-- print each form fields value --> <br /><span style = "color: blue">Name:</span> <?php print( $NAME ) ?><br /> <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br /> <span style = "color: blue">Favorite Color:</span> <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?> </span><br /> <p>Click <a href = "readCookies.php">here</a> to read the saved cookie.</p> </body>
103
Outline
cookies.php (2 of 2)
38 </html>
Hyperlink to readCookies.php.
104
26.8 Cookies
Fig. 26.21 Writing a cookie to the client.
105
106
107
26.8 Cookies
Fig. 26.22 Cookies directory before a cookie is written.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.24: readCookies.php -->
108
Outline
readCookies.php (1 of 2)
<!-- Program to read cookies from the client's computer --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>Read Cookies</title></head> <body style = "font-family: arial, sans-serif"> <p> <strong> The following data is saved in a cookie on your computer. </strong> </p>
19 20 21 22 23 24 25 26 27 28 29 30 31 32
<table border = "5" cellspacing = "0" cellpadding = "10"> <?php // iterate through array $_COOKIE and print // name and value of each cookie foreach ( $_COOKIE as $key => $value ) print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" ); ?> </table> </body>
109
Outline
readCookies.php (2 of 2)
33 </html>
110
26.8 Cookies
Fig. 26.24 Displaying the cookies content.
111
1 2 3 4 5 6 7 8 9
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.25: dynamicForm.php -->
112
Outline
dynamicForm.php (1 of 9)
<!-- Form for use with the form.php program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample form to take user input in XHTML</title>
10 </head> 11 12 <body> 13 14 15 16 17 18 19 20 21 22 // array of book titles $booklist = array( "Internet and WWW How to Program 3e", "C++ How to Program 4e", "Java How to Program 5e", "XML How to Program 1e" ); <?php extract ( $_POST ); $iserror = false;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// array of possible operating systems $systemlist = array( "Windows XP", "Windows 2000", "Windows 98", "Linux", "Other"); // array of name and alt values for the text input fields $inputlist = array( "fname" => "First Name", "lname" => "Last Name", "email" => "Email", "phone" => "Phone" ); if ( isset ( $submit ) ) { if ( $fname == "" ) { $formerrors[ "fnameerror" ] = true; $iserror = true; } if ( $lname == "" ) { $formerrors[ "lnameerror" ] = true; $iserror = true; }
113
Outline
dynamicForm.php (2 of 9)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
if ( $email == "" ) { $formerrors[ "emailerror" ] = true; $iserror = true; } if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) { $formerrors[ "phoneerror" ] = true; $iserror = true; } if ( !$iserror ) {
114
Outline
dynamicForm.php (3 of 9)
// build INSERT query $query = "INSERT INTO contacts " . "( LastName, FirstName, Email, Phone, Book, OS ) " . "VALUES ( '$lname', '$fname', '$email', " . "'" . quotemeta( $phone ) . "', '$book', '$os' )"; // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" ); // open MailingList database if ( !mysql_select_db( "MailingList", $database ) ) die( "Could not open MailingList database" );
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 <table border = '0' cellpadding = '0' cellspacing = '10'> <tr> <td bgcolor = '#ffffaa'>Name</td> <td bgcolor = '#ffffbb'>Email</td> <td bgcolor = '#ffffcc'>Phone</td> You have been added to the <span style = 'color: blue'> <strong>$book</strong></span> mailing list. </p> <strong>The following information has been saved in our database:</strong><br /> print( "<p>Hi <span style = 'color: blue'> <strong>$fname</strong></span>. Thank you for completing the survey.<br /> } // execute query in MailingList database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() );
115
Outline
dynamicForm.php (4 of 9)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 } }
<td bgcolor = '#ffffdd'>OS</td> </tr> <tr> <!-- print each form fields value --> <td>$fname $lname</td> <td>$email</td> <td>$phone</td> <td>$os</td> </tr></table> <br /><br /><br /> <div style = 'font-size: 10pt; text-align: center'> <div style = 'font-size : 18pt'> <a href = 'formDatabase.php'> Click here to view entire database.</a></div> This is only a sample form. You have not been added to a mailing list. </div></body></html>" ); die();
116
Outline
dynamicForm.php (5 of 9)
print( "<h1>This is a sample registration form.</h1> Please fill in all fields and click Register." );
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 } print( "<br />" ); if ( $formerrors[ ( $inputname )."error" ] == true ) print( "<span style = 'color : red'>*</span>" ); print( "<img src = 'images/$inputname.gif' alt = '$inputalt' /><input type = 'text' name = '$inputname' value = '" . $$inputname . "' />" ); <!-- create four text boxes for user input -->" ); foreach ( $inputlist as $inputname => $inputalt ) { $inputtext = $inputvalues[ $inputname ]; print( "<!-- post form data to form.php --> <form method = 'post' action = 'dynamicform.php'> <img src = 'images/user.gif' alt = 'User' /><br /> <span style = 'color: blue'> Please fill out the fields below.<br /> </span> } if ( $iserror ) { print( "<br /><span style = 'color : red'> Fields with * need to be filled in properly.</span>" );
117
Outline
dynamicForm.php (6 of 9)
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 if ( ( $currbook == $book ) ) print( " selected = 'true'" ); foreach ( $booklist as $currbook ) { print( "<option" ); <!-- create drop-down list containing book names --> <select name = 'book'>" ); <span style = 'color: blue'> Which book would you like information about? </span><br /> <img src = 'images/downloads.gif' alt = 'Publications' /><br /> print( "'>Must be in the form (555)555-5555 </span><br /><br /> if ( $formerrors[ "phoneerror" ] ) print( "; color : red" ); print( "<span style = 'font-size : 10pt" );
118
Outline
dynamicForm.php (7 of 9)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 } }
print( ">$currbook</option>" );
119
Outline
<img src = 'images/os.gif' alt = 'Operating System' /> <br /><span style = 'color: blue'> Which operating system are you currently using? <br /></span> <!-- create five radio buttons -->" );
dynamicForm.php (8 of 9)
$counter = 0; foreach ( $systemlist as $currsystem ) { print( "<input type = 'radio' name = 'os' value = '$currsystem'" ); if ( $currsystem == $os ) print( "checked = 'checked'" ); if ( $iserror && $counter == 0 ) print( "checked = 'checked'" ); print( " />$currsystem" ); if ( $counter == 2 ) print( "<br />" ); $counter++;
print( "<!-- create a submit button --> <br /> <input type = 'submit' name = 'submit' value = 'Register' /> </form></body></html>" );
120
Outline
dynamicForm.php (9 of 9)
121
122
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.26: formDatabase.php <!-- Program to query a database and --> <!-- send results to the client. --> -->
123
Outline
formDatabase.php (1 of 3)
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Search Results</title> </head> <body style = "font-family: arial, sans-serif" style = "background-color: #F0E68C"> <?php
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <tr> <td>ID</td> <td>Last Name</td> <td>First Name</td> <td>E-mail Address</td> <td>Phone Number</td> <td>Book</td> <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Mailing List Contacts</h3> ?> } // query MailingList database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() ); // open MailingList database if ( !mysql_select_db( "MailingList", $database ) ) die( "Could not open MailingList database" );
124
Outline
formDatabase.php (2 of 3)
<td>Operating System</td> </tr> <?php // fetch each record in result set for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ // build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database );
125
Outline
formDatabase.php (3 of 3)
</table>
126
127
Associativity
none right to left right to left
left to right
left to right
none
128
Associativity
left to right left to right left to right left to right left to right left to right