You are on page 1of 107

Chapter 26 - PHP

Outline
26.1
26.2
26.3
26.4
26.5
26.6
26.7
26.8
26.9
26.10
26.11

Introduction
PHP
String Processing and Regular Expressions
Viewing Client/Server Environment Variables
Form Processing and Business Logic
Verifying a Username and Password
Connecting to a Database
Cookies
Dynamic Content in PHP
Operator Precedence
Web Resources

Objectives
In this chapter, you will learn:

To understand PHP data types, operators, arrays and


control structures.
To understand string processing and regular
expressions in PHP.
To construct programs that process form data.
To be able to read and write client data using
cookies.
To construct programs that interact with MySQL
databases.
2

26.1 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

26.2 PHP

Basic application

Scripting delimiters
<? php ?>

Variables preceded by $ symbol

Must enclose all script code


Case-sensitive

End statements with semicolon


Comments
for single line
/* */ for multiline
//

Filenames end with .php by convention


4

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

2
3
4

<!-- Fig. 26.1: first.php -->

<!-- Our first PHP script -->

Scripting delimiters

6
7

<?php
$name = "LunaTic";

8
9

first.php
(1 of 1)

// declaration

Declare variable $name

?>

10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12
13
14

<head>
<title>A simple PHP document</title>Single-line

comment

</head>

15
16
17

<body style = "font-size: 2em">


<p>
<strong>

18
19
20

<!-- print variable names value -->

21

Welcome to PHP, <?php print( "$name" ); ?>!


</strong>

22
23

</p>

24

</body>

25 </html>

Function print outputs the value of variable


$name
5

26.2 PHP
Fig. 26.1

Simple PHP program.

26.2 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
7

26.2 PHP
D
a
taty
p
e

D
e
s
c
rip
tio
n
i
n
t
,i
n
t
e
g
e
r W
h
o
len
u
m
b
e
rs(i.e
.,n
u
m
b
e
rsw
ith
o
u
tad
e
c
im
a
lp
o
in
t).
f
l
o
a
t
,d
o
u
b
l
eR
e
a
ln
u
m
b
e
rs(i.e
.,n
u
m
b
e
rsc
o
n
ta
in
in
gad
e
c
im
a
lp
o
in
t).
s
t
r
i
n
g
T
e
x
te
n
c
lo
s
e
dine
ith
e
rs
in
g
le('
'
)o
rd
o
u
b
le("
"
)q
u
o
te
s
.
b
o
o
l
,B
o
o
l
e
a
nT
ru
eo
rfa
ls
e
.
a
r
r
a
y
G
ro
u
po
fe
le
m
e
n
tso
fth
es
a
m
ety
p
e
.
o
b
j
e
c
t
G
ro
u
po
fa
s
s
o
c
ia
te
dd
a
taa
n
dm
e
th
o
d
s
.
R
e
s
o
u
r
c
e
A
ne
x
te
rn
a
ld
a
tas
o
u
rc
e
.
N
U
L
L
N
ov
a
lu
e
.
F
ig
.2
6
.2
P
H
P
d
a
taty
p
e
s
.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.3: data.php

-->

data.php
(1 of 3)

5 <!-- Demonstration of PHP data types -->


6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10

<head>
<title>PHP data types</title>
</head>

11
12

<body>

13
14

<?php

15

Assign a string to variable


$testString

16

// declare a string, double and integer

17

$testString = "3.5 seconds";

18

$testDouble = 79.2;

19

$testInteger = 12;

20

Assign a double to variable


Assign
an integer to variable
$testDouble
$testInteger

?>

21

22

<!-- print each variables value -->

23

<?php print( $testString ); ?> is a string.<br />

24

<?php print( $testDouble ); ?> is a double.<br />

25

<?php print( $testInteger ); ?> is an integer.<br />

data.php
of 3)
Print each variables (2
value

26
27

<br />

28

Now, converting to other types:<br />

29

<?php

30
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

function
settype
print( "Converting back toCall
a string
results
in

41
42
43

to
convert
the data type
$testString <br /><br
/>"
); settype
Call function
to of
variable
to a
convert
the data$testString
type of
double.
$data = "98.6 degrees";
variable
$testString to an
integer.
Convert variable $testString
back to a string
10

4
4
4
5

/
/u
s
et
y
p
ec
a
s
t
i
n
gt
oc
a
s
tv
a
r
i
a
b
l
e
st
oa

4
6

/
/d
i
f
f
e
r
e
n
tt
y
p
e

4
7

p
r
i
n
t
("
N
o
wu
s
i
n
gt
y
p
ec
a
s
t
i
n
gi
n
s
t
e
a
d
:<
b
r/
>

4
8

A
sas
t
r
i
n
g-".(
s
t
r
i
n
g
)$
d
a
t
a.

4
9

"
<
b
r/
>
A
sad
o
u
b
l
e-".(
d
o
u
b
l
e
)$
d
a
t
a.

5
0

"
<
b
r/
>
A
sa
ni
n
t
e
g
e
r-".(
i
n
t
e
g
e
r
)$
d
a
t
a)
;

5
1

?
>

5
2

<
/
b
o
d
y
>

5
3<
/
h
t
m
l
>

data.php
(3 of 3)
Use type casting to cast variable
$data to different types

11

26.2 PHP
Fig. 26.3

Type conversion.

12

26.2 PHP

Arithmetic operators

Assignment operators

Syntactical shortcuts
Before being assigned values, variables have value
undef

Constants

Named values
define function

13

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.4: operators.php

-->

operators.php
(1 of 3)

5 <!-- Demonstration of operators -->


6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10

<head>
<title>Using arithmetic operators</title>
</head>

11
12
13

<body>
<?php

Define constant VALUE.

14

$a = 5;

15

print( "The value of variable a is $a <br />" );

16
17

// define constant VALUE

18

define( "VALUE", 5 );

Add constant VALUE to variable $a.

19
20

// add constant VALUE to variable $a

21

$a = $a + VALUE;

22

