Damascus road

Download Report

Transcript Damascus road

1
23
PHP
 2008 Pearson Education, Inc. All rights reserved.
2
Conversion for me was not a Damascus Road
experience. I slowly moved into a intellectual
acceptance of what my intuition had always known.
— Madeleine L’Engle
Be careful when reading health books;
you may die of a misprint.
— Mark Twain
 2008 Pearson Education, Inc. All rights reserved.
3
Reckoners without their host must reckon twice.
— John Heywood
There was a door to which I found no key;
There was the veil through which I might not see.
— Omar Khayyam
 2008 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn:
 To manipulate data of various types.
 To use operators, arrays and control statements.
 To use regular expressions to search for patterns.
 To construct programs that process form data.
 To store data on the client using cookies.
 To create programs that interact with MySQL
databases.
 2008 Pearson Education, Inc. All rights reserved.
5
23.1 Introduction
23.2 PHP Basics
23.3 String Processing and Regular Expressions
23.3.1 Comparing Strings
23.3.2 Regular Expressions
23.4 Form Processing and Business Logic
23.5 Connecting to a Database
23.6 Using Cookies
23.7 Dynamic Content
23.8 Operator Precedence Chart
23.9 Wrap-Up
23.10 Web Resources
 2008 Pearson Education, Inc. All rights reserved.
6
23.1 Introduction
• PHP, or PHP: Hypertext Preprocessor, has
become one of the most popular server-side
scripting languages for creating dynamic web
pages.
• PHP is open source and platform independent—
implementations exist for all major UNIX, Linux,
Mac and Windows operating systems. PHP also
supports a large number of databases.
 2008 Pearson Education, Inc. All rights reserved.
7
23.2 PHP Basics
• The power of the web resides not only in serving content to users, but
also in responding to requests from users and generating web pages
with dynamic content.
• PHP code is embedded directly into XHTML documents, though these
script segments are interpreted by a server before being delivered to
the client.
• PHP script file names end with .php.
• Although PHP can be used from the command line, a web server is
necessary to take full advantage of the scripting language.
• In PHP, code is inserted between the scripting delimiters <?php
and ?>. PHP code can be placed anywhere in XHTML markup, as
long as the code is enclosed in these delimiters.
 2008 Pearson Education, Inc. All rights reserved.
