Beruflich Dokumente
Kultur Dokumente
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
Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MSSQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
PHP
Software Platform
Development Tools
26.2 PHP
How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag
HTML
PHP CODE
HTML
Starting tag
<?php <? <script language="php">
<%
%>
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>
10
26.2 PHP
Fig. 26.1 Simple PHP program.
11
Type casting
12
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
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 -->
13
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" );
14
Outline
data.php of 3) Print each variables (2 value
to convert the data type $testString <br /><br />" ); settype Call function to of variable $testString to a convert the data type of double. $data = "98.6 degrees"; variable $testString to an integer. Convert variable $testString back to a string
2003 Prentice Hall, Inc.
All rights reserved.
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 );
15
Outline
data.php (3 of 3) Use type casting to cast variable $data to different types
53 </html>
16
26.2 PHP
Fig. 26.3 Type conversion.
17
Constants
Named values define function
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 -->
18
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 )
19
Outline
operators.php Test variable $a is less than 50 Print if variable $a is lesswhether than 50. (2 of 3)
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 />" );
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>
20
Outline
operators.php (3 of 3)
65 </html>
21
26.2 PHP
Fig. 26.4 Using PHPs arithmetic operators.
22
Arrays
Group of related data
Elements
array function
23
foreach loops
24
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
Array
Untuk menambahkan menggunakan kurung kotak tanpa isi index ( [] ) Tipe element tidak perlu di sebutkan, bisa berisi tipe macammacam
Fungsi-fungsi Array
Contoh Array
Statement if / else
Elseif adalah keyword yang sering dipakai, walaupun else if juga support
Loop while
Keyword break dan continue bisa digunakan dan mirip seperti di Java dan C
Loop foreach
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 -->
32
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 ] = Assign "one";
a value to the array, omitting the index. for loop print each elements index and value. $first[ 2 ] = Appends "two"; a Use newaelement to to the end out of the array. Function count returns the total number of elements in the $first[] = "three"; 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[ "GalAnt" ] = $third[ "LunaTic" ] = 18; print( "<br /><strong>Creating the third array </strong><br />" ); // call function $second = array( print( "<br /><strong>Creating the second array </strong><br />" );
33
Outline Call function array to create an array that contains the arguments passed to it. Store the array in variable $second arrays.php array to create array second . (2 of 3) "zero", "one", "two", "three" );
for ( $i = 0; $i < count( $second ); $i++ ) print( "Element $i is $second[$i] <br />" );
Assign values to non-numerical indices in array $third. 23; 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.
2003 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",
34
Outline
arrays.php (3 of 3)
"September" =>
Operator =>=> is used in function array to assign each "fifth", "June" "sixth", element a string index. The value to the left of the "seventh", "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>
35
26.2 PHP
Fig. 26.6 Array manipulation.
36
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 -->
37
Outline
compare.php (1 of 2)
// create array fruits $fruits = array( "apple", "orange", "banana" ); // iterate through for ( $i = 0; $i <
Function strcmp compares two strings. If the first string alphabetically precedes the second, then 1 is returned. If each array element the strings are equal, 0 is returned. If the first string count( $fruits ); $i++ ) { alphabetically follows the second, then 1 is returned.
// call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " );
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
38
Outline
to compare each array compare.php element to string apple. (2 of 2)
43 </html>
39
40
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 $search = "Now is
41
Outline
expression.php (1 of 3)
Function ereg searches for the literal Now inside variable $search. the characters 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
42
Outline
//
The dollar sign special character ($) search for the pattern Now at the end of the the string. The caret special character ( ^) matches expression.php of the line.<br />" ); beginning of a string. Function ereg searches the (2 of 3) beginning of the string for pattern Now . search for pattern 'Now' at the end of the string
if ( ereg( "Now$", $search ) ) 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
The expression inside the expressions parentheses,[[:<:]] [a-zA-Z]*ow The special bracket and , matches any word ending in ow. The quantifier * Placing a pattern in the parentheses stores the of matched [[:>:]] match beginning and end a with 't' found: "); matches the preceding pattern 0 or more times. string in the array that is specified in the third argument word, respectively. to function ereg.
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any The while word loop is used to find each occurrence of a beginning with the character t followed by one or Function eregi is used to specify case insensitive word in themore string beginningCharacter with t. class [[:alpha:]] characters. pattern matches.
All rights reserved.
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 );
43
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.
44
45
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
46
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
47
48
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 -->
49
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> The foreach loop ?> </table> </body>
is used to print out the keys and <td>$value</td></tr>" ); element in the $_ENV array. values for each PHP stores environment variables and their values in the $_ENV array.
26 </html>
50
51
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 -->
52
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 Please fill
The action attribute of the form element indicates that when the user clicks Register, the a sample registration form.</h1> in all fields and click Register. form data will be posted to form.php.
<!-- 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>
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
53
A unique name (e.g., email) is assigned to each Outline of the forms input fields. When Register is clicked, each fields name and value are sent to form.html <img src = "images/lname.gif" alt = "Last Name" /> the Web server. (2 of 4) <input type = "text" name = "lname" /><br />
<input type = "text" name = "fname" /><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 />
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 />
54
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
55
Outline
form.html (4 of 4)
56
57
Ending a script
die function Remember to close all HTML tags
2003 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 -->
58
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
Function ereg is called to determine whether the The parentheses in the expression must be phone number entered by the user is valid. followed by The three digits ([0-9]{3} ), a closing expression \( matches the opening ); parenthesis, parentheses three digits, of a literal hyphen and a phone number. four additional digits.
// 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
59
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
60
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>" );
61
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>
62
63
64
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 -->
65
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 />
66
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>
67
Outline
password.html (3 of 4)
72 73 74 75
68
Outline
password.html (4 of 4)
76 </html>
69
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 -->
70
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 );
Variable names, when preceded by the logical negation operator (!), return true if they are empty or set to 0. This checks if a user has submitted a form without specifying a username or password. Function fieldsBlank is called if the user has submitted an incomplete formthe to notify the user Function isset tests whether user has that all form fields must be completed. pressed the New User button, indicating that a new user must be added.
// check if user has left USERNAME or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); }
// check if the New User button was clicked To add a if ( isset( $NewUser ) ) {
new user, we open the file password.txt in append mode and assign the file handle that is returned to variable $file.
// 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();
71
Outline
password.php Print an error message and terminate script (2 ofexecution 7) if the file cannot be opened.
// write username and password to file and // call function userAdded fputs( $file, "$USERNAME,$PASSWORD\n" ); userAdded( $USERNAME ); else { // if a new user // for reading if ( !( $file = fopen( "password.txt", "r" ) ) ) { print( "<title>Error</title></head> <body>Could not open password file </body></html>" ); die();
Function userAdded is called to print a message to the Function fputs writes the name and password to the user to indicate that the username and password were text file.. added to theadded, file. open file is not being
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;
72
Outline
// read each line in file and check username Before entering the while // and password while ( !feof(
loop, variable Function fgets reads a line from the $userVerified is set to 0 . text file. $file ) && !$userVerified ) { The result is assigned to variable $line.
password.php (3 of 7)
The while loop executes as long as the there are more removes the newline character lines in the file to read and of variable $userVerified is from the end the line. Function split is called to separate the string at the still 0 or empty. // remove newline character from end of line specified delimiter (in this case, a comma). The $line = chop( $line ); The username entered by the user resulting array is stored in array $field . is tested against the one returned in the text file (stored // split username and password in the first element of the array). If they match, $field = split( ",", $line, 2 ); variable $userVerified is set to 1.
chop $line = fgets( Function $file, 255 );
// verify username if ( $USERNAME == $field[ 0 ] ) { $userVerified = 1;
checkPassword returns true, function accessGranted is called to notify the client that
Function checkPassword is called to verify the users password. Variable $PASSWORD and array $field are passed to the function. 2003 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 } } }
73
If variable $userVerified has not been set to a the while loop has executed, value otherAfter than 0 , function accessDenied is function file fclose is called to close the called to notify the client that access has file. been password.php ); denied. (4 of 7) Function checkPassword compares the users password to the password in the file. If they match, true is returned, whereas false is returned if they do not.
Outline
// 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; Function userAdded font-size: 1em; <strong>You have been added to the user list, $name. <br />Enjoy the }
74
Outline
password.php (5 of 7)
prints a message to the color: blue\"> client indicating that the user has been added.
Function accessGranted prints a site.</strong>"message ); to the client indicating that permission has been granted.
// 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>" ); }
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>
75
Outline
Function wrongPassword prints a message to the client indicating that the password is invalid. password.php <body style = \"font-family: arial; (6 of 7) 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>" ); }
Function accessDenied prints a message to the client indicating that access has been denied.
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() {
76
Function fieldsBlank prints a message to Outline the client indicating that all form fields have not been completed. print( "<title>Access Denied</title></head> password.php <body style = \"font-family: arial; (7 of 7)
font-size: 1em; color: red\"> <strong> Please fill in all form fields. <br /></strong>" );
} </body>
155 </html>
77
1 2 3 4 5 6 7 8 9
78
Outline
password.txt (1 of 1)
10 account10,password10
79
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 -->
80
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>
81
Outline
36 </html>
82
83
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. --> -->
84
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
Build the select query and assign the string to variable $query. 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.
extract( $_POST ); // build SELECT query $query = "SELECT " . $select . " // Connect to MySQL
if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" );
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 <?php <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Search Results</h3> ?> } // if // open Products database
85
returns an object die( "Could not open Products database" ); containing the result set of the query, which we assign to variable $result. database.php query Products database (2 of 3) ( !( $result = mysql_query( $query, $database ) ) ) { Function mysql_select_db is called to specify the print( "Could not execute query! <br />" ); database to be queried.
die( mysql_error() );
Outline
The for loop iterates through each record in the result set while // fetch each record in result set constructing an XHTML table from for ( $counter = 0; the results. Variable $counter is $row = mysql_fetch_row( $result incremented ); by one for each row $counter++ ){ Function mysql_fetch_row returns an retrieved. array containing the elements of each row in the result set of our query ($result).
2003 Prentice Hall, Inc.
All rights reserved.
// build table to display results print( "<tr>" ); foreach ( $row as $key => $value )
86
Outline
database.php (3 of 3) print( "</tr>" ); The foreach loop iterates through the } array containing the elements of each row and prints out each element in an mysql_close( $databaseThe ); total number of results are printed to the individual table cell. client.
print( "<td>$value</td>" );
<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>
87
88
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 -->
89
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>
90
Outline
Form data is posted to cookies.php. cookies.html (2 of 2)
33 </html>
91
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 );
92
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> Each <?php print( $NAME ) ?><br /> <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br />
form fields value is printed to Outline confirm the data that has been set as a cookie with the user. cookies.php (2 of 2)
93
<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>
38 </html>
Hyperlink to readCookies.php.
94
26.8 Cookies
Fig. 26.21 Writing a cookie to the client.
95
96
97
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 -->
98
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
99
The foreach loop iterates through the $_COOKIE Outline PHP creates array $_COOKIE which contains array and prints the name and value of each cookie all cookie values indexed by their names. // iterate through array $_COOKIE and print in an XHTML table. readCookies.php // name and value of each cookie (2 of 2) foreach ( $_COOKIE as $key => $value )
print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" );
33 </html>
100
26.8 Cookies
Fig. 26.24 Displaying the cookies content.
101
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 -->
102
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" =>
103
Outline
dynamicForm.php (2 of 9)
If the page is being loaded as a result of a form submission, do error checking and then field retrieve Check for errors or omissions in form "Phone" ); information from the database. input.
if ( isset ( $submit ) ) { if ( $fname == "" ) { $formerrors[ "fnameerror" ] = true; $iserror = true; } if ( $lname == "" ) { $formerrors[ "lnameerror" ] = true; $iserror = true; }
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 ) {
104
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() );
105
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. </div></body></html>" ); die(); You have not been added to a mailing list.
106
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' <!-- 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>" );
107
Outline
dynamicForm.php (6 of 9)
If the form input contained errors, place a red asterisk (*) next to the text field.
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'" ); print( "<option" ); <!-- create drop-down list containing book names --> <select name = 'book'>" ); foreach ( $booklist as $currbook ) { <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" );
108
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>" );
109
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)
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>" );
110
Outline
dynamicForm.php (9 of 9)
111
112
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. --> -->
113
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" );
114
Outline
formDatabase.php (2 of 3)
<td>Operating System</td> </tr> <?php // fetch each record in for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ // build table to print( "<tr>" );
115
Outline
Retrieve each mailing list member record from the resultdatabase. set formDatabase.php (3 of 3)
Dynamically create a table display results containing each mailing list member.
foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database );
</table>
116
117
Associativity
none right to left right to left
left to right
left to right
none
118
Associativity
left to right left to right left to right left to right left to right left to right