print( "Variable a after adding constant VALUE

23

is $a <br />" );

24

14

25

// multiply variable $a by 2

26

$a *= 2;

27

print( "Multiplying variable a by 2 yields $a <br />" );

Multiply variable $a by two using the


multiplication assignment operator *=.

28

operators.php
50
Print if variable $a isTest
lesswhether
than 50.variable $a is less(2than
of 3)

29

// test if variable $a is less than 50

30

if ( $a < 50 )

31

print( "Variable a is less than 50 <br />" );

32
33

// add 40 to variable $a

34

$a += 40;

35

print( "Variable a after adding 40 is $a <br />" );

Add 40 to variable $a using the addition assignment


operator +=.

36
37

// test if variable $a is 50 or less

38

if ( $a < 51 )

39

print( "Variable a is still 50 or less<br />" );

40
41

// test if variable $a is between 50 and 100, inclusive

42

elseif ( $a < 101 )

43

print( "Variable a is now between 50 and 100,


inclusive<br />" );

44
45
46
47

else
print( "Variable a is now greater than 100
<br />" );

48

15

49

// print an uninitialized variable

50

print( "Using a variable before initializing:


$nothing <br />" );

51
52
53

// add constant VALUE to an uninitialized variable

54

$test = $num + VALUE;

55

print( "An uninitialized variable plus constant


VALUE yields $test <br />" );

56

Print anAdd
uninitialized
variable
$nothing
).
constant VALUE
to (an
uninitialized

57
58

// add a string to an integer

59

$str = "3 dollars";

60

$a += $str;

61

print( "Adding a string to variable a yields $a

64

variable.

<br />" );

62
63

operators.php
(3 of 3)

?>
</body>

Add a string to an integer.

65 </html>

16

26.2 PHP
Fig. 26.4

Using PHPs arithmetic operators.

17

26.2 PHP

Keywords

Reserved for language features

ifelseifelse

Arrays

Group of related data

Elements

Name plus braces and index

Indices start at zero

count function
array function
18

26.2 PHP

Arrays, cont.

Built-in iterators

Maintain pointer to element currently referenced

reset
key
next
foreach

loops

19

26.2 PHP
P
H
P
k
e
y
w
o
rd
s
a
n
d
b
r
e
a
k
c
a
s
e
c
l
a
s
s
c
o
n
t
i
n
u
e
d
e
f
a
u
l
t

d
o
f
o
r
i
n
c
l
u
d
er
e
q
u
i
r
et
r
u
e
e
l
s
e
f
o
r
e
a
c
hl
i
s
t
r
e
t
u
r
n v
a
r
e
l
s
e
i
f f
u
n
c
t
i
o
nn
e
w
s
t
a
t
i
c v
i
r
t
u
a
l
e
x
t
e
n
d
sg
l
o
b
a
l n
o
t
s
w
i
t
c
h x
o
r
f
a
l
s
e i
f
o
r
t
h
i
s
w
h
i
l
e

F
ig
.2
6
.5
P
H
P
k
e
y
w
o
rd
s
.

20

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.6: arrays.php -->
5 <!-- Array manipulation

arrays.php
(1 of 3)

-->

6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10

<head>
<title>Array manipulation</title>
</head>

11
12
13

<body>

Create the array $first by assigning a value


to an array element.

<?php

14
15

// create array first

16

print( "<strong>Creating the first array</strong>

17

<br />" );

18

$first[ 0 ] = "zero";

19

$first[ 1 ] = Assign
"one";

22

a value to the array, omitting the index.


for loop
each
elements index and value.
$first[ 2 ] = Appends
"two";
a Use
newaelement
to to
theprint
end out
of the
array.
Function count returns the total number of elements in the
$first[] = "three";
array.

23

// print each elements index and value

24

for ( $i = 0; $i < count( $first ); $i++ )

20
21

25

print( "Element $i is $first[$i] <br />" );

21

26
27
28

print( "<br /><strong>Creating the second array

Call function array to create an array that contains


the arguments passed to it. Store the array in variable
arrays.php
function array to create array$second
second .
(2 of 3)
= array( "zero", "one", "two", "three" );

</strong><br />" );

29
30

// call

31

$second

32

for ( $i = 0; $i < count( $second ); $i++ )

33

print( "Element $i is $second[$i] <br />" );

34
35
36

print( "<br /><strong>Creating the third array


</strong><br />" );

37
38

// assign values to non-numerical indices

39

$third[ "ArtTic" ] = 21;

40

$third[

41

$third[

42

Assign values to non-numerical indices


"LunaTic" ] = 18;
in array $third.
"GalAnt" ] = 23; Function reset sets the internal pointer to the
first element of the array.

43

// iterate through the array elements and print each

44

// elements name and value

45

for ( reset( $third ); $element = key( $third );

46

next( $third ) )

47

print( "$element is $third[$element] <br />" );

48

Function key returns the index of the element which


the internal pointer references.
Function next moves the internal pointer to the next
element.

22

print( "<br /><strong>Creating the fourth array

49

</strong><br />" );

50
51
52

// call function array to create array fourth using

53

// string indices

54

$fourth = array(

55

"January"

=> "first",

"February" => "second",

56

"March"

=> "third",

"April"

arrays.php
(3 of 3)
=> "fourth",

60

used
in",function array to assign each
"May"
=> "fifth", Operator
"June" =>=is
>"
sixth
a string
index.
value to the left of the
"July"
=> "seventh",element
"August"
=> "e
ighth"The
,
index,
and the value to the right is
"September" => "ninth", operator
"Octoberis
" the
=> array
"tenth
",
elements
value.
"November" => "eleventh"the
,"De
cember" =>
"twelfth"

61

);

57
58
59

62
63

// print each elements name and value

64

foreach ( $fourth as $element => $value )


print( "$element is the $value month <br />" );

65
66

?>

67

</body>

68 </html>

23

26.2 PHP
Fig. 26.6

Array manipulation.

24

26.3 String Processing and Regular


Expressions

String processing

Equality and comparison two important operations


strcmp function

Returns 1 if string 1 < string 2


Returns 0 if string 1 = string 2
Returns 1 if string 1 > string 2

Relational operators

25

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.7: compare.php -->
5 <!-- String Comparison

-->

compare.php
(1 of 2)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<title>String Comparison</title>
</head>

11
12
13

<body>
<?php

Use a for loop to iterate through each array element.

14
15

// create array fruits

16

$fruits = array( "apple", "orange", "banana" );

17
18

// iterate through

19

for ( $i = 0; $i <

20

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.

21

// call function strcmp to compare the array element

22

// to string "banana"

23

if ( strcmp( $fruits[ $i ], "banana" ) < 0 )

24

print( $fruits[ $i ]." is less than banana " );

26

elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )

25

print( $fruits[ $i ].

26

" is greater than banana " );

27
else

28

print( $fruits[ $i ]." isUse


equarelational
l to bananoperators
a " );

to compare each array


compare.php
element to string apple.
(2 of 2)

29
30
31

// use relational operators to compare each element

32

// to string "apple"

33

if ( $fruits[ $i ] < "apple" )


print( "and less than apple! <br />" );

34

elseif ( $fruits[ $i ] > "apple" )

35

print( "and greater than apple! <br />" );

36

elseif ( $fruits[ $i ] == "apple" )

37

print( "and equal to apple! <br />" );

38
39
}

40
41
42

?>
</body>

43 </html>

27

26.3 String Processing and Regular


Expressions
Fig. 26.7

Using the string comparison operators.

28

26.3 String Processing and Regular


Expressions

Regular expressions

Pattern matching templates


ereg function

POSIX

preg_match function

Perl

ereg_replace function

Building regular expressions

Metacharacters
$, ., ^

Brackets [ ]

29

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.8: expression.php -->
5 <!-- Using regular expressions -->
6

expression.php
(1 of 3)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<title>Regular expressions</title>
</head>

11
12

<body>

14

Function ereg searches for the literal


characters Now inside variable $search.
$search = "Now is the time";

15

print( "Test string is: '$search'<br /><br />" );

13

<?php

16
17

// call function ereg to search for pattern 'Now'

18

// in variable search

19

if ( ereg( "Now", $search ) )

20

print( "String 'Now' was found.<br />" );

21

30

22

// search for pattern 'Now' in the beginning of

23

// the string

24

if ( ereg( "^Now", $search ) )

The dollar sign special character ($) search for the


pattern
Now at
end of the
the string.
The caret special
character
(^)the
matches
expression.php
of the line.<br />" );
beginning of a string. Function ereg searches the
(2 of 3)
beginning
of
the
string
for
pattern
Now
.
search for pattern 'Now' at the end of the string
print( "String 'Now' found at beginning

25
26
27
28

//

29

if ( ereg( "Now$", $search ) )

30
31

print( "String 'Now' was found at the end


of the line.<br />" );

32
33

// search for any word ending in 'ow'

34

if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search,

35

$match ) )

36

print( "Word found ending in 'ow': " .

37

$match[ 1 ] . "<br />" );

38

The expression
the expressions
parentheses,[[:<:]]
[a-zA-Z]*ow
The specialinside
bracket
and ,
matches
any
word
ending
in ow. The
quantifier
Placing
a pattern
in the
parentheses
stores
the of
matched
[[:>:]]
match
beginning
and
end
a*
with 't' found: ");
matches
thethe
preceding
pattern
0 or more
times.
string
in
array that
is specified
in the
third argument
word,
respectively.
to function ereg.

39

// search for any words beginning with 't'

40

print( "Words beginning

41
42

while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",

43

$search, $match ) ) {

44

print( $match[ 1 ] . " " );

45

The pattern used in this example,

[[:<:]](t[[:alpha:]]+)[[:>:]], matches any


The while word
loop is
used to find
occurrence of a
beginning
witheach
the character
or
Function eregi
is used
to specify
case
insensitivet followed by one 31
word in themore
stringcharacters.
beginningCharacter
with t. class [[:alpha:]]
pattern matches.

recognizes any alphabetic character.

4
6

/
/
r
e
m
o
v
e
t
h
e
f
i
r
s
t
o
c
c
u
r
r
e
n
c
e
o
f
a
w
o
r
d
b
e
g
i
n
n
i
n
g

4
7

/
/
w
i
t
h
'
t
'
t
o
f
i
n
d
o
t
h
e
r
i
n
s
t
a
n
c
e
s
i
n
t
h
e
s
t
r
i
n
g

4
8

$
s
e
a
r
c
h
=
e
r
e
g
_
r
e
p
l
a
c
e
(
$
m
a
t
c
h
[
1
]
,
"
"
,
$
s
e
a
r
c
h
)
;
}

4
9
5
0
5
1
5
2
5
3

p
r
i
n
t
(
"
<
b
r
/
>
"
)
;
?
>
<
/
b
o
d
y
>

5
4<
/
h
t
m
l
>

expression.php
After printing a match of a word beginning with t, function
(3 of
3)
ereg_replace is called to remove the word from the
string.
This is necessary be because to find multiple instances of a
given pattern, the first matched instance must first be removed.
Function ereg_replace takes three arguments: the pattern to
match, a string to replace the matched string and the string to
search.

32

26.3 String Processing and Regular


Expressions
Fig. 26.8

Regular expressions in PHP.

33

26.3 String Processing and Regular


Expressions
Q
u
a
n
tifie
r

M
a
tc
h
e
s

{
n
}
{
m
,
n
}
{
n
,
}
+
*
?

E
x
a
c
tlyn
tim
e
s
.
B
e
tw
e
e
nm
a
n
dn
tim
e
sin
c
lu
s
iv
e
.
n
o
rm
o
retim
e
s
.
O
n
eo
rm
o
retim
e
s(s
a
m
ea
s{
1
,
}
).
Z
e
roo
rm
o
retim
e
s(s
a
m
ea
s{
0
,
}
).
Z
e
roo
ro
n
etim
e(s
a
m
ea
s{
0
,
1
}
).

F
ig
.2
6
.9

S
o
m
e
P
H
P
q
u
a
n
tifie
rs
.

34

26.3 String Processing and Regular


Expressions
C
h
a
r
a
c
te
rc
la
s
s D
e
s
c
r
ip
tio
n
a
l
n
u
m
a
l
p
h
a
d
i
g
i
t
s
p
a
c
e
l
o
w
e
r
u
p
p
e
r

A
lp
h
a
n
u
m
e
r
ic
c
h
a
r
a
c
te
r
s(
i.e
.,le
tte
r
s[
a
z
A
Z
]o
rd
ig
its[
0
9
]
)
.
W
o
r
d
c
h
a
r
a
c
te
r
s(
i.e
.,le
tte
r
s[
a
z
A
Z
]
)
.
D
ig
its
.
W
h
ite
s
p
a
c
e
.
L
o
w
e
r
c
a
s
e
le
tte
r
s
.
U
p
p
e
r
c
a
s
e
le
tte
r
s
.

F
ig
.2
6
.1
0 S
o
m
e
P
H
P
c
h
a
r
a
c
te
rc
la
s
s
e
s
.

35

26.4 Viewing Client/Server


Environment Variables

Environment variables

Provide information about execution environment

Type of Web browser


Type of server
Details of HTTP connection

Stored as array in PHP


$_ENV

36

26.4 Viewing Client/Server


Environment Variables
V
a
r
ia
b
le
n
a
m
e D
e
s
c
r
ip
tio
n
$
_
S
E
R
V
E
R
D
a
taa
b
o
u
tth
ec
u
r
r
e
n
tly
r
u
n
n
in
g
s
e
r
v
e
r
.
$
_
E
N
V
D
a
taa
b
o
u
tth
ec
lie
n
t
se
n
v
ir
o
n
m
e
n
t.
$
_
G
E
T
D
a
tap
o
s
te
d
to
th
es
e
r
v
e
rb
y
th
eg
e
t
m
e
th
o
d
.
$
_
P
O
S
T
D
a
tap
o
s
te
d
to
th
es
e
r
v
e
rb
y
th
ep
o
s
t
m
e
th
o
d
.
$
_
C
O
O
K
I
E
D
a
tac
o
n
ta
in
e
d
in
c
o
o
k
ie
so
n
th
ec
lie
n
t
sc
o
m
p
u
te
r
.
$
G
L
O
B
A
L
S
A
r
r
a
y
c
o
n
ta
in
in
g
a
llg
lo
b
a
lv
a
r
ia
b
le
s
.
F
ig
.2
6
.1
1 S
o
m
e
u
s
e
fu
lg
lo
b
a
la
r
r
a
y
s
.

37

1
2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4

<!-- Fig. 26.11: env.php

-->

<!-- Program to display environment variables -->

6
7
8
9
10

env.php
(1 of 1)

<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 bgcolor = \"#11bbff\">

20

<strong>$key</strong></td>
The foreach loop

21
22
23

?>

24

</table>

25

is used to print out the keys and


<td>$value</td></tr>"
); element in the $_ENV array.
values for each
PHP stores environment variables and their values in
the $_ENV array.

</body>

26 </html>

38

26.4 Viewing Client/Server


Environment Variables
Fig. 26.12

Displaying environment variables.

39

26.5 Form Processing and Business


Logic

Form processing
action property

Where to send form data

method property
post

Each element has unique name

40

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.13: form.html

-->

5 <!-- Form for use with the form.php program -->


6

form.html
(1 of 4)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<title>Sample form to take user input in XHTML</title>
</head>

11
12
13
14
15

<body>

The action attribute of the form element


indicates
that when the user clicks Register, the
<h1>This is a sample registration
form.</h1>
form
data
will be posted to form.php.
Please fill in all fields and
click
Register.

16
17

<!-- post form data to form.php -->

18

<form method = "post" action = "form.php">

19

<img src = "images/user.gif" alt = "User" /><br />

20

<span style = "color: blue">

21
22

Please fill out the fields below.<br />


</span>

23

41

24

<!-- create four text boxes for user input -->

25

<img src = "images/fname.gif" alt = "First Name" />

26

<input type = "text" name = "fname" /><br />

27
28
29

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
form.html
<img src = "images/lname.gif" alt = "Last Name" />
the Web server.
(2 of 4)
<input type = "text" name = "lname" /><br />

30
31

<img src = "images/email.gif" alt = "Email" />

32

<input type = "text" name = "email" /><br />

33
34

<img src = "images/phone.gif" alt = "Phone" />

35

<input type = "text" name = "phone" /><br />

36
37
38
39

<span style = "font-size: 10pt">


Must be in the form (555)555-5555</span>
<br /><br />

40
41
42

<img src = "images/downloads.gif"


alt = "Publications" /><br />

43
44
45
46

<span style = "color: blue">


Which book would you like information about?
</span><br />

47

42

48

<!-- create drop-down list containing book names -->

49

<select name = "book">

50

<option>Internet and WWW How to Program 3e</option>

51

<option>C++ How to Program 4e</option>

52

<option>Java How to Program 5e</option>

53

<option>XML How to Program 1e</option>

54

</select>

55

<br /><br />

form.html
(3 of 4)

56
57

<img src = "images/os.gif" alt = "Operating System" />

58

<br /><span style = "color: blue">

59
60

Which operating system are you currently using?


<br /></span>

61
62

<!-- create five radio buttons -->

63

<input type = "radio" name = "os" value = "Windows XP"

64

checked = "checked" />

65

Windows XP

66
67

<input type = "radio" name = "os" value =

68

"Windows 2000" />

69

Windows 2000

70
71

<input type = "radio" name = "os" value =

72

"Windows 98" />

73

Windows 98<br />

43

7
4
<
i
n
p
u
tt
y
p
e="
r
a
d
i
o
"n
a
m
e="
o
s
"v
a
l
u
e="
L
i
n
u
x
"/
>

7
5

L
i
n
u
x

7
6
7
7

<
i
n
p
u
tt
y
p
e="
r
a
d
i
o
"n
a
m
e="
o
s
"v
a
l
u
e="
O
t
h
e
r
"/
>

7
8

O
t
h
e
r
<
b
r/
>

7
9

form.html
(4 of 4)

8
0
<
!
-c
r
e
a
t
eas
u
b
m
i
tb
u
t
t
o
n>

8
1

<
i
n
p
u
tt
y
p
e="
s
u
b
m
i
t
"v
a
l
u
e="
R
e
g
i
s
t
e
r
"/
>

8
2
8
3

<
/
f
o
r
m
>

8
4
8
5

<
/
b
o
d
y
>

8
6<
/
h
t
m
l
>

44

26.5 Form Processing and Business


Logic
Fig. 26.13

XHTML form for gathering user input.

45

26.5 Form Processing and Business


Logic

Business logic

Confirm that valid information was entered


extract function

Regular expressions very helpful


Do checks on client side where possible

Creates variables corresponding to each key-value pair


in array
Easily retrieve all values sent to PHP page

JavaScript
Conserves server resources

Ending a script
die function

Remember to close all HTML tags

46

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.14: form.php

-->

5 <!-- Read information sent from form.html -->


6

form.php
(1 of 4)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<title>Form Validation</title>
</head>

11
12
13
14
15
16

<body style = "font-family: arial,sans-serif">

Function ereg is called to determine whether the


The parentheses in the expression must be
phone number entered by the user is valid.
<?php
followed by The
threeexpression
digits ([0-9]{3}
), a closing
\( matches the opening
extract( $_POST )parenthesis,
;
three digits, of
a literal
hyphen
and
parentheses
a phone
number.
four additional digits.

17

// determine whether phone number is valid and print

18

// an error message if not

19

if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$",

20
21

$phone ) ){

We access the phone fields value from


form.html by using variable $phone.

47

print( "<p><span style = \"color: red;

22
23

font-size: 2em\">

24

INVALID PHONE NUMBER</span><br />

25

A valid phone number must be in the form

26

<strong>(555)555-5555</strong><br />

27

<span style = \"color: blue\">

28

Click the Back button, enter a valid phone

29

number and resubmit.<br /><br />

30

Thank You.</span></p></body></html>" );

form.php
(2 of 4)

Function die terminates script execution

31
die(); // terminate script execution

32
}

33
34

?>

35
36
37
38
39
40

<p>Hi
<span style = "color: blue">
<strong>
<?php print( "$fname" ); ?>
</strong>

41

</span>.

42

Thank you for completing the survey.<br />

43

48

44

You have been added to the

45

<span style = "color: blue">


<strong>

46

<?php print( "$book " ); ?>

47

</strong>

48
49

</span>

50

mailing list.

51

</p>

52

<strong>The following information has been saved

53

form.php
(3 of 4)

in our database:</strong><br />

54
55
56

<table border = "0" cellpadding = "0" cellspacing = "10">


<tr>

57

<td bgcolor = "#ffffaa">Name </td>

58

<td bgcolor = "#ffffbb">Email</td>

59

<td bgcolor = "#ffffcc">Phone</td>

60

<td bgcolor = "#ffffdd">OS</td>

61

</tr>

62
63
64

<tr>
<?php

65

49

66

// print each form fields value

67

print( "<td>$fname $lname</td>

68

<td>$email</td>

69

<td>$phone</td>

70

<td>$os</td>" );

71

?>

72

</tr>

73

</table>

form.php
(4 of 4)

74
75

<br /><br /><br />

76

<div style = "font-size: 10pt; text-align: center">

77

This is only a sample form.

78

You have not been added to a mailing list.

79
80

</div>
</body>

81 </html>

50

26.5 Form Processing and Business


Logic
Fig. 26.14

Obtaining user input through forms.

51

26.6 Verifying a Username and


Password

Private website

Only accessible to certain individuals


Encrypt username and password data when sending,
storing and retrieving for increased security

Implementing password checking

Login information stored in file


function
Read, write, append modes

fopen

Store data using fputs


\n

newline character

Close files when done


fclose

function

52

26.6 Verifying a Username and


Password

Implementing password checking, cont.

Trim newline character


chop

function

Split string into substrings given a certain delimiter


split

function

If username/password match list, allow access

53

1
2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4

<!-- Fig. 26.15: password.html

-->

<!-- XHTML form sent to password.php for verification -->

6
7
8
9

password.html
(1 of 4)

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Verifying a username and a password.</title>

10
11
12
13
14

<style type = "text/css">


td { background-color: #DDDDDD }
</style>
</head>

15
16

<body style = "font-family: arial">

17

<p style = "font-size: 13pt">

18

Type in your username and password below.

19

<br />

20

<span style = "color: #0000FF; font-size: 10pt;

21

font-weight: bold">

22

Note that password will be sent as plain text

23
24

</span>
</p>

25

54

26

<!-- post form data to password.php -->

27

<form action = "password.php" method = "post">

28

<br />

Form data is posted to password.php.

29
30

<table border = "0" cellspacing = "0"

31

style = "height: 90px; width: 123px;

32

font-size: 10pt" cellpadding = "0">

password.html
(2 of 4)

33
34
35

<tr>
<td colspan = "3">
<strong>Username:</strong>

36
37
38

</td>
</tr>

39
40
41

<tr>
<td colspan = "3">
<input size = "40" name = "USERNAME"

42

style = "height: 22px; width: 115px" />

43
44
45

</td>
</tr>

46

55

47
48

<tr>
<td colspan = "3">
<strong>Password:</strong>

49
50
51

</td>

password.html
(3 of 4)

</tr>

52
53
54

<tr>
<td colspan = "3">
<input size = "40" name = "PASSWORD"

55
56

style = "height: 22px; width: 115px"

57

type = "password" />

58
59

<br/></td>
</tr>

60
61
62
63

<tr>
<td colspan = "1">
<input type = "submit" name = "Enter"

64

value = "Enter" style = "height: 23px;

65

width: 47px" />

66

</td>

67

<td colspan = "2">

68

<input type = "submit" name = "NewUser"

69

value = "New User"

70

style = "height: 23px" />

71

</td>

56

7
2

<
/
t
r
>

7
3

<
/
t
a
b
l
e
>

7
4
7
5

<
/
f
o
r
m
>
<
/
b
o
d
y
>

7
6
<
/
h
t
m
l
>

password.html
(4 of 4)

57

26.6 Verifying a Username and


Password
Fig. 26.15

XHTML form for obtaining a username and password.

58

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.16: password.php

-->

5 <!-- Searching a database for usernames and passwords. -->


6

password.php
(1 of 7)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<?php
extract( $_POST );

11

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.

12

// check if user has left USERNAME or PASSWORD field blank

13

if ( !$USERNAME || !$PASSWORD ) {

14

fieldsBlank();

15

die();

16

Function fieldsBlank is called if the user has


submittedisset
an incomplete
formthe
to notify
the user
Function
tests whether
user has
that all form
fields
must
be completed.
pressed
the New
User
button,
indicating that a
new user must be added.

17
18

// check if the New User button wasTo


clicked
add a new

19

if ( isset( $NewUser ) ) {

20

user, we open the file


password.txt in append mode and assign the
file handle that is returned to variable $file.

21

// open password.txt for writing using append mode

22

if ( !( $file = fopen( "password.txt",

23

"a" ) ) ) {

24

59

25

// print error message and terminate script

26

// execution if file cannot be opened

27

print( "<title>Error</title></head><body>

28

Could not open password file

29

</body></html>" );
die();

30
}

31

password.php
Print an error message and terminate script
(2 ofexecution
7)
if the file cannot be opened.

32
33

// write username and password to file and

34

// call function userAdded

35

fputs( $file, "$USERNAME,$PASSWORD\n" );

36

userAdded( $USERNAME );

37

38

else {

39

Function userAdded is called to print a message to the


Function fputs writes the name and password to the
user to indicate that the username and password were
text file..
added
to theadded,
file. open file
is
not being

40

// if a new user

41

// for reading

42

if ( !( $file = fopen( "password.txt",

43

"r" ) ) ) {

44

print( "<title>Error</title></head>

45

<body>Could not open password file

46

</body></html>" );
die();

47
48

49

60

50

$userVerified = 0;

51
52

// read each line in file


and check
username
Before
entering
the while

53

// and password

54

while ( !feof(

loop, variable
Function$userVerified
fgets reads a line
from
is set
to 0the
. text file.
$file
) && !$userVerified
) {
The result
is assigned to variable
$line.

55
56
57
58
59
60
61
62
63

password.php
(3 of 7)

// read line from file

The while loop executes as long


as the
are more
removes
thethere
newline
character
lines in the filefrom
to read
and of
variable
$userVerified is
the end
the line.
Function
split is called to separate the string at the
still
0 or empty.
// remove newline character from end of line
specified delimiter (in this case, a comma). The
$line = chop( $line );
The username
by the user
resulting array
is stored inentered
array $field
. is tested
against the one returned in the text file (stored
// split username and password
in the first element of the array). If they match,
$field = split( ",", $line, 2 );
variable $userVerified is set to 1.
chop
$line = fgets( Function
$file, 255
);

64
65

// verify username

66

if ( $USERNAME == $field[ 0 ] ) {

67

$userVerified = 1;

68

checkPassword returns true, function


accessGranted is called to notify the client that

69

function
// call function checkPassword to If
verify

70

// users password

71

permission
if ( checkPassword( $PASSWORD, $field
)

has been granted. Otherwise, function


wrongPassword is called.

72

== true )

73

accessGranted( $USERNAME );

74
75

else
wrongPassword();

Function checkPassword is called to verify the


users password. Variable $PASSWORD and array
$field are passed to the function.

61

76
77

78

81

If variable $userVerified has not been set to a


while loop
has executed,
value
otherAfter
than 0the
, function
accessDenied
is function
// close text fi
le
fclose
is called
close the
called to notify
the client
thattoaccess
has file.
been
password.php
fclose( $file );
denied.
(4 of 7)

82

// call function accessDenied if username has

83

// not been verified

84

if ( !$userVerified )

85

accessDenied();

79
80

86

87
88

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.

// verify user password and return a boolean

89

function checkPassword( $userpassword, $filedata )

90

{
if ( $userpassword == $filedata[ 1 ] )

91

return true;

92

else

93

return false;

94
95

96

62

97

// print a message indicating the user has been added

98

function userAdded( $name )

99

{
print( "<title>Thank You</title></head>

100
101

<body style = \"font-family:


arial;
Function userAdded

102

font-size: 1em;

103

<strong>You have been added

104

to the user list, $name.

105

<br />Enjoy the

106

prints a message to the


color:
blue\">
client
indicating that the user has been added.

password.php
(5 of 7)

Function accessGranted prints a


site.</strong>"message
);
to the client indicating that
permission has been granted.

107
108

// print a message indicating permission

109

// has been granted

110

function accessGranted( $name )

111

{
print( "<title>Thank You</title></head>

112
113

<body style = \"font-family: arial;

114

font-size: 1em; color: blue\">

115

<strong>Permission has been

116

granted, $name. <br />

117

Enjoy the site.</strong>" );

118

119

63

120

// print a message indicating password is invalid

121

function wrongPassword()

122

125

Function wrongPassword prints a message to the


client indicating that the password is invalid.
password.php
<body style = \"font-family: arial;
(6 of 7)
font-size: 1em; color: red\">

126

<strong>You entered an invalid

127

password.<br />Access has

128

been denied.</strong>" );

print( "<title>Access Denied</title></head>

123
124

129

130
131

// print a message indicating access has been denied

132

function accessDenied()

133

{
print( "<title>Access Denied</title></head>

134
135

<body style = \"font-family: arial;

136

font-size: 1em; color: red\">

137

<strong>

138

You were denied access to this server.

139

<br /></strong>" );

140

Function accessDenied prints a message to the


client indicating that access has been denied.

141

64

1
4
2

/
/p
r
i
n
t am
e
s
s
a
g
ei
n
d
i
c
a
t
i
n
gt
h
a
tf
i
e
l
d
s

1
4
3

/
/h
a
v
eb
e
e
nl
e
f
tb
l
a
n
k

Function fieldsBlank prints a message to the


client indicating that all form fields have not been
completed.
p
r
i
n
t
("
<
t
i
t
l
e
>
A
c
c
e
s
sD
e
n
i
e
d
<
/
t
i
t
l
e
>
<
/
h
e
a
d
>
password.php
<
b
o
d
ys
t
y
l
e= \
"
f
o
n
t
f
a
m
i
l
y
:a
r
i
a
l
;
(7 of 7)

1
4
4

f
u
n
c
t
i
o
nf
i
e
l
d
s
B
l
a
n
k
(
)

1
4
5

1
4
6
1
4
7
1
4
8

f
o
n
t
s
i
z
e
:1
e
m
;c
o
l
o
r
:r
e
d
\
"
>

1
4
9

<
s
t
r
o
n
g
>

1
5
0

P
l
e
a
s
ef
i
l
li
na
l
lf
o
r
mf
i
e
l
d
s
.

1
5
1

<
b
r/
>
<
/
s
t
r
o
n
g
>
")
;
}

1
5
2
1
5
3
1
5
4

?
>
<
/
b
o
d
y
>

1
5
5<
/
h
t
m
l
>

65

26.6 Verifying a Username and


Password
Fig. 26.16

Verifying a username and password.

66

1a
c
c
o
u
n
t
1
,
p
a
s
s
w
o
r
d
1
2a
c
c
o
u
n
t
2
,
p
a
s
s
w
o
r
d
2
3a
c
c
o
u
n
t
3
,
p
a
s
s
w
o
r
d
3
4a
c
c
o
u
n
t
4
,
p
a
s
s
w
o
r
d
4
5a
c
c
o
u
n
t
5
,
p
a
s
s
w
o
r
d
5
6a
c
c
o
u
n
t
6
,
p
a
s
s
w
o
r
d
6

password.txt
(1 of 1)

7a
c
c
o
u
n
t
7
,
p
a
s
s
w
o
r
d
7
8a
c
c
o
u
n
t
8
,
p
a
s
s
w
o
r
d
8
9a
c
c
o
u
n
t
9
,
p
a
s
s
w
o
r
d
9
1
0a
c
c
o
u
n
t
1
0
,
p
a
s
s
w
o
r
d
1
0

67

26.7 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

68

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.18: data.html

-->

data.html
(1 of 2)

5 <!-- Querying a MySQL Database -->


6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10

<head>
<title>Sample Database Query</title>
</head>

11
12
13
14
15

<body style = "background-color: #F0E68C">


<h2 style = "font-family: arial color: blue">
Querying a MySQL database.
</h2>

16
17
18

<form method = "post" action = "database.php">


<p>Select a field to display:

19
20

<!-- add a select box containing options -->

21

<!-- for SELECT query

-->

69

<
s
e
l
e
c
tn
a
m
e= "
s
e
l
e
c
t
"
>

22
23

<
o
p
t
i
o
ns
e
l
e
c
t
e
d= "
s
e
l
e
c
t
e
d
"
>
*
<
/
o
p
t
i
o
n
>

24

<
o
p
t
i
o
n
>
I
D
<
/
o
p
t
i
o
n
>

25

<
o
p
t
i
o
n
>
T
i
t
l
e
<
/
o
p
t
i
o
n
>

26

<
o
p
t
i
o
n
>
C
a
t
e
g
o
r
y
<
/
o
p
t
i
o
n
>

27

<
o
p
t
i
o
n
>
I
S
B
N
<
/
o
p
t
i
o
n
>

Select box containing options for a SELECT


data.html
query.
(2 of 2)

<
/
s
e
l
e
c
t
>

28

<
/
p
>

29
30

<
i
n
p
u
tt
y
p
e="
s
u
b
m
i
t
"v
a
l
u
e="
S
e
n
dQ
u
e
r
y
"

31
32

s
t
y
l
e= "
b
a
c
k
g
r
o
u
n
d
c
o
l
o
r
:b
l
u
e
;

33

c
o
l
o
r
:y
e
l
l
o
w
;f
o
n
t
w
e
i
g
h
t
:b
o
l
d
"/
>

34
35

<
/
f
o
r
m
>
<
/
b
o
d
y
>

36 <
/
h
t
m
l
>

70

26.7 Connecting to a Database


Fig. 26.18

Form to query a MySQL database.

71

26.7 Connecting to a Database

Interacting with databases

SQL

Structured Query Language


Used to manipulate databases

Several useful functions

mysql_connect
mysql_select_db
mysql_query
mysql_error
mysql_fetch_row
mysql_close
72

1
2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4

<!-- Fig. 26.19: database.php

-->

<!-- Program to query a database and -->

<!-- send results to the client.

database.php
(1 of 3)

-->

7
8
9
10
11

<html xmlns = "http://www.w3.org/1999/xhtml">


<head>
<title>Search Results</title>
</head>

12
13

<body style = "font-family: arial, sans-serif"

14

style = "background-color: #F0E68C">

15

<?php

16
17

Build the select query and assign the


string to variable $query.

extract( $_POST );

18
19

// build SELECT query

20

$query = "SELECT " . $select . "

Function mysql_connect returns a database


handle which represents PHPs connection to a
database. If this connection is not made, function
FROM
dieBooks";
is called to terminate script execution.

21
22

// Connect to MySQL

23

if ( !( $database = mysql_connect( "localhost",

24

"httpd", "" ) ) )

25

die( "Could not connect to database" );

73

26
27

// open Products database

28

Function)mysql_query
if ( !mysql_select_db( "Products", $database
)

29
30
31

//

32

if

33

die( mysql_error() );

34
}

35
36

returns an object
die( "Could not open Products database"
); the result set of the query, which
containing
we assign to variable $result.
database.php
query Products database
(2 of 3)
( !( $result
= mysql_query(
$query, $database
) ) { the
Function
mysql_select_db
is called to) specify
print( "Could not execute query! <br />" );
database to be queried.

?>

37
38

<h3 style = "color: blue">

39

Search Results</h3>

40
41
42

<table border = "1" cellpadding = "3" cellspacing = "2"


style = "background-color: #ADD8E6">

43
44
45
46
47
48
49
50

The for loop iterates through each


record in the result set while
// fetch each record in result setconstructing an XHTML table from
for ( $counter = 0;
the results. Variable $counter is
$row = mysql_fetch_row( $resultincremented
);
by one for each row
Function mysql_fetch_row returns an
$counter++ ){
retrieved.
array containing the elements of each
row in the result set of our query
74
($result).

<?php

51

// build table to display results

52

print( "<tr>" );

53
foreach ( $row as $key => $value )

54

database.php
(3 of 3)
print( "</tr>" );
The foreach loop iterates through the
}
array containing the elements of each row
and prints out each element in an
mysql_close( $databaseThe
); total number of results are printed to the
individual table cell.
client.
print( "<td>$value</td>" );

55
56
57
58
59
60
?>

61
62
63

</table>

64
65

<br />Your search yielded <strong>

66

<?php print( "$counter" ) ?> results.<br /><br /></strong>

67
68

<h5>Please email comments to


<a href = "mailto:deitel@deitel.com">

69

Deitel and Associates, Inc.

70

</a>

71
72

</h5>

73
74

</body>

75 </html>

75

26.7 Connecting to a Database


Fig. 26.19

Querying a database and displaying the results.

76

26.8 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

Cookies and PHP


setcookie function

Name
Value
Expiration date

77

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.20: cookies.html -->
5 <!-- Writing a Cookie

-->

cookies.html
(1 of 2)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9
10

<head>
<title>Writing a cookie to the client computer</title>
</head>

11
12
13

<body style = "font-family: arial, sans-serif;


background-color: #99CCFF">

14
15

<h2>Click Write Cookie to save your cookie data.</h2>

16

78

17

<form method = "post" action = "cookies.php"


style = "font-size: 10pt">

18
19

<strong>Name:</strong><br />

20

<input type = "text" name = "NAME" /><br />

Form data is posted to cookies.php.

21
22

<strong>Height:</strong><br />

23

<input type = "text" name = "HEIGHT" /><br />

cookies.html
(2 of 2)

24
25

<strong>Favorite Color:</strong><br />

26

<input type = "text" name = "COLOR" /><br />

27
<input type = "submit" value = "Write Cookie"

28
29

style = "background-color: #F0E86C; color: navy;

30

font-weight: bold" /></p>

31
32

</form>
</body>

33 </html>

79

26.8 Cookies
Fig. 26.20

Gathering data to be written as a cookie.

80

1 <?php
2

// Fig. 26.21: cookies.php

// Program to write a cookie to a client's machine

4
5

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 );

10

setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );

cookies.php
(1 of 2)

Function setcookie takes the name of the


cookie to be set as the first argument,
followed by the value to be stored in the
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
cookie. The optional third argument specifies
the expiration date of the cookie.

11 ?>
12
13
14
15

16 <html xmlns = "http://www.w3.org/1999/xhtml">


17
18
19

<head>
<title>Cookie Saved</title>
</head>

20
21
22

<body style = "font-family: arial, sans-serif">


<p>The cookie has been set with the following data:</p>

23

81

24

<
!
-p
r
i
n
te
a
c
hf
o
r
mf
i
e
l
d

sv
a
l
u
e>

25

<
b
r/
>
<
s
p
a
ns
t
y
l
e="
c
o
l
o
r
:b
l
u
e
"
>
N
a
m
e
:
<
/
s
p
a
n
>
Each
<
?
p
h
pp
r
i
n
t
($
N
A
M
E)?
>
<
b
r/
>

26
27
28

<
s
p
a
ns
t
y
l
e= "
c
o
l
o
r
:b
l
u
e
"
>
H
e
i
g
h
t
:
<
/
s
p
a
n
>
<
?
p
h
pp
r
i
n
t
($
H
E
I
G
H
T)?
>
<
b
r/
>

29

form fields value is printed to


confirm the data that has been set as a
cookie with the user.
cookies.php
(2 of 2)

30
31

<
s
p
a
ns
t
y
l
e= "
c
o
l
o
r
:b
l
u
e
"
>
F
a
v
o
r
i
t
eC
o
l
o
r
:
<
/
s
p
a
n
>

32
33

<
s
p
a
ns
t
y
l
e= "
c
o
l
o
r
:<
?
p
h
pp
r
i
n
t
("
$
C
O
L
O
R
\
"
>
$
C
O
L
O
R
")?
>

34

<
/
s
p
a
n
>
<
b
r/
>

35

<
p
>
C
l
i
c
k<
ah
r
e
f="
r
e
a
d
C
o
o
k
i
e
s
.
p
h
p
"
>
h
e
r
e
<
/
a
>
t
or
e
a
dt
h
es
a
v
e
dc
o
o
k
i
e
.<
/
p
>

36
37

<
/
b
o
d
y
>

38 <
/
h
t
m
l
>

Hyperlink to readCookies.php.

82

26.8 Cookies
Fig. 26.21 Writing a cookie to the client.

83

26.8 Cookies

Reading cookies
$_COOKIE environment

Array

foreach loop

variable

to access each element

Split into key and value

84

26.8 Cookies

Cookie storage

Internet Explorer

Stores cookies in Cookies directory


Text file

85

26.8 Cookies
Fig. 26.22 Cookies directory before a cookie is written.

Fig. 26.23 Cookies directory after a cookie is written.

86

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.24: readCookies.php

-->

5 <!-- Program to read cookies from the client's computer -->


6

readCookies.php
(1 of 2)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8

<head><title>Read Cookies</title></head>

9
10

<body style = "font-family: arial, sans-serif">

11
12
13

<p>
<strong>

14

The following data is saved in a cookie on your

15

computer.

16
17

</strong>
</p>

18

87

19

<
t
a
b
l
eb
o
r
d
e
r="
5
"c
e
l
l
s
p
a
c
i
n
g="
0
"c
e
l
l
p
a
d
d
i
n
g="
1
0
"
>
<
?
p
h
p

20

The foreach
loop
iterates
through
the $_COOKIE
PHP
creates
array
$_COOKIE
which contains all
array and prints
thevalues
name indexed
and valuebyoftheir
eachnames.
cookie
cookie
/
/i
t
e
r
a
t
et
h
r
o
u
g
ha
r
r
a
y$
_
C
O
O
K
I
Ea
n
dp
r
i
n
t
in an XHTML table.
readCookies.php
/
/n
a
m
ea
n
dv
a
l
u
eo
fe
a
c
hc
o
o
k
i
e
(2 of 2)
f
o
r
e
a
c
h($
_
C
O
O
K
I
Ea
s$
k
e
y=
>$
v
a
l
u
e)

21
22
23
24

p
r
i
n
t( "
<
t
r
>

25
26

<
t
db
g
c
o
l
o
r
=\
"
#
F
0
E
6
8
C
\
"
>
$
k
e
y
<
/
t
d
>

27

<
t
db
g
c
o
l
o
r
=\
"
#
F
F
A
5
0
0
\
"
>
$
v
a
l
u
e
<
/
t
d
>

28

<
/
t
r
>
")
;
?
>

29
30
31
32

<
/
t
a
b
l
e
>
<
/
b
o
d
y
>

33 <
/
h
t
m
l
>

88

26.8 Cookies
Fig. 26.24 Displaying the cookies content.

89

26.9 Dynamic Content in PHP

Dynamically alter XHTML content

Forms action property set to same page that


contains it
Perform different actions when page is loaded and
form is submitted
isset

variable

Check for errors

Write different XHTML when errors encountered

$$variable syntax

References variable whose name equals the value of


$variable

If input is valid, make MySQL database calls

90

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.25: dynamicForm.php

-->

5 <!-- Form for use with the form.php program -->


6

dynamicForm.php
(1 of 9)

7 <html xmlns = "http://www.w3.org/1999/xhtml">


8
9

<head>
<title>Sample form to take user input in XHTML</title>

10 </head>
11
12 <body>
13

<?php

14

extract ( $_POST );

15

$iserror = false;

Build array of options for the form.

16
17

// array of book titles

18

$booklist = array( "Internet and WWW How to Program 3e",

19

"C++ How to Program 4e",

20

"Java How to Program 5e",

21

"XML How to Program 1e" );

22

91

23

// array of possible operating systems

24

$systemlist = array( "Windows XP",

25

"Windows 2000",

26

"Windows 98",

27

"Linux",

28

"Other");

dynamicForm.php
(2 of 9)

29
30

// array of name and alt values for the text input fields

31

$inputlist = array( "fname" => "First Name",

32

"lname" => "Last Name",

33

"email" => "Email",

34

"phone" =>

35

If the page is being loaded as a result of a form


submission,
do error
checking and
then field
retrieve
Check for errors
or omissions
in form
"Phone" );
information
from the database.
input.

36

if ( isset ( $submit ) ) {

37

if ( $fname == "" ) {

38

$formerrors[ "fnameerror" ] = true;

39

$iserror = true;

40

41
42

if ( $lname == "" ) {

43

$formerrors[ "lnameerror" ] = true;

44

$iserror = true;

45

46

92

47

if ( $email == "" ) {

48

$formerrors[ "emailerror" ] = true;

49

$iserror = true;

50

51
52

if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) {

53

$formerrors[ "phoneerror" ] = true;

54

$iserror = true;

55

56
57
58

dynamicForm.php
(3 of 9)

if ( !$iserror ) {

If there were no errors, query the MySQL


database.

59

// build INSERT query

60

$query = "INSERT INTO contacts " .

61

"( LastName, FirstName, Email, Phone, Book, OS ) " .

62

"VALUES ( '$lname', '$fname', '$email', " .

63

"'" . quotemeta( $phone ) . "', '$book', '$os' )";

64
65

// Connect to MySQL

66

if ( !( $database = mysql_connect( "localhost",

67

"httpd", "" ) ) )

68

die( "Could not connect to database" );

69
70

// open MailingList database

71

if ( !mysql_select_db( "MailingList", $database ) )

72

die( "Could not open MailingList database" );

93

73
74

// execute query in MailingList database

75

if ( !( $result = mysql_query( $query, $database ) ) ) {

76

print( "Could not execute query! <br />" );

77

die( mysql_error() );

78

dynamicForm.php
(4 of 9)

79
80

print( "<p>Hi

81

<span style = 'color: blue'>

82

<strong>$fname</strong></span>.

83

Thank you for completing the survey.<br />

84
85

You have been added to the

86

<span style = 'color: blue'>

87

<strong>$book</strong></span>

88

mailing list.

89

</p>

90

<strong>The following information has been saved

91

in our database:</strong><br />

92
93

<table border = '0' cellpadding = '0' cellspacing = '10'>

94

<tr>

95

<td bgcolor = '#ffffaa'>Name</td>

96

<td bgcolor = '#ffffbb'>Email</td>

97

<td bgcolor = '#ffffcc'>Phone</td>

94

98

<td bgcolor = '#ffffdd'>OS</td>

99

</tr>

100

<tr>

101
102

<!-- print each form fields value -->

103

<td>$fname $lname</td>

104

<td>$email</td>

105

<td>$phone</td>

106

<td>$os</td>

107

</tr></table>

dynamicForm.php
(5 of 9)

108
109

<br /><br /><br />

110

<div style = 'font-size: 10pt; text-align: center'>

111

<div style = 'font-size : 18pt'>

112

<a href = 'formDatabase.php'>

113

Click here to view entire database.</a></div>

114

This is only a sample form.

115

You have not been added to a mailing list.

116

</div></body></html>" );

Halt the script so the form-generation code


does not execute.

die();

117
}

118
119

120
121

print( "<h1>This is a sample registration form.</h1>

122

Please fill in all fields and click Register." );

95

123
124

if ( $iserror ) {
print( "<br /><span style = 'color : red'>

125

Fields with * need to be filled in properly.</span>" );

126
127

dynamicForm.php
(6 of 9)

128
129

print( "<!-- post form data to form.php -->

130

<form method = 'post' action = 'dynamicform.php'>

131

<img src = 'images/user.gif' alt = 'User' /><br />

132

<span style = 'color: blue'>

133

Please fill out the fields below.<br />

134

</span>

135
<!-- create four text boxes for user input -->" );

136
137

Fill in the forms using $$variable syntax.

foreach ( $inputlist as $inputname => $inputalt ) {


$inputtext = $inputvalues[ $inputname ];

138
139

print( "<img src = 'images/$inputname.gif'

140

If the form input contained errors, place a red


asterisk (*) next to the text field.

141

alt = '$inputalt' /><input type = 'text'

142

name = '$inputname' value = '" . $$inputname . "' />" );

143
if ( $formerrors[ ( $inputname )."error" ] == true )

144

print( "<span style = 'color : red'>*</span>" );

145
146

print( "<br />" );

147
148

96

149
150

print( "<span style = 'font-size : 10pt" );

151
152
153

if ( $formerrors[ "phoneerror" ] )
print( "; color : red" );

154
155
156

dynamicForm.php
(7 of 9)

print( "'>Must be in the form (555)555-5555


</span><br /><br />

157
158

<img src = 'images/downloads.gif'

159

alt = 'Publications' /><br />

160
161

<span style = 'color: blue'>

162

Which book would you like information about?

163

</span><br />

164
165

<!-- create drop-down list containing book names -->

166

<select name = 'book'>" );

167
168
169

Make sure the correct book is selected in the


dropdown box.

foreach ( $booklist as $currbook ) {


print( "<option" );

170
171
172

if ( ( $currbook == $book ) )
print( " selected = 'true'" );

173

97

print( ">$currbook</option>" );

174
175

176
177

print( "</select><br /><br />

178

<img src = 'images/os.gif' alt = 'Operating System' />

179

<br /><span style = 'color: blue'>

180

Which operating system are you currently using?

181

<br /></span>

dynamicForm.php
(8 of 9)

182
<!-- create five radio buttons -->" );

183
184
185

$counter = 0;

186
187

foreach ( $systemlist as $currsystem ) {

Make sure the correct OS is checked in the


checkbox.
'$currsystem'" );

print( "<input type = 'radio' name = 'os'

188

value =

189
190
191

if ( $currsystem == $os ) print( "checked = 'checked'" );

192

if ( $iserror && $counter == 0 ) print( "checked = 'checked'" );

193
print( " />$currsystem" );

194
195
196

if ( $counter == 2 ) print( "<br />" );

197

$counter++;

198
199

98

2
0
0

p
r
i
n
t
(
"
<
!
c
r
e
a
t
e
a
s
u
b
m
i
t
b
u
t
t
o
n
>

2
0
1

<
b
r
/
>

2
0
2

<
i
n
p
u
t
t
y
p
e
=
'
s
u
b
m
i
t
'
n
a
m
e
=
'
s
u
b
m
i
t
'
v
a
l
u
e
=
'
R
e
g
i
s
t
e
r
'
/
>

2
0
3

<
/
f
o
r
m
>
<
/
b
o
d
y
>
<
/
h
t
m
l
>
"
)
;

2
0
4 ?
>

dynamicForm.php
(9 of 9)

99

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

100

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

101

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3
4 <!-- Fig. 26.26: formDatabase.php

-->

5 <!-- Program to query a database and -->


6 <!-- send results to the client.

-->

formDatabase.php
(1 of 3)

7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10
11

<head>
<title>Search Results</title>
</head>

12
13

<body style = "font-family: arial, sans-serif"

14

style = "background-color: #F0E68C">

15

<?php

16
17

Build the query string.


extract( $_POST );

18
19

// build SELECT query

20

$query = "SELECT * FROM contacts";

21
22

// Connect to MySQL

23

if ( !( $database = mysql_connect( "localhost",

24

"httpd", "" ) ) )

25

die( "Could not connect to database" );

102

26
27

// open MailingList database

28

if ( !mysql_select_db( "MailingList", $database ) )

29

die( "Could not open MailingList database" );

30
31

// query MailingList database

32

if ( !( $result = mysql_query( $query, $database ) ) ) {

33

print( "Could not execute query! <br />" );

34

die( mysql_error() );
}

35
36

formDatabase.php
(2 of 3)

?>

37
38

<h3 style = "color: blue">

39

Mailing List Contacts</h3>

40
41
42

<table border = "1" cellpadding = "3" cellspacing = "2"


style = "background-color: #ADD8E6">

43
44

<tr>

45

<td>ID</td>

46

<td>Last Name</td>

47

<td>First Name</td>

48

<td>E-mail Address</td>

49

<td>Phone Number</td>

50

<td>Book</td>

103

<td>Operating System</td>

51
52

</tr>

53

<?php

54
55

// fetch each record in

56

for ( $counter = 0;

Retrieve each mailing list


member record from the
resultdatabase.
set

57

$row = mysql_fetch_row( $result );

58

$counter++ ){

59
60

// build table to

61

print( "<tr>" );

formDatabase.php
(3 of 3)

Dynamically create a table


display
resultseach mailing list
containing
member.

62
63

foreach ( $row as $key => $value )

64

print( "<td>$value</td>" );

65
print( "</tr>" );

66
}

67
68

mysql_close( $database );

69
?>

70
71
72

</table>

73
74

</body>

75 </html>

104

26.9 Dynamic Content in PHP


Fig. 26.26 Displaying the MailingList database.

105

26.10 Operator Precedence


Operator
new
[]
~
!
++
-@
*
/
%
+
.
<<
>>
<
>
<=
>=
==
!=
===
!==
Fig. 26.27

Type

Associativity

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

none
right to left
right to left

left to right

left to right

left to right
none

none

PHP operator precedence and associativity.

106

26.10 Operator Precedence


Operator
&
^
|
&&
||
=
+=
-=
*=
/=
&=
|=
^=
.=
<<=
>>=
and
xor
or
,
Fig. 26.27

Type

Associativity

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

left to right
left to right
left to right
left to right

PHP operator precedence and associativity.


107

You might also like