8
23.2 PHP Basics (Cont.)
• Variables are preceded by a $ and are created the first time they are
encountered.
• PHP statements terminate with a semicolon (;).
• Single-line comments which begin with two forward slashes (//) or a
pound sign (#). Text to the right of the delimiter is ignored by the
interpreter. Multiline comments begin with delimiter /* and end with
delimiter */.
• When a variable is encountered inside a double-quoted ("") string,
PHP interpolates the variable. In other words, PHP inserts the
variable’s value where the variable name appears in the string.
• All operations requiring PHP interpolation execute on the server
before the XHTML document is sent to the client.
• PHP variables are loosely typed—they can contain different types of
data at different times.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
9
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.1: first.php -->
6
<!-- Simple PHP program. -->
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<?php
9
Delimiters
enclosing PHP
script
first.php
$name = "Harvey"; // declaration and initialization
10 ?><!-- end PHP script -->
11
12
<head>
<title>Using PHP document</title>
13
</head>
14
<body style = "font-size: 2em">
15
Declares and
initializes a PHP
variable
<p>
<strong>
16
17
<!-- print variable name’s value -->
18
Welcome to PHP, <?php print( "$name" ); ?>!
</strong>
19
20
</p>
21
</body>
Interpolates the variable
so that its value will be
output to the XHTML
document
22 </html>
 2008 Pearson Education,
Inc. All rights reserved.
10
Common Programming Error 23.1
Failing to precede a variable name
with a $ is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
11
Common Programming Error 23.2
Variable names in PHP are case sensitive.
Failure to use the proper mixture of cases to
refer to a variable will result in a logic error,
since the script will create a new variable for
any name it doesn’t recognize as a previously
used variable.
 2008 Pearson Education, Inc. All rights reserved.
12
Common Programming Error 23.3
Forgetting to terminate a statement
with a semicolon (;) is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
13
Type
Description
int, integer
Whole numbers (i.e., numbers without a decimal point).
float, double, real
string
Real numbers (i.e., numbers containing a decimal point).
bool, boolean
array
True or false.
object
Group of associated data and methods.
resource
An external source—usually information from a database.
NULL
No value.
Text enclosed in either single ('') or double ("") quotes.
[Note: Using double quotes allows PHP to recognize
more escape sequences.]
Group of elements.
Fig. 23.2 | PHP types.
 2008 Pearson Education, Inc. All rights reserved.
14
23.2 PHP Basics (Cont.)
• Type conversions can be performed using function settype. This function
takes two arguments—a variable whose type is to be changed and the
variable’s new type.
• Variables are automatically converted to the type of the value they are
assigned.
• Function gettype returns the current type of its argument.
• Calling function settype can result in loss of data. For example, doubles are
truncated when they are converted to integers.
• When converting from a string to a number, PHP uses the value of the
number that appears at the beginning of the string. If no number appears at
the beginning, the string evaluates to 0.
• Another option for conversion between types is casting (or type casting).
Casting does not change a variable’s content—it creates a temporary copy of
a variable’s value in memory.
• The concatenation operator (.) combines multiple strings.
• A print statement split over multiple lines prints all the data that is enclosed
in its parentheses.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
15
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.3: data.php -->
6
<!-- Data type conversion. -->
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
9
(1 of 3)
<head>
<title>Data type conversion</title>
10
</head>
11
<body>
12
data.php
<?php
13
// declare a string, double and integer
14
$testString = "3.5 seconds";
15
$testDouble = 79.2;
16
$testInteger = 12;
17
?><!-- end PHP script -->
Automatically declares a string
Automatically declares a double
Automatically declares an integer
18
19
<!-- print each variable’s value and type -->
20
<?php
21
22
Outputs the type of
$testString
print( "$testString is a(n) " . gettype( $testString )
. "<br />" );
 2008 Pearson Education,
Inc. All rights reserved.
23
print( "$testDouble is a(n) " . gettype( $testDouble )
. "<br />" );
24
25
print( "$testInteger is a(n) " . gettype( $testInteger)
26
. "<br />" );
27
?><!-- end PHP script -->
28
<br />
29
converting to other data types:<br />
30
<?php
Outline
data.php
(2 of 3)
31
// call function settype to convert variable
32
// testString to different data types
33
print( "$testString" );
34
settype( $testString, "double" );
35
print( " as a double is $testString <br />" );
36
print( "$testString" );
37
settype( $testString, "integer" );
38
print( " as an integer is $testString <br />" );
39
settype( $testString, "string" );
40
print( "converting back to a string results in
41
16
Modifies $testString
to be a double
Modifies $testString
to be an integer
Modifies $testString
to be a string
$testString <br /><br />" );
42
 2008 Pearson Education,
Inc. All rights reserved.
43
// use type casting to cast variables to a different type
44
$data = "98.6 degrees";
45
print( "before casting, $data is a " .
46
gettype( $data ) . "<br /><br />" );
47
print( "using type casting instead: <br />
48
as a double: " . (double) $data .
49
"<br />as an integer: " . (integer) $data );
Outline
data.php
(3 of 3)
gettype( $data ) );
51
53
Temporarily casts
$data as a double
and an integer
print( "<br /><br />after casting, $data is a " .
50
52
17
?><!-- end PHP script -->
</body>
Concatenation
54 </html>
 2008 Pearson Education,
Inc. All rights reserved.
18
Error-Prevention Tip 23.1
Function print can be used to display
the value of a variable at a particular
point during a program’s execution.
This is often helpful in debugging a script.
 2008 Pearson Education, Inc. All rights reserved.
19
23.2 PHP Basics (Cont.)
• Function define creates a named constant. It takes two
arguments—the name and value of the constant. An
optional third argument accepts a boolean value that
specifies whether the constant is case insensitive—
constants are case sensitive by default.
• Uninitialized variables have the value undef, which has
different values, depending on its context. In a numeric
context, it evaluates to 0. In a string context, it evaluates
to an empty string ("").
• Keywords may not be used as identifiers.
 2008 Pearson Education, Inc. All rights reserved.
20
Common Programming Error 23.4
Assigning a value to a constant after
it is declared is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- Using arithmetic operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using arithmetic operators</title>
Outline
<!-- Fig. 23.4: operators.php -->
10
</head>
11
12
<body>
<?php
operators.php
(1 of 3)
13
14
$a = 5;
print( "The value of variable a is $a <br />" );
15
16
// define constant VALUE
Creates the named
constant VALUE with a
value of 5
17
18
define( "VALUE", 5 );
19
20
21
// add constant VALUE to variable $a
$a = $a + VALUE;
print( "Variable a after adding constant VALUE
22
23
21
is $a <br />" );
Equivalent to $a = $a * 2
24
25
// multiply variable $a by 2
$a *= 2;
26
27
print( "Multiplying variable a by 2 yields $a <br />" );
 2008 Pearson Education,
Inc. All rights reserved.
28
29
30
// test if variable $a is less than 50
if ( $a < 50 )
22
print( "Variable a is less than 50 <br />" );
Outline
31
32
// add 40 to variable $a
33
34
35
$a += 40;
print( "Variable a after adding 40 is $a <br />" );
36
// test if variable $a is 50 or less
37
38
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
Uses a comparison operator
with a variable and an integer
operators.php
(2 of 3)
39
40
// test if variable $a is between 50 and 100, inclusive
41
elseif ( $a < 101 )
42
43
44
45
46
47
48
49
print( "Variable a is now between 50 and 100,
inclusive<br />" );
else
print( "Variable a is now greater than 100 <br />" );
// print an uninitialized variable
print( "Using a variable before initializing:
$nothing <br />" ); // nothing evaluates to ""
50
51
// add constant VALUE to an uninitialized variable
52
$test = $num + VALUE; // num evaluates to 0
Uninitialized variable
$num evaluates to 0
 2008 Pearson Education,
Inc. All rights reserved.
print( "An uninitialized variable plus constant
53
Outline
VALUE yields $test <br />" );
54
23
55
$str is converted to an
integer for this operation
56
// add a string to an integer
57
$str = "3 dollars";
58
$a += $str;
59
print( "Adding a string to variable a yields $a <br />" );
60
61
?><!-- end PHP script -->
operators.php
(3 of 3)
</body>
62 </html>
 2008 Pearson Education,
Inc. All rights reserved.
24
Error-Prevention Tip 23.2
Initialize variables before they are used
to avoid subtle errors. For example,
multiplying a number by an uninitialized
variable results in 0.
 2008 Pearson Education, Inc. All rights reserved.
25
PHP keywords
abstract
and
array
as
break
case
catch
__CLASS__
die
do
echo
else
elseif
empty
enddeclare
endfor
exit
extends
__FILE__
file
final
for
foreach
__FUNCTION__
interface
isset
__LINE__
line
list
__METHOD__
method
new
require
require_once
return
static
switch
throw
try
unset
class
clone
endforeach
endif
function
global
or
php_user_filter
use
var
const
continue
declare
default
endswitch
endwhile
eval
exception
if
implements
include
include_once
print
private
protected
public
while
xor
Fig. 23.5 | PHP keywords.
 2008 Pearson Education, Inc. All rights reserved.
26
23.2 PHP Basics (Cont.)
• PHP provides the capability to store data in arrays. Arrays are
divided into elements that behave as individual variables. Array
names, like other variables, begin with the $ symbol.
• Individual array elements are accessed by following the array’s
variable name with an index enclosed in square brackets ([]).
• If a value is assigned to an array that does not exist, then the array is
created. Likewise, assigning a value to an element where the index is
omitted appends a new element to the end of the array.
• Function count returns the total number of elements in the array.
• Function array creates an array that contains the arguments passed
to it. The first item in the argument list is stored as the first array
element (index 0), the second item is stored as the second array
element and so on.
 2008 Pearson Education, Inc. All rights reserved.
27
23.2 PHP Basics (Cont.)
• Arrays with nonnumeric indices are called associative arrays. You can
create an associative array using the operator =>, where the value to
the left of the operator is the array index and the value to the right is
the element’s value.
• PHP provides functions for iterating through the elements of an array.
Each array has a built-in internal pointer, which points to the array
element currently being referenced. Function reset sets the internal
pointer to the first array element. Function key returns the index of
the element currently referenced by the internal pointer, and function
next moves the internal pointer to the next element.
• The foreach statement, designed for iterating through arrays, starts
with the array to iterate through, followed by the keyword as,
followed by two variables—the first is assigned the index of the
element and the second is assigned the value of that index’s element.
(If only one variable is listed after as, it is assigned the value of the
array element.)
 2008 Pearson Education, 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
22
23
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
28
Outline
<!-- Fig. 23.6: arrays.php -->
<!-- Array manipulation. -->
arrays.php
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
(1 of 4)
<title>Array manipulation</title>
Automatically creates
</head>
array $first
<body>
<?php
Sets the first element of array
// create array first
print( "<strong>Creating the first array</strong><br />" );$first to the string “zero”
$first[ 0 ] = "zero";
“three” is appended to
$first[ 1 ] = "one";
$first[ 2 ] = "two";
the end of array $first
$first[] = "three";
// print each element’s index and value
for ( $i = 0; $i < count( $first ); $i++ )
print( "Element $i is $first[$i] <br />" );
Returns the number of
elements in the array
 2008 Pearson Education,
Inc. All rights reserved.
24
25
print( "<br /><strong>Creating the second array
29
Outline
</strong><br />" );
26
27
// call function array to create array second
28
$second = array( "zero", "one", "two", "three" );
arrays.php
29
30
31
for ( $i = 0; $i < count( $second ); $i++ )
(2 of 4)
print( "Element $i is $second[$i] <br />" );
32
33
34
Function array creates
array $second with its
arguments as elements
print( "<br /><strong>Creating the third array
</strong><br />" );
35
36
// assign values to entries using nonnumeric indices
37
$third[ "Amy" ] = 21;
38
$third[ "Bob" ] = 18;
39
$third[ "Carol" ] = 23;
Creates associative
array $third
40
41
// iterate through the array elements and print each
42
// element’s name and value
43
for ( reset( $third ); $element = key( $third ); next( $third ) )
44
print( "$element is $third[$element] <br />" );
45
Sets the internal
pointer to the first
array element in
$third
Returns the index
of the element
being pointed to
Moves the internal
pointer to the next
element and returns
it
 2008 Pearson Education,
Inc. All rights reserved.
print( "<br /><strong>Creating the fourth array
46
30
Outline
</strong><br />" );
47
48
49
// call function array to create array fourth using
50
// string indices
51
$fourth = array(
arrays.php
52
"January"
=> "first",
"February" => "second",
53
"March"
=> "third",
"April"
=> "fourth",
54
"May"
=> "fifth",
"June"
=> "sixth",
55
"July"
=> "seventh", "August"
56
"September" => "ninth",
57
"November"
58
);
"October"
=> "eighth",
=> "tenth",
=> "eleventh","December" => "twelfth"
59
60
// print each element’s name and value
61
foreach ( $fourth as $element => $value )
64
Uses operator => to
initialize the element
with index
“January” to have
value “first”
print( "$element is the $value month <br />" );
62
63
(3 of 4)
?><!-- end PHP script -->
</body>
65 </html>
Iterates through
each element in
array $fourth
Stores
the index
of the
element
Stores the value
of the element
 2008 Pearson Education,
Inc. All rights reserved.
31
Outline
arrays.php
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
32
23.3 String Processing and Regular
Expressions
• A regular expression is a series of characters used for
pattern-matching templates in strings, text files and
databases.
• Many string-processing tasks can be accomplished using
the equality and relational operators (==, !=, <, <=, >
and >=).
• Function strcmp compares two strings. The function
returns -1 if the first string alphabetically precedes the
second string, 0 if the strings are equal, and 1 if the first
string alphabetically follows the second.
 2008 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 23.7: compare.php -->
<!-- Using the string-comparison operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>String Comparison</title>
</head>
<body>
<?php
// create array fruits
$fruits = array( "apple", "orange", "banana" );
// iterate through each array element
for ( $i = 0; $i < count( $fruits ); $i++ )
{
19
20
21
22
23
24
// call function strcmp to compare the array element
// to string "banana"
if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
print( $fruits[ $i ] . " is less than banana " );
elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
print( $fruits[ $i ] . " is greater than banana " );
25
26
27
28
29
else
print( $fruits[ $i ] . " is equal to banana " );
33
Outline
compare.php
(1 of 2)
Checks whether the ith
element of the fruits
array preceeds the string
banana
// use relational operators to compare each element
// to string "apple"
 2008 Pearson Education,
Inc. All rights reserved.
if ( $fruits[ $i ] < "apple" )
30
print( "and less than apple! <br />" );
31
elseif ( $fruits[ $i ] > "apple" )
32
elseif ( $fruits[ $i ] == "apple" )
34
print( "and equal to apple! <br />" );
35
compare.php
} // end for
36
38
Outline
print( "and greater than apple! <br />" );
33
37
34
?><!-- end PHP script -->
(2 of 2)
</body>
39 </html>
Uses relational operators
to compare the element
of the fruits array
with the string apple
 2008 Pearson Education,
Inc. All rights reserved.
35
23.3 String Processing and Regular
Expressions (Cont.)
• Functions ereg and preg_match use regular expressions to search a string
for a specified pattern.
• If a pattern is found using ereg, it returns the length of the matched string—
which evaluates to true in a boolean context.
• Anything enclosed in single quotes in a print statement is not interpolated
(unless the single quotes are nested in a double-quoted string literal).
• Function ereg receives a regular expression pattern to search for and the
string to search.
• Function eregi performs case-insensitive pattern matches.
• Regular expressions can include metacharacters that specify patterns. For
example, the caret (^) metacharacter matches the beginning of a string, while
the dollar sign ($) matches the end of a string. The period (.) metacharacter
matches any single character.
• Bracket expressions are lists of characters enclosed in square brackets ([])
that match any single character from the list. Ranges can be specified by
supplying the beginning and the end of the range separated by a dash (-).
 2008 Pearson Education, Inc. All rights reserved.
36
23.3 String Processing and Regular
Expressions (Cont.)
• The special bracket expressions [[:<:]] and [[:>:]] match the beginning and end
of a word, respectively.
• Quantifiers are used in regular expressions to denote how often a particular character
or set of characters can appear in a match.
• The optional third argument to function ereg is an array that stores matches to each
parenthetical statement of the regular expression. The first element stores the string
matched for the entire pattern, and the remaining elements are indexed from left to
right.
• To find multiple instances of a given pattern, we must make multiple calls to ereg, and
remove matched instances before calling the function again by using a function such as
ereg_replace.
• Character classes, or sets of specific characters, are enclosed by the delimiters [:
and :]. When this expression is placed in another set of brackets, it is a regular
expression matching all of the characters in the class.
• A bracketed expression containing two or more adjacent character classes in the class
delimiters represents those character sets combined.
• Function ereg_replace takes three arguments—the pattern to match, a string to
replace the matched string and the string to search. The modified string is returned.
 2008 Pearson Education, 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
22
23
24
25
26
27
28
29
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 23.8: expression.php -->
<!-- Regular expressions. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Regular expressions</title>
</head>
<body>
<?php
$search = "Now is the time";
print( "Test string is: '$search'<br /><br />" );
// call ereg to search for pattern 'Now' in variable search
if ( ereg( "Now", $search ) )
print( "String 'Now' was found.<br />" );
// 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 ) )
print( "String 'Now' was found at the end
of the line.<br />" );
37
Outline
expression.php
(1 of 2)
String to search
Searches for the string
“Now” in $search
Checks if string “Now”
appears at the beginning
of $search
Checks if string “Now”
appears at the end of
$search
 2008 Pearson Education,
Inc. All rights reserved.
30
// search for any word ending in 'ow'
31
if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) )
print( "Word found ending in 'ow': " .
32
$match[ 1 ] . "<br />" );
33
34
35
// search for any words beginning with 't'
36
print( "Words beginning with 't' found: ");
38
Outline
Searches for a word
ending in “ow” and
stores matches in
$match array
expression.php
(2 of 2)
37
while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
38
$search, $match ) )
39
{
40
print( $match[ 1 ] . " " );
41
Prints first encountered
instance of word ending
in “ow”
42
43
// remove the first occurrence of a word beginning
44
// with 't' to find other instances in the string
45
$search = ereg_replace( $match[ 1 ], "", $search );
} // end while
46
47
48
Performs a caseinsensitive search for
words beginning with the
letter “t”
?><!-- end PHP script -->
</body>
49 </html>
Replaces the found
instance from the
previous call to eregi
with an empty string so
that the next instance of
the pattern can be found
and stored in $match
 2008 Pearson Education,
Inc. All rights reserved.
39
Quantifier
Matches
{n}
Exactly n times.
{m,n}
Between m and n times, inclusive.
{n,}
+
n or more times.
*
Zero or more times (same as {0,}).
?
Zero or one time (same as {0,1}).
One or more times (same as {1,}).
Fig. 23.9 | Some PHP quantifiers.
 2008 Pearson Education, Inc. All rights reserved.
40
Character class Description
alnum
Alphanumeric characters (i.e., letters [a-zA-Z] or
digits [0-9]).
alpha
Word characters (i.e., letters [a-zA-Z]).
digit
Digits.
space
White space.
lower
Lowercase letters.
upper
Uppercase letters.
Fig. 23.10 | Some PHP character classes.
 2008 Pearson Education, Inc. All rights reserved.
41
PHP 5.3
function getAdder($x) {
return function ($y) use ($x) {
return $x + $y;
};
}
$adder = getAdder(8);
echo $adder(2); // prints "10"
 2008 Pearson Education, Inc. All rights reserved.
42
PHP 5.3
function lock() {
$file = fopen('file.txt', 'r+');
retry:
if (!flock($file, LOCK_EX)) {
goto retry;
}
fwrite($file, 'Success!');
fclose($file);
return 0; }
 2008 Pearson Education, Inc. All rights reserved.
43
PHP 5.3.3
<?php
namespace Foo;
class Bar {
public function Bar() {
// treated as constructor in PHP 5.3.05.3.2
// treated as regular method in PHP
5.3.3
}
}
?>
 2008 Pearson Education, Inc. All rights reserved.
44
PHP Objects
class Person {
public $first;
public $last;
public function __construct($f, $l) {
$this->first = $f;
$this->last = $l;
}
public function greeting() {
return "Hello, my name is {$this->first} {$this->last}.";
}
static public function staticGreeting($first, $last) {
return "Hello, my name is {$first} {$last}.";
}
}
$him = new Person('John', 'Smith');
$her = new Person('Sally', 'Davis');
echo $him->greeting(); // prints "Hello, my name is John Smith."
echo '<br />'; echo $her->greeting(); // prints "Hello, my name is Sally Davis."
echo '<br />';
echo Person::staticGreeting('Jane', 'Doe'); // prints "Hello, my name is Jane Doe."
 2008 Pearson Education, Inc. All rights reserved.
45
Resources (http://php.resourceindex.com)
Complete Scripts (3745) Hundreds of ready-to-use PHP
programs for your web site!
Functions and Classes (300) Although not complete scripts,
these code pieces aid in development and often with little
modification can become complete programs.
Documentation (425) Information, books, tutorials, examples
and help regarding PHP programming. If you want to learn it,
here's how. Includes: Examples and Tutorials (308)
Community (126) There is a large PHP community and this is
where you'll find resources such as jobs, chats, message
boards, developer sites and much more!Web Hosting Need a
web host for your PHP programs? Find one here.
 2008 Pearson Education, Inc. All rights reserved.
46
Complete Scripts (3745) (http://php.resourceindex.com)
Access Counters (67) Display how many visitors you've had in a text-based
or graphical manner.
Advertisements (70) Set up banner rotations on your web page and track
their statistics.
Auctions (38) Conduct online web-based auctions using these PHP scripts.
Audio Management (39) Manage and provide audio files in different formats
for users to listen to.
Bulletin Board Message Systems (66) On-line message forums allowing for
threaded discussions.
Calendars (76) Schedule events on-line and/or allow users to post dated
information.
Chat (77) Real time chat scripts for use on the web. These often bog down a
server.
Includes: Shoutbox (19), ...
Classified Ads (210) Users can post information on buying, selling and/or
trading possessions.
………..
 2008 Pearson Education, Inc. All rights reserved.
47
23.4 Form Processing and Business
Logic
• Superglobal arrays are associative arrays predefined by
PHP that hold variables acquired from user input, the
environment or the web server and are accessible in any
variable scope.
• The arrays $_GET and $_POST retrieve information sent
to the server by HTTP get and post requests,
respectively.
• Using method = "post" appends form data to the
browser request that contains the protocol and the
requested resource’s URL. Scripts located on the web
server’s machine can access the form data sent as part of
the request.
 2008 Pearson Education, Inc. All rights reserved.
48
Variable name
Description
$_SERVER
Data about the currently running server.
$_ENV
Data about the client’s environment.
$_GET
Data sent to the server by a get request.
$_POST
Data sent to the server by a post request.
$_COOKIE
Data contained in cookies on the client’s computer.
$GLOBALS
Array containing all global variables.
Fig. 23.11 | Some useful superglobal arrays.
 2008 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "utf-8"?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- XHTML form for gathering user input. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Sample form to take user input in XHTML</title>
10
11
12
13
14
15
16
49
<!-- Fig. 23.12: form.html -->
form.html
(1 of 4)
<style type = "text/css">
.prompt { color: blue;
font-family: sans-serif;
font-size: smaller }
</style>
</head>
<body>
Appends form data to the
browser request that
contains the protocol and
the URL of the requested
resource
17
18
<h1>Sample Registration Form</h1>
<p>Please fill in all fields and click Register.</p>
19
20
21
<!-- post form data to form.php -->
<form method = "post" action = "form.php">
22
23
Outline
Form data is posted to
form.php to be processed
<div>
<img src = "images/user.gif" alt = "User" /><br />
24
25
<span class = "prompt">
Please fill out the fields below.<br />
26
27
</span>
 2008 Pearson Education,
Inc. All rights reserved.
28
<!-- create four text boxes for user input -->
29
<img src = "images/fname.gif" alt = "First Name" />
30
31
<input type = "text" name = "fname" /><br />
32
<img src = "images/lname.gif" alt = "Last Name" />
33
<input type = "text" name = "lname" /><br />
34
35
<img src = "images/email.gif" alt = "Email" />
36
<input type = "text" name = "email" /><br />
50
Outline
form.html
(2 of 4)
37
38
39
<img src = "images/phone.gif" alt = "Phone" />
<input type = "text" name = "phone" /><br />
40
41
<span style = "font-size: 10pt">
42
43
44
Must be in the form (555)555-5555</span>
<br /><br />
45
<img src = "images/downloads.gif"
46
47
48
alt = "Publications" /><br />
49
Creates form fields
<span class = "prompt">
Which book would you like information about?
50
</span><br />
51
52
<!-- create drop-down list containing book names -->
53
<select name = "book">
Creates drop-down list
with book names
 2008 Pearson Education,
Inc. All rights reserved.
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<option>Internet and WWW How to Program 4e</option>
<option>C++ How to Program 6e</option>
<option>Java How to Program 7e</option>
<option>Visual Basic 2005 How to Program 3e</option>
</select>
<br /><br />
<img src = "images/os.gif" alt = "Operating System" />
<br /><span class = "prompt">
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 Vista" /> Windows Vista<br />
<input type = "radio" name = "os" value =
"Mac OS X" /> Mac OS X
<input type = "radio" name = "os" value = "Linux" /> Linux
<input type = "radio" name = "os" value = "Other" />
Other<br />
51
Outline
form.html
(3 of 4)
Creates radio buttons
with “Windows XP”
initially selected
 2008 Pearson Education,
Inc. All rights reserved.
77
<!-- create a submit button -->
78
<input type = "submit" value = "Register" />
</div>
79
80
81
52
Outline
</form>
</body>
82 </html>
form.html
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
53
Good Programming Practice 23.1
Use meaningful XHTML object names for
input fields. This makes PHP scripts that
retrieve form data easier to understand.
 2008 Pearson Education, Inc. All rights reserved.
54
23.4 Form Processing and Business
Logic (Cont.)
• Function extract creates a variable/value pair
corresponding to each key/value pair in the associative
array passed as an argument.
• Business logic, or business rules, ensures that only valid
information is stored in databases.
• We escape the normal meaning of a character in a string
by preceding it with the backslash character (\).
• Function die terminates script execution. The function’s
optional argument is a string, which is printed as the
script exits.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- Process information sent from form.html. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Form Validation</title>
10
11
12
13
14
15
16
form.php
(1 of 5)
<style type = "text/css">
body
div
{ font-family: arial, sans-serif }
{ font-size: 10pt;
table
text-align: center }
{ border: 0 }
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
padding-right: 10px }
19
20
21
.error
{ color: red }
.distinct { color: blue }
.name
{ background-color: #ffffaa }
22
23
.email
.phone
26
27
Outline
<!-- Fig. 23.13: form.php -->
17
18
24
25
55
.os
</style>
{ background-color: #ffffbb }
{ background-color: #ffffcc }
{ background-color: #ffffdd }
</head>
<body>
 2008 Pearson Education,
Inc. All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
extract( $_POST );
Creates a variable/value pair for each key/value pair
Outline
in $_POST
56
// 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 ) )
{
print( "<p><span class = 'error'>
Invalid phone number</span><br />
A valid phone number must be in the form
<strong>(555)555-5555</strong><br />
<span class = 'distinct'>
Click the Back button, enter a valid phone
form.php
(2 of 5)
Ensures that phone
number is in proper
format
number and resubmit.<br /><br />
Thank You.</span></p>" );
die( "</body></html>" ); // terminate script execution
44
45
}
?><!-- end PHP script -->
46
47
48
49
50
51
<p>Hi
<span class = "distinct">
<strong><?php print( "$fname" ); ?></strong>
</span>.
Thank you for completing the survey.<br />
You have been added to the
52
53
<span class = "distinct">
<strong><?php print( "$book " ); ?></strong>
54
55
</span>
mailing list.
Terminates execution and
closes the document
properly
 2008 Pearson Education,
Inc. All rights reserved.
56
57
</p>
<p><strong>The following information has been saved
in our database:</strong></p>
58
59
<table>
60
<tr>
61
62
63
<td class = "name">Name </td>
<td class = "email">Email</td>
<td class = "phone">Phone</td>
64
<td class = "os">OS</td>
Outline
form.php
(3 of 5)
</tr>
<tr>
65
66
<?php
67
68
// print each form field’s value
69
print( "<td>$fname $lname</td>
70
71
<td>$email</td>
<td>$phone</td>
72
<td>$os</td>" );
?><!-- end PHP script -->
73
74
75
76
</tr>
</table>
<br /><br /><br />
77
<div>This is only a sample form.
Prints the value entered
in the email field in
form.html
You have not been added to a mailing list.</div>
78
79
57
</body>
80 </html>
 2008 Pearson Education,
Inc. All rights reserved.
58
Outline
form.php
(4 of 5)
 2008 Pearson Education,
Inc. All rights reserved.
59
Outline
form.php
(5 of 5)
 2008 Pearson Education,
Inc. All rights reserved.
60
Software Engineering Observation 23.1
Use business logic to ensure that invalid
information is not stored in databases. When
possible, validate important or sensitive form
data on the server, since JavaScript may be
disabled by the client. Some data, such as
passwords, must always be validated on the
server side.
 2008 Pearson Education, Inc. All rights reserved.
61
Error-Prevention Tip 23.3
Be sure to close any open XHTML tags when
calling function die. Not doing so can produce
invalid XHTML output that will not display
properly in the client browser. Function die has
an optional parameter that specifies a message to
output when exiting, so one technique for closing
tags is to close all open tags using die, as in
die("</body></html>").
 2008 Pearson Education, Inc. All rights reserved.
62
23.5 Connecting to a Database
• Function mysql_connect connects to the MySQL database. It takes
three arguments—the server’s hostname, a username and a password,
and returns a database handle—a representation of PHP’s connection
to the database, or false if the connection fails.
• Function mysql_select_db specifies the database to be queried,
and returns a bool indicating whether or not it was successful.
• To query the database, we call function mysql_query, specifying the
query string and the database to query. This returns a resource
containing the result of the query, or false if the query fails. It can also
execute SQL statements such as INSERT or DELETE that do not
return results.
• Function mysql_error returns any error strings from the database.
• mysql_close closes the connection to the database specified in its
argument.
 2008 Pearson Education, Inc. All rights reserved.
1
2
3
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
63
Outline
4
5
<!-- Fig. 23.14: data.html -->
6
7
8
<!-- Form to query a MySQL database. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
<title>Sample Database Query</title>
10
11
<style type = "text/css">
body { background-color: #F0E68C }
12
h2
color: blue }
input { background-color: blue;
color: yellow;
font-weight: bold }
15
16
17
(1 of 2)
{ font-family: arial, sans-serif;
13
14
data.html
Posts data to
database.php
</style>
18
</head>
19
20
21
<body>
<h2> Querying a MySQL database.</h2>
<form method = "post" action = "database.php">
22
23
<div>
<p>Select a field to display:
24
<!-- add a select box containing options -->
25
<!-- for SELECT query -->
 2008 Pearson Education,
Inc. All rights reserved.
<select name = "select">
26
27
<option selected = "selected">*</option>
28
<option>ID</option>
29
<option>Title</option>
30
<option>Category</option>
31
<option>ISBN</option>
<input type = "submit" value = "Send Query" />
33
data.html
(2 of 2)
</div>
34
36
Outline
</select></p>
32
35
64
</form>
</body>
37 </html>
Creates drop-down menu specifying
which data to output to the screen, with
* (all data) as the default selection
 2008 Pearson Education,
Inc. All rights reserved.
1
2
3
4
5
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
11
12
13
body
14
15
16
td
database.php
(1 of 3)
{ font-family: arial, sans-serif;
background-color: #F0E68C }
table { background-color: #ADD8E6 }
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
17
18
padding-right: 4px;
border-width: 1px;
19
20
21
22
23
24
border-style: inset }
27
28
Outline
<!-- Fig. 23.15: database.php -->
6 <!-- Querying a database and displaying the results. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Search Results</title>
10
<style type = "text/css">
25
26
65
</style>
</head>
<body>
<?php
extract( $_POST );
Builds a SELECT query
with the selection made
in data.html
// build SELECT query
$query = "SELECT " . $select . " FROM books";
 2008 Pearson Education,
Inc. All rights reserved.
29
30
31
32
33
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
34
35
36
37
38
// open Products database
if ( !mysql_select_db( "products", $database ) )
die( "Could not open products database </body></html>" );
39
40
41
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
42
43
44
die( mysql_error() . "</body></html>" );
} // end if
Returns
// query Products database
any error strings
from the database
45
46
mysql_close( $database );
?><!-- end PHP script -->
47
48
49
50
51
52
Closes the connection to
<h3>Search Results</h3>
the database
<table>
<?php
// fetch each record in result set
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
53
54
55
56
66
Outline
database.php
(2 of 3)
Connects to database
using server hostname
localhost and
username and password
“iw3htp4”
Specifies products as
the database to be
queried
Queries $database
with $query
{
// build table to display results
print( "<tr>" );
Returns an array with the
values for each column
of the current row in
$result
 2008 Pearson Education,
Inc. All rights reserved.
foreach ( $row as $key => $value )
57
print( "<td>$value</td>" );
58
67
Outline
59
print( "</tr>" );
60
} // end for
61
?><!-- end PHP script -->
62
63
</table>
64
<br />Your search yielded <strong>
65
<?php print( "$counter" ) ?> results.<br /><br /></strong>
66
<h5>Please email comments to
67
<a href = "mailto:[email protected]">
68
Deitel and Associates, Inc.</a>
69
70
database.php
(3 of 3)
</h5>
</body>
71 </html>
 2008 Pearson Education,
Inc. All rights reserved.
68
23.6 Using Cookies
• A cookie is a text file that a website stores on a client’s computer to
maintain information about the client during and between browsing
sessions.
• A server can access only the cookies that it has placed on the client.
• Function setcookie takes the name of the cookie to be set as the
first argument, followed by the value to be stored in the cookie. The
optional third argument indicates the expiration date of the cookie. A
cookie without a third argument is known as a session cookie, while
one with an expiration date is a persistent cookie. If only the name
argument is passed to function setcookie, the cookie is deleted
from the client’s computer.
• Cookies defined in function setcookie are sent to the client at the
same time as the information in the HTTP header; therefore, it needs
to be called before any XHTML is printed.
• The current time is returned by function time.
 2008 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
69
Outline
<!-- Fig. 23.16: cookies.html -->
6 <!-- Gathering data to be written as a cookie. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Writing a cookie to the client computer</title>
10
<style type = "text/css">
11
12
13
body
14
15
16
.submit { background-color: #F0E86C;
color: navy;
font-weight: bold }
form
Posts form data to
cookies.php
</style>
</head>
19
20
21
22
23
24
<body>
<h2>Click Write Cookie to save your cookie data.</h2>
<form method = "post" action = "cookies.php">
<div>
<strong>Name:</strong><br />
<input type = "text" name = "Name" /><br />
27
28
(1 of 2)
{ font-family: arial, sans-serif;
background-color: #99CCFF }
{ font-size: 10pt }
17
18
25
26
cookies.html
Creates fields to gather
information to be written
into a cookie
<strong>Height:</strong><br />
<input type = "text" name = "Height" /><br />
 2008 Pearson Education,
Inc. All rights reserved.
29
<strong>Favorite Color:</strong><br />
30
<input type = "text" name = "Color" /><br />
70
Outline
31
<input type = "submit" value = "Write Cookie"
32
class = "submit" />
33
</div>
34
35
36
Form field
cookies.html
</form>
</body>
(2 of 2)
37 </html>
 2008 Pearson Education,
Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// Fig. 23.17: cookies.php
// Writing a cookie to the client.
extract( $_POST );
// write each form field’s value to a cookie and set the
// cookie’s 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 );
?><!-- end PHP script -->
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
71
Outline
cookies.php
(1 of 2)
Creates a cookie for each
entered value and sets the
expiration date to be five
days after the current
time
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
19
20
21
22
23
24
<title>Cookie Saved</title>
<style type = "text/css">
body { font-family: arial, sans-serif }
span { color: blue }
</style>
</head>
25
26
27
28
29
<body>
<p>The cookie has been set with the following data:</p>
<!-- print each form field’s value -->
<br /><span>Name:</span><?php print( $Name ) ?><br />
 2008 Pearson Education,
Inc. All rights reserved.
30
<span>Height:</span><?php print( $Height ) ?><br />
31
<span>Favorite Color:</span>
32
<span style = "color: <?php print( "$Color\">$Color" ) ?>
33
</span><br />
34
<p>Click <a href = "readCookies.php">here</a>
to read the saved cookie.</p>
35
36
</body>
37 </html>
Links to the page that
displays the contents of
the cookie
72
Outline
cookies.php
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
73
Software Engineering Observation 23.2
Some clients do not accept cookies. When
a client declines a cookie, the browser
application normally informs the user that
the site may not function correctly without
cookies enabled.
 2008 Pearson Education, Inc. All rights reserved.
74
Software Engineering Observation 23.3
Cookies should not be used to store
e-mail addresses or private data on a
client’s computer.
 2008 Pearson Education, Inc. All rights reserved.
75
23.6 Using Cookies (Cont.)
• When using Internet Explorer, cookies are stored
in a Cookies directory on the client’s machine.
In Firefox, cookies are stored in a file named
cookies.txt.
 2008 Pearson Education, Inc. All rights reserved.
76
Fig. 23.18 | IE7’s Cookies directory before a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
77
Fig. 23.19 | IE7’s Cookies directory after a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
78
23.6 Using Cookies (Cont.)
• PHP creates the superglobal array $_COOKIE,
which contains all the cookie values indexed by
their names.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- Displaying the cookie’s contents. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Read Cookies</title>
10
Outline
<!-- Fig. 23.20: readCookies.php -->
readCookies.php
(1 of 2)
<style type = "text/css">
body
table
{ font-family: arial, sans-serif }
{ border-width: 5px;
13
14
td
border-style: outset }
{ padding: 10px }
15
16
.key
{ background-color: #F0E68C }
.value { background-color: #FFA500 }
11
12
17
18
</style>
</head>
19
20
21
<body>
<p>
<strong>The following data is saved in a cookie on your
computer.</strong>
22
23
</p>
24
25
<table>
<?php
26
27
79
// iterate through array $_COOKIE and print
// name and value of each cookie
 2008 Pearson Education,
Inc. All rights reserved.
foreach ( $_COOKIE as $key => $value )
28
<td class = 'value' >$value</td></tr>" );
30
?><!-- end PHP script -->
31
33
Outline
print( "<tr><td class = 'key' >$key</td>
29
32
80
</table>
</body>
Iterates through
all values in
$_COOKIE
readCookies.php
34 </html>
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
81
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4
<!-- Fig. 26.11: env.php
-->
5
<!-- Program to display environment variables -->
6
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Environment Variables</title>
</head>
11
12
13
<body>
<table border = "0" cellpadding = "2" cellspacing = "0"
width = "100%">
14
15
<?php
16
17
// print the key and value for each element
18
// in the $_ENV array
19
foreach ( $_ENV as $key => $value )
print( "<tr><td
= \"#11bbff\">
Thebgcolor
foreach
loop is used
20
21
22
23
?>
24
</table>
25
to print out the keys and
<strong>$key</strong></td>
values for each element in the $_ENV array.
<td>$value</td></tr>"
);
PHP stores environment
variables and their values in
the $_ENV array.
</body>
26 </html>
 2008 Pearson Education,
Inc. All rights reserved.
82
Fig. 26.12
Displaying environment variables.
 2008 Pearson Education,
Inc. All rights reserved.
83
23.7 Dynamic Content
• Function isset allows you to find out if a
variable has a value.
• A variable variable ($$variable) allows the
code to reference variables dynamically. You can
use this expression to obtain the value of the
variable whose name is equal to the value of
$variable.
• The quotemeta function inserts a backslash (\)
before any special characters in the passed string.
 2008 Pearson Education, 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
22
23
24
25
26
27
28
29
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 23.21: dynamicForm.php -->
<!-- Dynamic form. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Sample form to take user input in XHTML</title>
<style type = "text/css">
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
padding-right: 10px }
div
{ text-align: center }
div div
{ font-size: larger }
.name
{ background-color: #ffffaa }
.email
{ background-color: #ffffbb }
.phone
.os
.smalltext
.prompt
{
{
{
{
84
Outline
dynamicForm.php
(1 of 12)
background-color: #ffffcc }
background-color: #ffffdd }
font-size: smaller }
color: blue;
font-family: sans-serif;
font-size: smaller }
.largeerror { color: red }
.error
{ color: red;
font-size: smaller }
</style>
</head>
 2008 Pearson Education,
Inc. All rights reserved.
30
31
32
33
34
<body>
<?php
extract( $_POST );
$iserror = false;
85
Outline
35
36
37
38
39
// array of book titles
$booklist = array( "Internet and WWW How to Program 4e",
"C++ How to Program 6e", "Java How to Program 7e",
"Visual Basic 2005 How to Program 3e" );
40
41
42
// array of possible operating systems
$systemlist = array( "Windows XP", "Windows Vista",
"Mac OS X", "Linux", "Other");
43
44
45
// array of name values for the text input fields
$inputlist = array( "fname" => "First Name",
46
47
"lname" => "Last Name", "email" => "Email",
"phone" => "Phone" );
48
49
50
51
52
53
54
55
56
57
dynamicForm.php
(2 of 12)
// ensure that all fields have been filled in correctly
if ( isset ( $submit ) )
Checks whether the Register
{
button has been pressed
if ( $fname == "" )
{
$formerrors[ "fnameerror" ] = true;
$iserror = true;
Checks that the first name field is
not blank
} // end if
Makes an entry in the error array
Sets $iserror to true
 2008 Pearson Education,
Inc. All rights reserved.
58
59
if ( $lname == "" )
{
86
60
$formerrors[ "lnameerror" ] = true;
61
$iserror = true;
62
} // end if
63
64
65
if ( $email == "" )
{
$formerrors[ "emailerror" ] = true;
66
67
68
$iserror = true;
} // end if
Outline
Checks that all
other form fields
are filled in
correctly
dynamicForm.php
(3 of 12)
69
70
if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) )
71
{
72
73
74
$formerrors[ "phoneerror" ] = true;
$iserror = true;
} // end if
75
76
77
78
79
if ( !$iserror )
{
// build INSERT query
$query = "INSERT INTO contacts " .
80
"( LastName, FirstName, Email, Phone, Book, OS ) " .
81
"VALUES ( '$lname', '$fname', '$email', " .
82
"'" . quotemeta( $phone ) . "', '$book', '$os' )";
Inserts a backslash
before the parentheses
in the phone number
 2008 Pearson Education,
Inc. All rights reserved.
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
87
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database" );
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
die( "Could not open MailingList database" );
Outline
dynamicForm.php
(4 of 12)
// execute query in MailingList database
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
die( mysql_error() );
} // end if
mysql_close( $database );
print( "<p>Hi<span class = 'prompt'>
<strong>$fname</strong></span>.
Thank you for completing the survey.<br />
You have been added to the
<span class = 'prompt'>
<strong>$book</strong></span>
mailing list.</p>
<strong>The following information has been saved
in our database:</strong><br />
 2008 Pearson Education,
Inc. All rights reserved.
113
114
115
116
117
<table><tr>
<td class =
<td class =
<td class =
<td class =
118
119
120
121
122
</tr><tr>
123
124
125
<td>$phone</td>
<td>$os</td>
</tr></table>
126
127
128
<br /><br /><br />
<div><div>
129
130
<a href = 'formDatabase.php'>
Click here to view entire database.</a>
88
'name'>Name </td>
'email'>Email</td>
'phone'>Phone</td>
'os'>OS</td>
<!-- print each form field’s value -->
<td>$fname $lname</td>
<td>$email</td>
131
132
133
134
135
136
</div>This is only a sample form.
You have not been added to a mailing list.
</div></body></html>" );
die();
} // end if
} // end if
137
138
print( "<h1>Sample Registration Form.</h1>
139
140
Please fill in all fields and click Register." );
Outline
dynamicForm.php
(5 of 12)
Ends script here if
there were no errors
in the user input
Section to be
executed only if
$iserror is true
 2008 Pearson Education,
Inc. All rights reserved.
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
if ( $iserror )
{
print( "<br /><span class = 'largeerror'>
Fields with * need to be filled in properly.</span>" );
} // end if
print( "<!-- post form data to form.php -->
<form method = 'post' action = 'dynamicForm.php'>
<img src = 'images/user.gif' alt = 'User' /><br />
<span class = 'prompt'>
Please fill out the fields below.<br /> </span>
<!-- create four text boxes for user input -->" );
foreach ( $inputlist as $inputname => $inputalt )
{
$inputtext = $inputvalues[ $inputname ];
print( "<img src = 'images/$inputname.gif'
alt = '$inputalt' /><input type = 'text'
name = '$inputname' value = '" . $$inputname . "' />" );
if ( $formerrors[ ( $inputname )."error" ] == true )
print( "<span class = 'error'>*</span>" );
print( "<br />" );
} // end foreach
if ( $formerrors[ "phoneerror" ] )
print( "<span class = 'error'>" );
89
Outline
dynamicForm.php
(6 of 12)
Alerts the user that
there are errors
Iterates through
$inputlist to create
the form’s text boxes
Outputs the field’s
image
Sets the name attribute
of the text field to
$inputname
Sets the value attribute of the text
field to the value of the variable
Puts an asterisk with the name of $inputname’s
next to fields that
value
have errors
 2008 Pearson Education,
Inc. All rights reserved.
170
else
172
173
90
print("<span class = 'smalltext'>");
171
print( "Must be in the form (555)555-5555
</span><br /><br />
174
175
<img src = 'images/downloads.gif'
alt = 'Publications' /><br />
176
177
178
179
<span class = 'prompt'>
180
181
Which book would you like information about?
</span><br />
182
183
<!-- create drop-down list containing book names -->
foreach ( $booklist as $currbook )
187
{
191
195
(7 of 12)
print( "<option" );
if ( ( $currbook == $book ) )
print( " selected = 'true'" );
192
193
194
dynamicForm.php
<select name = 'book'>" );
184
185
186
188
189
190
Outline
print( ">$currbook</option>" );
} // end foreach
Creates drop-down
list for books,
keeping the
previously selected
one selected
 2008 Pearson Education,
Inc. All rights reserved.
196
197
198
199
200
201
202
203
204
print( "</select><br /><br />
<img src = 'images/os.gif' alt = 'Operating System' />
<br /><span class = 'prompt'>
Which operating system are you currently using?
<br /></span>
<!-- create five radio buttons -->" );
$counter = 0;
91
Outline
dynamicForm.php
(8 of 12)
205
206
207
foreach ( $systemlist as $currsystem )
{
208
209
print( "<input type = 'radio' name = 'os'
value = '$currsystem'" );
210
211
if ( $currsystem == $os )
212
213
print( "checked = 'checked'" );
elseif ( !$os && $counter == 0 )
214
215
216
print( "checked = 'checked'" );
print( " />$currsystem" );
217
218
// put a line break in list of operating systems
219
220
if ( $counter == 1 ) print( "<br />" );
++$counter;
221
222
} // end foreach
Creates radio
buttons for
operating-system
selection, keeping
the previously
selected option
selected
 2008 Pearson Education,
Inc. All rights reserved.
223
print( "<!-- create a submit button -->
224
<br /><input type = 'submit' name = 'submit'
225
value = 'Register' /></form></body></html>" );
226
92
Outline
?><!-- end PHP script -->
dynamicForm.php
(9 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
93
Outline
dynamicForm.php
(10 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
94
Outline
dynamicForm.php
(11 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
95
Outline
dynamicForm.php
(12 of 12)
 2008 Pearson Education,
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
22
23
24
25
26
27
28
29
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 23.22: formDatabase.php -->
<!-- Displaying the MailingList database. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Search Results</title>
<style type = "text/css">
body { font-family: arial, sans-serif;
background-color: #F0E68C }
h3
{ color: blue }
table { background-color: #ADD8E6 }
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
border-width: 1px;
border-style: inset }
</style>
</head>
<body>
<?php
96
Outline
formDatabase.php
(1 of 3)
Selects all fields from
the contacts
database to display
extract( $_POST );
// build SELECT query
$query = "SELECT * FROM contacts";
 2008 Pearson Education,
Inc. All rights reserved.
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<h3>Mailing List Contacts</h3>
48
49
50
51
52
53
<table>
<tr>
<td>ID</td>
<td>Last Name</td>
<td>First Name</td>
<td>E-mail Address</td>
54
55
56
57
58
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
die( "Could not open MailingList database </body></html>" );
97
Outline
formDatabase.php
(2 of 3)
// query MailingList database
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
die( mysql_error() . "</body></html>" );
} // end if
?><!-- end PHP script -->
<td>Phone Number</td>
<td>Book</td>
<td>Operating System</td>
</tr>
<?php
 2008 Pearson Education,
Inc. All rights reserved.
59
// fetch each record in result set
60
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
61
98
Outline
{
62
63
// build table to display results
64
print( "<tr>" );
formDatabase.php
foreach ( $row as $key => $value )
(3 of 3)
65
66
print( "<td>$value</td>" );
67
68
print( "</tr>" );
69
} // end for
70
71
mysql_close( $database );
72
?><!-- end PHP script -->
73
74
75
</table>
</body>
76 </html>
 2008 Pearson Education,
Inc. All rights reserved.
99
23.8 Operator Precedence Chart
• The following table contains a list of PHP
operators in decreasing order of precedence.
 2008 Pearson Education, Inc. All rights reserved.
100
Operator
Type
Associativity
new
constructor
none
[]
subscript
right to left
~
!
++
-@
bitwise not
not
increment
decrement
unary negative
error control
right to left
*
/
%
multiplication
division
modulus
left to right
+
.
addition
subtraction
concatenation
left to right
Fig. 23.23 | PHP operator precedence and associativity. (Part 1 of 3.)
 2008 Pearson Education, Inc. All rights reserved.
101
Operator
Type
Associativity
<<
bitwise shift left
left to right
>>
bitwise shift right
<
>
<=
>=
less than
greater than
less than or equal
greater than or equal
none
==
!=
===
!==
equal
not equal
identical
not identical
none
&
bitwise AND
left to right
^
bitwise XOR
left to right
|
bitwise OR
left to right
&&
logical AND
left to right
||
logical OR
left to right
Fig. 23.23 | PHP operator precedence and associativity. (Part 2 of 3.)
 2008 Pearson Education, Inc. All rights reserved.
102
Operator
Type
Associativity
=
+=
-=
*=
/=
&=
|=
^=
.=
<<=
>>=
assignment
left to right
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
and
logical AND
left to right
xor
exclusive OR
left to right
or
logical OR
left to right
,
list
left to right
Fig. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)
 2008 Pearson Education, Inc. All rights reserved.