Академический Документы
Профессиональный Документы
Культура Документы
Introduction
PHP
PHP: Hypertext Preprocessor Originally called Personal Home Page Tools Popular server-side scripting technology Open-source
Anyone may view, modify and redistribute source code Supported freely by community
Platform independent
PHP
Basic application
Scripting delimiters
<? 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 -->
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>
PHP
PHP
Variables
Can have different types at different times Variable names inside strings replaced by their value Type conversions
function Type casting
settype
Concatenation operator
. (period) Combine strings
6
PHP
Data type 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.
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 -->
<!-- Demonstration of PHP data types --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>PHP data types</title> </head> <body> <?php
data.php (1 of 3)
Assign a double to variable Assign an integer to variable $testDouble
$testInteger
// 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( "$testString" );
data.php (2 of 3)
to convert $testString <br /><br function settypetype of Call />" ); the data to variable $testString to a convert the data type of $data = "98.6 degrees"; double. variable $testString to an integer. Convert variable $testString back to a string
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 );
53 </html>
data.php
10
PHP
11
PHP
Arithmetic operators
Assignment operators
Syntactical shortcuts Before being assigned values, variables have value
undef
Constants
Named values define function
12
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 -->
<!-- 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 );
operators.php (1 of 3)
Add constant VALUE to variable $a.
// add constant VALUE to variable $a $a = $a + VALUE; print( "Variable a after adding constant VALUE is $a <br />" );
13
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 after adding 40 is $a <br />" ); // test if variable $a is 50 or less if ( $a < 51 )
operators.php (2 of 3)
// 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 />" );
14
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; <br />" ); </body>
operators.php (3 of 3)
Add a string to an integer.
variable.
65 </html>
15
PHP
16
PHP
Keywords
Reserved for language features
ifelseifelse
Arrays
Group of related data
Elements
2 PHP
Arrays, cont.
Built-in iterators
Maintain pointer to element currently referenced
reset key next foreach
loops
18
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
19
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 -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Array manipulation</title> </head> <body> <?php // create array first <br />" ); $first[ 0 ] = "zero"; $first[ 1 ] = Assign "one";
arrays.php (1 of 3)
a value to the array, omitting the index. $first[ 2 ] = Appends a Use a for loop to print outthe array. "two"; new element to the end of each elements index and value. 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 />" );
20
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 $third[ "ArtTic" ] = 21; $third[ "GalAnt" ] = print( "<br /><strong>Creating the third array </strong><br />" ); // call function array to create print( "<br /><strong>Creating the second array </strong><br />" );
Call function array to create an array that contains the arguments passed to it. Store the array in variable $second array second .
$second = array( "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.
arrays.php (2 of 3)
// 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.
21
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" ); => "first", => "third", => => => "February" => "second", "April" => "fourth",
"September" =>
Operator =>=> used in function array to assign each is "sixth", "fifth", "June" element a => "eighth", "seventh", "August" string index. The value to the left of the "ninth", operator is the array index, and the value to the right is "October" => "tenth", the elements value. "eleventh","December" => "twelfth"
arrays.php (3 of 3)
foreach ( $fourth as $element => $value ) print( "$element is the $value month <br />" ); </body>
68 </html>
22
PHP
23
Relational operators
24
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 -->
compare.php (1 of 2)
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
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 print( $fruits[ $i ]." is Use relational operators equal to banana " ); // use relational operators to compare each element // to string "apple" if ( $fruits[ $i ] < "apple" ) print( "and less than apple! <br />" ); elseif ( $fruits[ $i ] > "apple" )
print( "and greater than apple! <br />" ); elseif ( $fruits[ $i ] == "apple" ) print( "and equal to apple! <br />" );
compare.php (2 of 2)
43 </html>
26
27
function function
Perl
ereg_replace
Brackets [
28
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
Function ereg searches for the literal the characters Now inside variable $search. 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 />" );
expression.php (1 of 3)
29
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 ) ) of the line.<br />" ); // search for print( "String 'Now' found at beginning
The dollar sign special character ($) search for the pattern Now (^) matches the The caret special character at the end of the string.
beginning of a string. Function ereg searches the beginning of the string for string pattern 'Now' at the end of the pattern Now .
if ( ereg( "Now$", $search ) ) print( "String 'Now' was found at the end of the line.<br />" );
if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, print( "Word found ending in 'ow': " . $match[ 1 ] . "<br />" ); // search for any words beginning with 't' print( "Words beginning
expression.php (2 of 3)
The expression inside the expressions [[:<:]] and , The special bracket parentheses, [a-zA-Z]*ow matches anypatternending beginning and end of a Placing a word in the in ow. The quantifier * [[:>:]] match parentheses stores the matched with 't' found: "); matches in the array that is specified in the third argument string therespectively. word, preceding pattern 0 or more times. to function ereg.
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any The while word is used to find each occurrence of a loop beginning with the Function eregi is used to specify case character t followed by one or insensitive word in themore characters. Character class [[:alpha:]] string beginning with t. pattern matches.
30
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 );
54 </html>
expression.php
After printing a match of a word beginning with t, function 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.
31
32
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}).
33
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.
34
35
36
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 -->
<!-- Program to display environment variables --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Environment Variables</title> </head> <body> width = "100%"> <?php
env.php (1 of 1)
// 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>" each element in the $_ENV array. values for ); PHP stores environment variables and their values in the $_ENV array.
26 </html>
37
38
39
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 -->
<!-- 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. posted to form.php. form data will be
form.html (1 of 4)
<!-- 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>
40
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"
A unique name (e.g., email) is assigned to each of the forms input fields. When Register is clicked, each fields name and value are sent to alt = "Last Name" /> the Web server.
<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"> <br /><br /> <img src = "images/downloads.gif" alt = "Publications" /><br /> <span style = "color: blue"> Which book would you like information about? </span><br />
form.html (2 of 4)
41
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"> <br /></span> Which operating system are you currently using?
<!-- create five radio buttons --> checked = "checked" /> Windows XP
form.html (3 of 4)
<input type = "radio" name = "os" value = "Windows 2000" /> Windows 2000 <input type = "radio" name = "os" value = "Windows 98" /> Windows 98<br />
42
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
form.html
43
44
Ending a script
die
function
45
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 -->
<!-- Read information sent from form.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Form Validation</title> </head>
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 expression \( matchesclosing three digits ([0-9]{3}), a the opening ); parenthesis, parentheses ofliteral hyphen and three digits, a a phone number. four additional digits.
form.php (1 of 4)
// 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.
46
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
form.php (2 of 4)
<span style = "color: blue"> <strong> <?php print( "$fname" ); ?> </strong> </span>. Thank you for completing the survey.<br />
47
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
form.php (3 of 4)
48
// print each form fields value print( "<td>$fname $lname</td> <td>$email</td> <td>$phone</td> <td>$os</td>" );
<br /><br /><br /> This is only a sample form. </div> </body>
<div style = "font-size: 10pt; text-align: center"> You have not been added to a mailing list.
form.php (4 of 4)
81 </html>
49
50
character
51
function function
52
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 -->
<!-- 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"> </style> </head>
td { background-color: #DDDDDD }
password.html (1 of 4)
<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>
53
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 />
<table border = "0" cellspacing = "0" style = "height: 90px; width: 123px; font-size: 10pt" cellpadding = "0"> <tr> <td colspan = "3"> </td> </tr> <tr> <strong>Username:</strong>
password.html (2 of 4)
<td colspan = "3"> <input size = "40" name = "USERNAME" style = "height: 22px; width: 115px" /> </td> </tr>
54
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>
password.html (3 of 4)
<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>
55
72 73 74 75
76 </html>
password.html
56
57
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 -->
<!-- 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.
// check if user has left USERNAME or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); }
password.php (1 of 7)
new user must be added.
Function fieldsBlank is called if the user has submitted an incomplete form to user has Function isset tests whether the notify the user that all the New User button, indicating pressed form fields must be completed. that a
// 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" ) ) ) {
58
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();
Print an error message and terminate script execution if the file cannot be opened.
// write username and password to file and // call function userAdded 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(); fputs( $file, "$USERNAME,$PASSWORD\n" );
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 the file. is not being added, open file
password.php (2 of 7)
59
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; // read each line in file and check usernamewhile Before entering the // and password while ( !feof(
loop, variable Function fgets reads a lineset to 0. text file. $userVerified is from the $file result !$userVerified variable $line. The ) && is assigned to ) {
The while loop executes as long as the there are more removes the newline character lines in the file to read end of the line. from the and variable $userVerified is Function split still 0 or empty. is called to separate the string at the // remove newline character from end of line specified delimiter (in this case, a comma). The $line = chop( $line ); The is stored entered by the user resulting array usernamein 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.
$line = fgets( Function chop $file, 255 );
password.php (3 of 7)
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.
60
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 } } }
If variable $userVerified has not been set to a value otherAfter 0, function loop has executed, function than the while accessDenied is file fclose is called to close has been called to notify the client that access the file. ); denied. 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.
// call function accessDenied if username has // not been verified if ( !$userVerified ) accessDenied();
// verify user password and return a boolean { return true; else return false;
password.php (4 of 7)
61
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: userAdded Function arial; font-size: 1em; <strong>You have been added to the user list, $name. <br />Enjoy the }
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 )
password.php (5 of 7)
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>" ); }
62
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>" ); }
Function wrongPassword prints a message to the client indicating that the password is invalid.
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>" ); }
password.php (6 of 7)
Function accessDenied prints a message to the client indicating that access has been denied.
63
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>
Function fieldsBlank prints a message to the client indicating that all form fields have not been completed.
155 </html>
password.php
64
65
1 2 3 4 5 6 7 8 9
10 account10,password10
password.txt
66
Connecting to a Database
Databases
Store and maintain data MySQL is a free database product PHP supports many database operations
Access databases from Web pages
67
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 -->
<!-- Querying a MySQL Database --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample Database Query</title> </head> <body style = "background-color: #F0E68C"> Querying a MySQL database. </h2>
data.html (1 of 2)
-->
<form method = "post" action = "database.php"> <p>Select a field to display: <!-- add a select box containing options --> <!-- for SELECT query
68
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; </form> color: yellow; font-weight: bold" />
36 </html>
data.html (2 of 2)
69
Connecting to a Database
70
Connecting to a Database
Interacting with databases
SQL
Structured Query Language Used to manipulate databases
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. --> -->
Build the select query and assign the string to variable $query.
database.php (1 of 3)
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" );
72
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 <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
returns an object database" ); containing the result set of the query, which we assign to variable $result.
database.php (2 of 3)
<table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6">
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).
73
// build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" );
mysql_close(
The foreach loop iterates through the array containing the elements of each row and prints out each element in an $databaseThe total number of results are printed to the ); individual table cell. client.
database.php (3 of 3)
<?php print( "$counter" ) ?> results.<br /><br /></strong> <h5>Please email comments to <a href = "mailto:deitel@deitel.com"> Deitel and Associates, Inc. </a>
74
Connecting to a Database
75
Cookies
Cookies
Store information on client computer Track preferences and other information Stored as text files on hard drive Never store sensitive information, such as credit card numbers, in a cookie
Security risk
function
76
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 -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Writing a cookie to the client computer</title> </head>
cookies.html (1 of 2)
77
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" font-weight: bold" /></p> </form> </body>
cookies.html (2 of 2)
33 </html>
78
Cookies
79
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 );
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" the value to be stored in the followed by "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>
cookies.php (1 of 2)
80
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 /> <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>
form fields value is printed to confirm the data that has been set as a cookie with the user.
38 </html>
cookies.php (2 of 2)
Hyperlink to readCookies.php.
81
Cookies
82
Cookies
Reading cookies
$_COOKIE environment
variable
Array
foreach loop
83
Cookies
Cookie storage
Internet Explorer
Stores cookies in Cookies directory Text file
84
Cookies
85
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 -->
<!-- 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> computer. </strong> </p>
readCookies.php (1 of 2)
86
19 20 21 22 23 24 25 26 27 28 29 30 31 32
The foreach loop iterates through the $_COOKIE PHP creates array $_COOKIE which contains array and prints the name and value of each cookie all cookie values indexed by their names. through array $_COOKIE and print in an XHTML table.
// 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>
33 </html>
readCookies.php (2 of 2)
87
Cookies
88
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 -->
<!-- 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>
dynamicForm.php (1 of 9)
Build array of options for the form.
// 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" );
90
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" =>
If the page is being loaded as a result of a form submission,errors or omissionsandform field Check for do error checking in then retrieve "Phone" ); information from the database. input.
dynamicForm.php (2 of 9)
91
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 ) {
"( 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" );
dynamicForm.php (3 of 9)
92
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> print( "<p>Hi <span style = 'color: blue'> <strong>$fname</strong></span>. Thank you for completing the survey.<br /> You have been added to the } // execute query in MailingList database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() );
<strong>$book</strong></span>
dynamicForm.php (4 of 9)
93
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>
<div style = 'font-size: 10pt; text-align: center'> <div style = 'font-size : 18pt'> <a href = 'formDatabase.php'> This is only a sample form. </div></body></html>" ); die();
dynamicForm.php (5 of 9)
Halt the script so the form-generation code does not execute.
Click here to view entire database.</a></div> You have not been added to a mailing list.
print( "<h1>This is a sample registration form.</h1> Please fill in all fields and click Register." );
94
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' 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'> </span> Please fill out the fields below.<br /> } if ( $iserror ) { print( "<br /><span style = 'color : red'> Fields with * need to be filled in properly.</span>" );
<!-- create four text boxes for user input -->" ); foreach ( $inputlist as $inputname => $inputalt ) { $inputtext = $inputvalues[ $inputname ];
dynamicForm.php (6 of 9)
If the form input contained errors, place a red asterisk (*) next to the text field.
95
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 ) { <img src = 'images/downloads.gif' alt = 'Publications' /><br /> <span style = 'color: blue'> </span><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" );
dynamicForm.php (7 of 9)
Make sure the correct book is selected in the dropdown box.
96
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>" );
print( "</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 -->" ); $counter = 0;
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++;
97
print( "<!-- create a submit button --> <br /> <input type = 'submit' name = 'submit' value = 'Register' /> </form></body></html>" );
dynamicForm.php
98
99
100
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. --> -->
formDatabase.php (1 of 3)
101
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> ?> } // 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" );
formDatabase.php (2 of 3)
<table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6">
102
<td>Operating System</td> </tr> <?php // fetch each record in for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ // build table to print( "<tr>" );
Retrieve each mailing list member record from the resultdatabase. set
foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database );
formDatabase.php (3 of 3)
Dynamically create a table display results containing each mailing list member.
</table>
103
104
Operator Precedence
Operator new [] ~ ! ++ -@ * / % + . << >> < > <= >= == != === !== Type
constructor subscript bitwise not not increment decrement unary negative error control multiplication division modulus addition subtraction concatenation bitwise shift left bitwise shift right less than greater than less than or equal greater than or equal equal not equal identical not identical
Associativity
none right to left right to left
left to right
left to right
none
105
Operator Precedence
Type
bitwise AND bitwise XOR bitwise OR logical AND logical OR assignment addition assignment subtraction assignment multiplication assignment division assignment bitwise AND assignment bitwise OR assignment bitwise exclusive OR assignment concatenation assignment bitwise shift left assignment bitwise shift right assignment logical AND exclusive OR logical OR list left to right left to right left to right left to right left to right left to right
Associativity
106