SlideShare a Scribd company logo
© 2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 26 - PHP
Outline
26.1 Introduction
26.2 PHP
26.3 String Processing and Regular Expressions
26.4 Viewing Client/Server Environment Variables
26.5 Form Processing and Business Logic
26.6 Verifying a Username and Password
26.7 Connecting to a Database
26.8 Cookies
26.9 Dynamic Content in PHP
26.10 Operator Precedence
26.11 Web Resources
© 2003 Prentice Hall, Inc. All rights reserved.
2
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.
© 2003 Prentice Hall, Inc. All rights reserved.
3
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
© 2003 Prentice Hall, Inc. All rights reserved.
4
26.2 PHP
• Basic application
– Scripting delimiters
• <? php ?>
• Must enclose all script code
– Variables preceded by $ symbol
• Case-sensitive
– End statements with semicolon
– Comments
• // for single line
• /* */ for multiline
– Filenames end with .php by convention
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
5
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4 <!-- Fig. 26.1: first.php -->
5 <!-- Our first PHP script -->
6
7 <?php
8 $name = "LunaTic"; // declaration
9 ?>
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12 <head>
13 <title>A simple PHP document</title>
14 </head>
15
16 <body style = "font-size: 2em">
17 <p>
18 <strong>
19
20 <!-- print variable name’s value -->
21 Welcome to PHP, <?php print( "$name" ); ?>!
22 </strong>
23 </p>
24 </body>
25 </html>
first.php
(1 of 1)
Declare variable $name
Scripting delimiters
Single-line comment
Function print outputs the value of variable
$name
© 2003 Prentice Hall, Inc. All rights reserved.
6
26.2 PHP
Fig. 26.1 Simple PHP program.
© 2003 Prentice Hall, Inc. All rights reserved.
7
26.2 PHP
• Variables
– Can have different types at different times
– Variable names inside strings replaced by their value
– Type conversions
• settype function
• Type casting
– Concatenation operator
• . (period)
• Combine strings
© 2003 Prentice Hall, Inc. All rights reserved.
8
26.2 PHP
Data type Description
int, integer Whole numbers (i.e., numbers without a decimal point).
float, double Real numbers (i.e., numbers containing a decimal point).
string Text enclosed in either single ('') or double ("") quotes.
bool, Boolean True or false.
array Group of elements of the same type.
object Group of associated data and methods.
Resource An external data source.
NULL No value.
Fig. 26.2PHP data types.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
9
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 -->
5 <!-- Demonstration of PHP data types -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>PHP data types</title>
10 </head>
11
12 <body>
13
14 <?php
15
16 // declare a string, double and integer
17 $testString = "3.5 seconds";
18 $testDouble = 79.2;
19 $testInteger = 12;
20 ?>
21
data.php
(1 of 3)
Assign a string to variable
$testString
Assign a double to variable
$testDoubleAssign an integer to variable
$testInteger
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
10
22 <!-- print each variable’s 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 />
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 print( "Converting back to a string results in
41 $testString <br /><br />" );
42
43 $data = "98.6 degrees";
data.php
(2 of 3)Print each variable’s value
Call function settype to
convert the data type of
variable $testString to a
double.
Call function settype to
convert the data type of
variable $testString to an
integer.
Convert variable $testString
back to a string
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
11
44
45 // use type casting to cast variables to a
46 // different type
47 print( "Now using type casting instead: <br />
48 As a string - " . (string) $data .
49 "<br />As a double - " . (double) $data .
50 "<br />As an integer - " . (integer) $data );
51 ?>
52 </body>
53 </html>
data.php
(3 of 3)
Use type casting to cast variable
$data to different types
© 2003 Prentice Hall, Inc. All rights reserved.
12
26.2 PHP
Fig. 26.3 Type conversion.
© 2003 Prentice Hall, Inc. All rights reserved.
13
26.2 PHP
• Arithmetic operators
– Assignment operators
• Syntactical shortcuts
• Before being assigned values, variables have value undef
• Constants
– Named values
– define function
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
14
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 -->
5 <!-- Demonstration of operators -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using arithmetic operators</title>
10 </head>
11
12 <body>
13 <?php
14 $a = 5;
15 print( "The value of variable a is $a <br />" );
16
17 // define constant VALUE
18 define( "VALUE", 5 );
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
operators.php
(1 of 3)
Define constant VALUE.
Add constant VALUE to variable $a.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
15
25 // multiply variable $a by 2
26 $a *= 2;
27 print( "Multiplying variable a by 2 yields $a <br />" );
28
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 />" );
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,
44 inclusive<br />" );
45 else
46 print( "Variable a is now greater than 100
47 <br />" );
48
operators.php
(2 of 3)
Multiply variable $a by two using the
multiplication assignment operator *=.
Test whether variable $a is less than 50
Add 40 to variable $a using the addition assignment
operator +=.
Print if variable $a is less than 50.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
16
49 // print an uninitialized variable
50 print( "Using a variable before initializing:
51 $nothing <br />" );
52
53 // add constant VALUE to an uninitialized variable
54 $test = $num + VALUE;
55 print( "An uninitialized variable plus constant
56 VALUE yields $test <br />" );
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
62 <br />" );
63 ?>
64 </body>
65 </html>
operators.php
(3 of 3)
Add constant VALUE to an uninitialized
variable.
Add a string to an integer.
Print an uninitialized variable ($nothing).
© 2003 Prentice Hall, Inc. All rights reserved.
17
26.2 PHP
Fig. 26.4 Using PHP’s arithmetic operators.
© 2003 Prentice Hall, Inc. All rights reserved.
18
26.2 PHP
• Keywords
– Reserved for language features
– if…elseif…else
• Arrays
– Group of related data
• Elements
– Name plus braces and index
• Indices start at zero
– count function
– array function
© 2003 Prentice Hall, Inc. All rights reserved.
19
26.2 PHP
• Arrays, cont.
– Built-in iterators
• Maintain pointer to element currently referenced
• reset
• key
• next
• foreach loops
© 2003 Prentice Hall, Inc. All rights reserved.
20
26.2 PHP
PHP keywords
and
break
case
class
continue
default
do
else
elseif
extends
false
for
foreach
function
global
if
include
list
new
not
or
require
return
static
switch
this
true
var
virtual
xor
while
Fig. 26.5PHP keywords.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
21
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 -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Array manipulation</title>
10 </head>
11
12 <body>
13 <?php
14
15 // create array first
16 print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
19 $first[ 1 ] = "one";
20 $first[ 2 ] = "two";
21 $first[] = "three";
22
23 // print each element’s index and value
24 for ( $i = 0; $i < count( $first ); $i++ )
25 print( "Element $i is $first[$i] <br />" );
arrays.php
(1 of 3)
Create the array $first by assigning a value
to an array element.
Assign a value to the array, omitting the index.
Appends a new element to the end of the array.Use a for loop to print out each element’s index and value.
Function count returns the total number of elements in the
array.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
22
26
27 print( "<br /><strong>Creating the second array
28 </strong><br />" );
29
30 // call function array to create array second
31 $second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print( "Element $i is $second[$i] <br />" );
34
35 print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values to non-numerical indices
39 $third[ "ArtTic" ] = 21;
40 $third[ "LunaTic" ] = 18;
41 $third[ "GalAnt" ] = 23;
42
43 // iterate through the array elements and print each
44 // element’s name and value
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 print( "$element is $third[$element] <br />" );
48
arrays.php
(2 of 3)
Call function array to create an array that contains
the arguments passed to it. Store the array in variable
$second.
Assign values to non-numerical indices
in array $third.
Function reset sets the internal pointer to the
first element of the array.
Function key returns the index of the element which
the internal pointer references.
Function next moves the internal pointer to the next
element.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
23
49 print( "<br /><strong>Creating the fourth array
50 </strong><br />" );
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" => "fourth",
57 "May" => "fifth", "June" => "sixth",
58 "July" => "seventh", "August" => "eighth",
59 "September" => "ninth", "October" => "tenth",
60 "November" => "eleventh","December" => "twelfth"
61 );
62
63 // print each element’s name and value
64 foreach ( $fourth as $element => $value )
65 print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>
arrays.php
(3 of 3)
Operator => is used in function array to assign each
element a string index. The value to the left of the
operator is the array index, and the value to the right is
the element’s value.
© 2003 Prentice Hall, Inc. All rights reserved.
24
26.2 PHP
Fig. 26.6 Array manipulation.
© 2003 Prentice Hall, Inc. All rights reserved.
25
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
26
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 -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>String Comparison</title>
10 </head>
11
12 <body>
13 <?php
14
15 // create array fruits
16 $fruits = array( "apple", "orange", "banana" );
17
18 // iterate through each array element
19 for ( $i = 0; $i < count( $fruits ); $i++ ) {
20
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 " );
compare.php
(1 of 2)
Use a for loop to iterate through each array element.
Function strcmp compares two strings. If the first string
alphabetically precedes the second, then –1 is returned. If
the strings are equal, 0 is returned. If the first string
alphabetically follows the second, then 1 is returned.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
27
25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
26 print( $fruits[ $i ].
27 " is greater than banana " );
28 else
29 print( $fruits[ $i ]." is equal to banana " );
30
31 // use relational operators to compare each element
32 // to string "apple"
33 if ( $fruits[ $i ] < "apple" )
34 print( "and less than apple! <br />" );
35 elseif ( $fruits[ $i ] > "apple" )
36 print( "and greater than apple! <br />" );
37 elseif ( $fruits[ $i ] == "apple" )
38 print( "and equal to apple! <br />" );
39
40 }
41 ?>
42 </body>
43 </html>
compare.php
(2 of 2)
Use relational operators to compare each array
element to string “apple”.
© 2003 Prentice Hall, Inc. All rights reserved.
28
26.3 String Processing and Regular
Expressions
Fig. 26.7 Using the string comparison operators.
© 2003 Prentice Hall, Inc. All rights reserved.
29
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 [ ]
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
30
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
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Regular expressions</title>
10 </head>
11
12 <body>
13 <?php
14 $search = "Now is the time";
15 print( "Test string is: '$search'<br /><br />" );
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
expression.php
(1 of 3)
Function ereg searches for the literal
characters Now inside variable $search.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
31
22 // search for pattern 'Now' in the beginning of
23 // the string
24 if ( ereg( "^Now", $search ) )
25 print( "String 'Now' found at beginning
26 of the line.<br />" );
27
28 // search for pattern 'Now' at the end of the string
29 if ( ereg( "Now$", $search ) )
30 print( "String 'Now' was found at the end
31 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
39 // search for any words beginning with 't'
40 print( "Words beginning with 't' found: ");
41
42 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
43 $search, $match ) ) {
44 print( $match[ 1 ] . " " );
45
expression.php
(2 of 3)
The dollar sign special character ($) search for the
pattern Now at the end of the string.
The expression inside the parentheses, [a-zA-Z]*ow,
matches any word ending in ow. The quantifier *
matches the preceding pattern 0 or more times.
The special bracket expressions [[:<:]] and
[[:>:]] match the beginning and end of a word,
respectively.
Placing a pattern in parentheses stores the matched
string in the array that is specified in the third argument
to function ereg.
The while loop is used to find each occurrence of a
word in the string beginning with t.
The pattern used in this example, [[:<:]]
(t[[:alpha:]]+)[[:>:]], matches any word
beginning with the character t followed by one or more
characters. Character class [[:alpha:]] recognizes
any alphabetic character.
Function eregi is used to specify case insensitive
pattern matches.
The caret special character (^) matches the
beginning of a string. Function ereg searches the
beginning of the string for pattern Now .
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
32
expression.php
(3 of 3)
46 // remove the first occurrence of a word beginning
47 // with 't' to find other instances in the string
48 $search = ereg_replace( $match[ 1 ], "", $search );
49 }
50
51 print( "<br />" );
52 ?>
53 </body>
54 </html>
After printing a match of a word beginning with t, function
ereg_replace is called to remove the word from the string.
This is necessary be because to find multiple instances of a
given pattern, the first matched instance must first be removed.
Function ereg_replace takes three arguments: the pattern to
match, a string to replace the matched string and the string to
search.
© 2003 Prentice Hall, Inc. All rights reserved.
33
26.3 String Processing and Regular
Expressions
Fig. 26.8 Regular expressions in PHP.
© 2003 Prentice Hall, Inc. All rights reserved.
34
26.3 String Processing and Regular
Expressions
Quantifier Matches
{n} Exactly n times.
{m,n} Between m and n times inclusive.
{n,} n or more times.
+ One or more times (same as {1,}).
* Zero or more times (same as {0,}).
? Zero or one time (same as {0,1}).
Fig. 26.9 Some PHP quantifiers.
© 2003 Prentice Hall, Inc. All rights reserved.
35
26.3 String Processing and Regular
Expressions
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 Whitespace.
lower Lowercase letters.
upper Uppercase letters.
Fig. 26.10 Some PHP character classes.
© 2003 Prentice Hall, Inc. All rights reserved.
36
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
© 2003 Prentice Hall, Inc. All rights reserved.
37
26.4 Viewing Client/Server Environment
Variables
Variable name Description
$_SERVER Data about the currently running server.
$_ENV Data about the client’s environment.
$_GET Data posted to the server by the get method.
$_POST Data posted to the server by the post method.
$_COOKIE Data contained in cookies on the client’s computer.
$GLOBALS Array containing all global variables.
Fig. 26.11 Some useful global arrays.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
38
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.11: env.php -->
5 <!-- Program to display environment variables -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Environment Variables</title>
10 </head>
11
12 <body>
13 <table border = "0" cellpadding = "2" cellspacing = "0"
14 width = "100%">
15 <?php
16
17 // print the key and value for each element
18 // in the $_ENV array
19 foreach ( $_ENV as $key => $value )
20 print( "<tr><td bgcolor = "#11bbff">
21 <strong>$key</strong></td>
22 <td>$value</td></tr>" );
23 ?>
24 </table>
25 </body>
26 </html>
env.php
(1 of 1)
The foreach loop is used to print out the keys and
values for each element in the $_ENV array.
PHP stores environment variables and their values in
the $_ENV array.
© 2003 Prentice Hall, Inc. All rights reserved.
39
26.4 Viewing Client/Server Environment
Variables
Fig. 26.12 Displaying environment variables.
© 2003 Prentice Hall, Inc. All rights reserved.
40
26.5 Form Processing and Business Logic
• Form processing
– action property
• Where to send form data
– method property
• post
– Each element has unique name
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
41
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
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample form to take user input in XHTML</title>
10 </head>
11
12 <body>
13
14 <h1>This is a sample registration form.</h1>
15 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 Please fill out the fields below.<br />
22 </span>
23
form.html
(1 of 4)
The action attribute of the form element
indicates that when the user clicks Register, the
form data will be posted to form.php.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
42
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 <img src = "images/lname.gif" alt = "Last Name" />
29 <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 <span style = "font-size: 10pt">
38 Must be in the form (555)555-5555</span>
39 <br /><br />
40
41 <img src = "images/downloads.gif"
42 alt = "Publications" /><br />
43
44 <span style = "color: blue">
45 Which book would you like information about?
46 </span><br />
47
form.html
(2 of 4)
A unique name (e.g., email) is assigned to each
of the form’s input fields. When Register is
clicked, each field’s name and value are sent to
the Web server.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
43
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 />
56
57 <img src = "images/os.gif" alt = "Operating System" />
58 <br /><span style = "color: blue">
59 Which operating system are you currently using?
60 <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 />
form.html
(3 of 4)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
44
form.html
(4 of 4)
74
75 <input type = "radio" name = "os" value = "Linux" />
76 Linux
77
78 <input type = "radio" name = "os" value = "Other" />
79 Other<br />
80
81 <!-- create a submit button -->
82 <input type = "submit" value = "Register" />
83 </form>
84
85 </body>
86 </html>
© 2003 Prentice Hall, Inc. All rights reserved.
45
26.5 Form Processing and Business Logic
Fig. 26.13 XHTML form for gathering user input.
© 2003 Prentice Hall, Inc. All rights reserved.
46
26.5 Form Processing and Business Logic
• Business logic
– Confirm that valid information was entered
– extract function
• Creates variables corresponding to each key-value pair in array
• Easily retrieve all values sent to PHP page
– Regular expressions very helpful
– Do checks on client side where possible
• JavaScript
• Conserves server resources
• Ending a script
– die function
• Remember to close all HTML tags
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
47
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
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Form Validation</title>
10 </head>
11
12 <body style = "font-family: arial,sans-serif">
13
14 <?php
15 extract( $_POST );
16
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 $phone ) ){
21
form.php
(1 of 4)
Function ereg is called to determine whether the
phone number entered by the user is valid.
The expression ( matches the opening
parentheses of a phone number.
We access the phone field’s value from
form.html by using variable $phone.
The parentheses in the expression must be
followed by three digits ([0-9]{3}), a closing
parenthesis, three digits, a literal hyphen and
four additional digits.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
48
22 print( "<p><span style = "color: red;
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>" );
31
32 die(); // terminate script execution
33 }
34 ?>
35
36 <p>Hi
37 <span style = "color: blue">
38 <strong>
39 <?php print( "$fname" ); ?>
40 </strong>
41 </span>.
42 Thank you for completing the survey.<br />
43
form.php
(2 of 4)
Function die terminates script execution
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
49
44 You have been added to the
45 <span style = "color: blue">
46 <strong>
47 <?php print( "$book " ); ?>
48 </strong>
49 </span>
50 mailing list.
51 </p>
52 <strong>The following information has been saved
53 in our database:</strong><br />
54
55 <table border = "0" cellpadding = "0" cellspacing = "10">
56 <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 <tr>
64 <?php
65
form.php
(3 of 4)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
50
form.php
(4 of 4)
66 // print each form field’s value
67 print( "<td>$fname $lname</td>
68 <td>$email</td>
69 <td>$phone</td>
70 <td>$os</td>" );
71 ?>
72 </tr>
73 </table>
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 </div>
80 </body>
81 </html>
© 2003 Prentice Hall, Inc. All rights reserved.
51
26.5 Form Processing and Business Logic
Fig. 26.14 Obtaining user input through forms.
© 2003 Prentice Hall, Inc. All rights reserved.
52
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
• fopen function
• Read, write, append modes
– Store data using fputs
• n newline character
– Close files when done
• fclose function
© 2003 Prentice Hall, Inc. All rights reserved.
53
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
54
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.15: password.html -->
5 <!-- XHTML form sent to password.php for verification -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Verifying a username and a password.</title>
10
11 <style type = "text/css">
12 td { background-color: #DDDDDD }
13 </style>
14 </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 </span>
24 </p>
25
password.html
(1 of 4)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
55
26 <!-- post form data to password.php -->
27 <form action = "password.php" method = "post">
28 <br />
29
30 <table border = "0" cellspacing = "0"
31 style = "height: 90px; width: 123px;
32 font-size: 10pt" cellpadding = "0">
33
34 <tr>
35 <td colspan = "3">
36 <strong>Username:</strong>
37 </td>
38 </tr>
39
40 <tr>
41 <td colspan = "3">
42 <input size = "40" name = "USERNAME"
43 style = "height: 22px; width: 115px" />
44 </td>
45 </tr>
46
password.html
(2 of 4)
Form data is posted to password.php.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
56
47 <tr>
48 <td colspan = "3">
49 <strong>Password:</strong>
50 </td>
51 </tr>
52
53 <tr>
54 <td colspan = "3">
55 <input size = "40" name = "PASSWORD"
56 style = "height: 22px; width: 115px"
57 type = "password" />
58 <br/></td>
59 </tr>
60
61 <tr>
62 <td colspan = "1">
63 <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>
password.html
(3 of 4)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
57
72 </tr>
73 </table>
74 </form>
75 </body>
76 </html> password.html
(4 of 4)
© 2003 Prentice Hall, Inc. All rights reserved.
58
26.6 Verifying a Username and Password
Fig. 26.15 XHTML form for obtaining a username and password.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
59
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
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <?php
10 extract( $_POST );
11
12 // check if user has left USERNAME or PASSWORD field blank
13 if ( !$USERNAME || !$PASSWORD ) {
14 fieldsBlank();
15 die();
16 }
17
18 // check if the New User button was clicked
19 if ( isset( $NewUser ) ) {
20
21 // open password.txt for writing using append mode
22 if ( !( $file = fopen( "password.txt",
23 "a" ) ) ) {
24
password.php
(1 of 7)
Variable names, when preceded by the logical
negation operator (!), return true if they are empty
or set to 0. This checks if a user has submitted a form
without specifying a username or password.
Function fieldsBlank is called if the user has
submitted an incomplete form to notify the user
that all form fields must be completed.
Function isset tests whether the user has
pressed the New User button, indicating that a
new user must be added.
To add a new user, we open the file
password.txt in append mode and assign the
file handle that is returned to variable $file.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
60
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>" );
30 die();
31 }
32
33 // write username and password to file and
34 // call function userAdded
35 fputs( $file, "$USERNAME,$PASSWORDn" );
36 userAdded( $USERNAME );
37 }
38 else {
39
40 // if a new user is not being added, open file
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>" );
47 die();
48 }
49
password.php
(2 of 7)Print an error message and terminate script execution
if the file cannot be opened.
Function fputs writes the name and password to the
text file..
Function userAdded is called to print a message to the
user to indicate that the username and password were
added to the file.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
61
50 $userVerified = 0;
51
52 // read each line in file and check username
53 // and password
54 while ( !feof( $file ) && !$userVerified ) {
55
56 // read line from file
57 $line = fgets( $file, 255 );
58
59 // remove newline character from end of line
60 $line = chop( $line );
61
62 // split username and password
63 $field = split( ",", $line, 2 );
64
65 // verify username
66 if ( $USERNAME == $field[ 0 ] ) {
67 $userVerified = 1;
68
69 // call function checkPassword to verify
70 // user’s password
71 if ( checkPassword( $PASSWORD, $field )
72 == true )
73 accessGranted( $USERNAME );
74 else
75 wrongPassword();
password.php
(3 of 7)
Before entering the while loop, variable
$userVerified is set to 0.
The while loop executes as long as the there are more
lines in the file to read and variable $userVerified is
still 0 or empty.
Function fgets reads a line from the text file.
The result is assigned to variable $line.
Function chop removes the newline character
from the end of the line.
Function split is called to separate the string at the
specified delimiter (in this case, a comma). The
resulting array is stored in array $field.The username entered by the user is tested
against the one returned in the text file (stored
in the first element of the array). If they match,
variable $userVerified is set to 1.
Function checkPassword is called to verify the
user’s password. Variable $PASSWORD and array
$field are passed to the function.
If function checkPassword returns true, function
accessGranted is called to notify the client that
permission has been granted. Otherwise, function
wrongPassword is called.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
62
76 }
77 }
78
79 // close text file
80 fclose( $file );
81
82 // call function accessDenied if username has
83 // not been verified
84 if ( !$userVerified )
85 accessDenied();
86 }
87
88 // verify user password and return a boolean
89 function checkPassword( $userpassword, $filedata )
90 {
91 if ( $userpassword == $filedata[ 1 ] )
92 return true;
93 else
94 return false;
95 }
96
password.php
(4 of 7)
After the while loop has executed, function
fclose is called to close the file.
If variable $userVerified has not been set to a
value other than 0, function accessDenied is
called to notify the client that access has been
denied.
Function checkPassword compares the user’s
password to the password in the file. If they match,
true is returned, whereas false is returned if they
do not.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
63
97 // print a message indicating the user has been added
98 function userAdded( $name )
99 {
100 print( "<title>Thank You</title></head>
101 <body style = "font-family: arial;
102 font-size: 1em; color: blue">
103 <strong>You have been added
104 to the user list, $name.
105 <br />Enjoy the site.</strong>" );
106 }
107
108 // print a message indicating permission
109 // has been granted
110 function accessGranted( $name )
111 {
112 print( "<title>Thank You</title></head>
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
password.php
(5 of 7)
Function userAdded prints a message to the
client indicating that the user has been added.
Function accessGranted prints a
message to the client indicating that
permission has been granted.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
64
120 // print a message indicating password is invalid
121 function wrongPassword()
122 {
123 print( "<title>Access Denied</title></head>
124 <body style = "font-family: arial;
125 font-size: 1em; color: red">
126 <strong>You entered an invalid
127 password.<br />Access has
128 been denied.</strong>" );
129 }
130
131 // print a message indicating access has been denied
132 function accessDenied()
133 {
134 print( "<title>Access Denied</title></head>
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 }
141
password.php
(6 of 7)
Function wrongPassword prints a message to the
client indicating that the password is invalid.
Function accessDenied prints a message to the
client indicating that access has been denied.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
65
142 // print a message indicating that fields
143 // have been left blank
144 function fieldsBlank()
145 {
146 print( "<title>Access Denied</title></head>
147 <body style = "font-family: arial;
148 font-size: 1em; color: red">
149 <strong>
150 Please fill in all form fields.
151 <br /></strong>" );
152 }
153 ?>
154 </body>
155 </html>
password.php
(7 of 7)
Function fieldsBlank prints a message to the
client indicating that all form fields have not been
completed.
© 2003 Prentice Hall, Inc. All rights reserved.
66
26.6 Verifying a Username and Password
Fig. 26.16 Verifying a username and password.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
67
password.txt
(1 of 1)
1 account1,password1
2 account2,password2
3 account3,password3
4 account4,password4
5 account5,password5
6 account6,password6
7 account7,password7
8 account8,password8
9 account9,password9
10 account10,password10
© 2003 Prentice Hall, Inc. All rights reserved.
68
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
69
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 -->
5 <!-- Querying a MySQL Database -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample Database Query</title>
10 </head>
11
12 <body style = "background-color: #F0E68C">
13 <h2 style = "font-family: arial color: blue">
14 Querying a MySQL database.
15 </h2>
16
17 <form method = "post" action = "database.php">
18 <p>Select a field to display:
19
20 <!-- add a select box containing options -->
21 <!-- for SELECT query -->
data.html
(1 of 2)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
70
22 <select name = "select">
23 <option selected = "selected">*</option>
24 <option>ID</option>
25 <option>Title</option>
26 <option>Category</option>
27 <option>ISBN</option>
28 </select>
29 </p>
30
31 <input type = "submit" value = "Send Query"
32 style = "background-color: blue;
33 color: yellow; font-weight: bold" />
34 </form>
35 </body>
36 </html>
data.html
(2 of 2)
Select box containing options for a SELECT
query.
© 2003 Prentice Hall, Inc. All rights reserved.
71
26.7 Connecting to a Database
Fig. 26.18 Form to query a MySQL database.
© 2003 Prentice Hall, Inc. All rights reserved.
72
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
73
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.19: database.php -->
5 <!-- Program to query a database and -->
6 <!-- send results to the client. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search Results</title>
11 </head>
12
13 <body style = "font-family: arial, sans-serif"
14 style = "background-color: #F0E68C">
15 <?php
16
17 extract( $_POST );
18
19 // build SELECT query
20 $query = "SELECT " . $select . " FROM Books";
21
22 // Connect to MySQL
23 if ( !( $database = mysql_connect( "localhost",
24 "httpd", "" ) ) )
25 die( "Could not connect to database" );
database.php
(1 of 3)
Build the select query and assign the
string to variable $query.
Function mysql_connect returns a database
handle which represents PHP’s connection to a
database. If this connection is not made, function
die is called to terminate script execution.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
74
26
27 // open Products database
28 if ( !mysql_select_db( "Products", $database ) )
29 die( "Could not open Products database" );
30
31 // query Products database
32 if ( !( $result = mysql_query( $query, $database ) ) ) {
33 print( "Could not execute query! <br />" );
34 die( mysql_error() );
35 }
36 ?>
37
38 <h3 style = "color: blue">
39 Search Results</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 style = "background-color: #ADD8E6">
43
44 <?php
45
46 // fetch each record in result set
47 for ( $counter = 0;
48 $row = mysql_fetch_row( $result );
49 $counter++ ){
50
database.php
(2 of 3)
Function mysql_select_db is called to specify the
database to be queried.
Function mysql_query returns an object
containing the result set of the query, which
we assign to variable $result.
The for loop iterates through each
record in the result set while
constructing an XHTML table from
the results. Variable $counter is
incremented by one for each row
retrieved. Function mysql_fetch_row returns an
array containing the elements of each row
in the result set of our query ($result).
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
75
51 // build table to display results
52 print( "<tr>" );
53
54 foreach ( $row as $key => $value )
55 print( "<td>$value</td>" );
56
57 print( "</tr>" );
58 }
59
60 mysql_close( $database );
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
69 <a href = "mailto:deitel@deitel.com">
70 Deitel and Associates, Inc.
71 </a>
72 </h5>
73
74 </body>
75 </html>
database.php
(3 of 3)
The foreach loop iterates through the
array containing the elements of each row
and prints out each element in an
individual table cell.
The total number of results are printed to the
client.
© 2003 Prentice Hall, Inc. All rights reserved.
76
26.7 Connecting to a Database
Fig. 26.19 Querying a database and displaying the results.
© 2003 Prentice Hall, Inc. All rights reserved.
77
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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
78
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 -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Writing a cookie to the client computer</title>
10 </head>
11
12 <body style = "font-family: arial, sans-serif;
13 background-color: #99CCFF">
14
15 <h2>Click Write Cookie to save your cookie data.</h2>
16
cookies.html
(1 of 2)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
79
17 <form method = "post" action = "cookies.php"
18 style = "font-size: 10pt">
19 <strong>Name:</strong><br />
20 <input type = "text" name = "NAME" /><br />
21
22 <strong>Height:</strong><br />
23 <input type = "text" name = "HEIGHT" /><br />
24
25 <strong>Favorite Color:</strong><br />
26 <input type = "text" name = "COLOR" /><br />
27
28 <input type = "submit" value = "Write Cookie"
29 style = "background-color: #F0E86C; color: navy;
30 font-weight: bold" /></p>
31 </form>
32 </body>
33 </html>
cookies.html
(2 of 2)
Form data is posted to cookies.php.
© 2003 Prentice Hall, Inc. All rights reserved.
80
26.8 Cookies
Fig. 26.20 Gathering data to be written as a cookie.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
81
1 <?php
2 // Fig. 26.21: cookies.php
3 // Program to write a cookie to a client's machine
4
5 extract( $_POST );
6 // write each form field’s value to a cookie and set the
7 // cookie’s expiration date
8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?>
12
13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17 <head>
18 <title>Cookie Saved</title>
19 </head>
20
21 <body style = "font-family: arial, sans-serif">
22 <p>The cookie has been set with the following data:</p>
23
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
cookie. The optional third argument specifies
the expiration date of the cookie.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
82
24 <!-- print each form field’s value -->
25 <br /><span style = "color: blue">Name:</span>
26 <?php print( $NAME ) ?><br />
27
28 <span style = "color: blue">Height:</span>
29 <?php print( $HEIGHT ) ?><br />
30
31 <span style = "color: blue">Favorite Color:</span>
32
33 <span style = "color: <?php print( "$COLOR">$COLOR" ) ?>
34 </span><br />
35 <p>Click <a href = "readCookies.php">here</a>
36 to read the saved cookie.</p>
37 </body>
38 </html>
cookies.php
(2 of 2)
Each form field’s value is printed to
confirm the data that has been set as a
cookie with the user.
Hyperlink to readCookies.php.
© 2003 Prentice Hall, Inc. All rights reserved.
83
26.8 Cookies
Fig. 26.21 Writing a cookie to the client.
© 2003 Prentice Hall, Inc. All rights reserved.
84
26.8 Cookies
• Reading cookies
– $_COOKIE environment variable
• Array
– foreach loop to access each element
• Split into key and value
© 2003 Prentice Hall, Inc. All rights reserved.
85
26.8 Cookies
• Cookie storage
– Internet Explorer
• Stores cookies in Cookies directory
• Text file
© 2003 Prentice Hall, Inc. All rights reserved.
86
26.8 Cookies
Fig. 26.22 Cookies directory before a cookie is written.
Fig. 26.23 Cookies directory after a cookie is written.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
87
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
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 <p>
13 <strong>
14 The following data is saved in a cookie on your
15 computer.
16 </strong>
17 </p>
18
readCookies.php
(1 of 2)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
88
19 <table border = "5" cellspacing = "0" cellpadding = "10">
20 <?php
21
22 // iterate through array $_COOKIE and print
23 // name and value of each cookie
24 foreach ( $_COOKIE as $key => $value )
25 print( "<tr>
26 <td bgcolor="#F0E68C">$key</td>
27 <td bgcolor="#FFA500">$value</td>
28 </tr>" );
29 ?>
30
31 </table>
32 </body>
33 </html>
readCookies.php
(2 of 2)
PHP creates array $_COOKIE which contains all
cookie values indexed by their names.
The foreach loop iterates through the $_COOKIE
array and prints the name and value of each cookie in
an XHTML table.
© 2003 Prentice Hall, Inc. All rights reserved.
89
26.8 Cookies
Fig. 26.24 Displaying the cookie’s content.
© 2003 Prentice Hall, Inc. All rights reserved.
90
26.9 Dynamic Content in PHP
• Dynamically alter XHTML content
– Form’s 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
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
91
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
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample form to take user input in XHTML</title>
10 </head>
11
12 <body>
13 <?php
14 extract ( $_POST );
15 $iserror = false;
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
dynamicForm.php
(1 of 9)
Build array of options for the form.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
92
23 // array of possible operating systems
24 $systemlist = array( "Windows XP",
25 "Windows 2000",
26 "Windows 98",
27 "Linux",
28 "Other");
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" => "Phone" );
35
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
dynamicForm.php
(2 of 9)
Check for errors or omissions in form field
input.
If the page is being loaded as a result of a form
submission, do error checking and then retrieve
information from the database.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
93
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 if ( !$iserror ) {
58
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" );
dynamicForm.php
(3 of 9)
If there were no errors, query the MySQL
database.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
94
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 }
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>
dynamicForm.php
(4 of 9)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
95
98 <td bgcolor = '#ffffdd'>OS</td>
99 </tr>
100 <tr>
101
102 <!-- print each form field’s value -->
103 <td>$fname $lname</td>
104 <td>$email</td>
105 <td>$phone</td>
106 <td>$os</td>
107 </tr></table>
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>" );
117 die();
118 }
119 }
120
121 print( "<h1>This is a sample registration form.</h1>
122 Please fill in all fields and click Register." );
dynamicForm.php
(5 of 9)
Halt the script so the form-generation code
does not execute.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
96
123
124 if ( $iserror ) {
125 print( "<br /><span style = 'color : red'>
126 Fields with * need to be filled in properly.</span>" );
127 }
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
136 <!-- create four text boxes for user input -->" );
137 foreach ( $inputlist as $inputname => $inputalt ) {
138 $inputtext = $inputvalues[ $inputname ];
139
140 print( "<img src = 'images/$inputname.gif'
141 alt = '$inputalt' /><input type = 'text'
142 name = '$inputname' value = '" . $$inputname . "' />" );
143
144 if ( $formerrors[ ( $inputname )."error" ] == true )
145 print( "<span style = 'color : red'>*</span>" );
146
147 print( "<br />" );
148 }
dynamicForm.php
(6 of 9)
If the form input contained errors, place a red
asterisk (*) next to the text field.
Fill in the forms using $$variable syntax.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
97
149
150 print( "<span style = 'font-size : 10pt" );
151
152 if ( $formerrors[ "phoneerror" ] )
153 print( "; color : red" );
154
155 print( "'>Must be in the form (555)555-5555
156 </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 foreach ( $booklist as $currbook ) {
169 print( "<option" );
170
171 if ( ( $currbook == $book ) )
172 print( " selected = 'true'" );
173
dynamicForm.php
(7 of 9)
Make sure the correct book is selected in the
dropdown box.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
98
174 print( ">$currbook</option>" );
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>
182
183 <!-- create five radio buttons -->" );
184
185 $counter = 0;
186
187 foreach ( $systemlist as $currsystem ) {
188 print( "<input type = 'radio' name = 'os'
189 value = '$currsystem'" );
190
191 if ( $currsystem == $os ) print( "checked = 'checked'" );
192 if ( $iserror && $counter == 0 ) print( "checked = 'checked'" );
193
194 print( " />$currsystem" );
195
196 if ( $counter == 2 ) print( "<br />" );
197 $counter++;
198 }
199
dynamicForm.php
(8 of 9)
Make sure the correct OS is checked in the
checkbox.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
99
200 print( "<!-- create a submit button -->
201 <br />
202 <input type = 'submit' name = 'submit' value = 'Register' />
203 </form></body></html>" );
204 ?> dynamicForm.php
(9 of 9)
© 2003 Prentice Hall, Inc. All rights reserved.
100
26.9 Dynamic Content in PHP
Fig. 26.25 Dynamic form using PHP.
© 2003 Prentice Hall, Inc. All rights reserved.
101
26.9 Dynamic Content in PHP
Fig. 26.25 Dynamic form using PHP.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
102
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. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search Results</title>
11 </head>
12
13 <body style = "font-family: arial, sans-serif"
14 style = "background-color: #F0E68C">
15 <?php
16
17 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" );
formDatabase.php
(1 of 3)
Build the query string.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
103
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 ?>
37
38 <h3 style = "color: blue">
39 Mailing List Contacts</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 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>
formDatabase.php
(2 of 3)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
104
51 <td>Operating System</td>
52 </tr>
53 <?php
54
55 // fetch each record in result set
56 for ( $counter = 0;
57 $row = mysql_fetch_row( $result );
58 $counter++ ){
59
60 // build table to display results
61 print( "<tr>" );
62
63 foreach ( $row as $key => $value )
64 print( "<td>$value</td>" );
65
66 print( "</tr>" );
67 }
68
69 mysql_close( $database );
70 ?>
71
72 </table>
73
74 </body>
75 </html>
formDatabase.php
(3 of 3)
Dynamically create a table
containing each mailing list
member.
Retrieve each mailing list
member record from the
database.
© 2003 Prentice Hall, Inc. All rights reserved.
105
26.9 Dynamic Content in PHP
Fig. 26.26 Displaying the MailingList database.
© 2003 Prentice Hall, Inc. All rights reserved.
106
26.10 Operator Precedence
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
<<
>>
bitwise shift left
bitwise shift right
left to right
<
>
<=
>=
less than
greater than
less than or equal
greater than or equal
none
==
!=
===
!==
equal
not equal
identical
not identical
none
Fig. 26.27 PHP operator precedence and associativity.
© 2003 Prentice Hall, Inc. All rights reserved.
107
26.10 Operator Precedence
Operator Type Associativity
& 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
=
+=
-=
*=
/=
&=
|=
^=
.=
<<=
>>=
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
left to right
and logical AND left to right
xor exclusive OR left to right
or logical OR left to right
, list left to right
Fig. 26.27 PHP operator precedence and associativity.

More Related Content

What's hot (16)

Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
Peter Eisentraut
 
PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
andrewdotcom
 
Introduction to PHP 5.3
Introduction to PHP 5.3Introduction to PHP 5.3
Introduction to PHP 5.3
guestcc91d4
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionality
Sayed Ahmed
 
Workshop unittesting
Workshop unittestingWorkshop unittesting
Workshop unittesting
Joshua Thijssen
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
Damien Seguy
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
webhostingguy
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
Fwdays
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
Perl Intro 4 Debugger
Perl Intro 4 DebuggerPerl Intro 4 Debugger
Perl Intro 4 Debugger
Shaun Griffith
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Psr-7
Psr-7Psr-7
Psr-7
Marco Perone
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
Peter Eisentraut
 
PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
andrewdotcom
 
Introduction to PHP 5.3
Introduction to PHP 5.3Introduction to PHP 5.3
Introduction to PHP 5.3
guestcc91d4
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionality
Sayed Ahmed
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
Damien Seguy
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
Fwdays
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 

Similar to Php 26 (20)

Php 26
Php 26Php 26
Php 26
Simratpreet Singh
 
Synapse india basic php development part 1
Synapse india basic php development part 1Synapse india basic php development part 1
Synapse india basic php development part 1
Synapseindiappsdevelopment
 
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP nPHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
ArtiRaju1
 
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP nPHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
ArtiRaju1
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
Aftabali702240
 
Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401
lakshitakumar291
 
Intro to php
Intro to phpIntro to php
Intro to php
NithyaNithyav
 
PHP-Part1
PHP-Part1PHP-Part1
PHP-Part1
Ahmed Saihood
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
pkaviya
 
Php introduction
Php introductionPhp introduction
Php introduction
Pratik Patel
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
Muthuganesh S
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
vibrantuser
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
Khem Puthea
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
Bozhidar Boshnakov
 
Php
PhpPhp
Php
Rajkiran Mummadi
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
Chhom Karath
 
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP nPHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
ArtiRaju1
 
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP nPHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n
ArtiRaju1
 
Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401
lakshitakumar291
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
pkaviya
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
vibrantuser
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
Khem Puthea
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Ch1(introduction to php)
Ch1(introduction to php)Ch1(introduction to php)
Ch1(introduction to php)
Chhom Karath
 
Ad

Php 26

  • 1. © 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 26 - PHP Outline 26.1 Introduction 26.2 PHP 26.3 String Processing and Regular Expressions 26.4 Viewing Client/Server Environment Variables 26.5 Form Processing and Business Logic 26.6 Verifying a Username and Password 26.7 Connecting to a Database 26.8 Cookies 26.9 Dynamic Content in PHP 26.10 Operator Precedence 26.11 Web Resources
  • 2. © 2003 Prentice Hall, Inc. All rights reserved. 2 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.
  • 3. © 2003 Prentice Hall, Inc. All rights reserved. 3 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
  • 4. © 2003 Prentice Hall, Inc. All rights reserved. 4 26.2 PHP • Basic application – Scripting delimiters • <? php ?> • Must enclose all script code – Variables preceded by $ symbol • Case-sensitive – End statements with semicolon – Comments • // for single line • /* */ for multiline – Filenames end with .php by convention
  • 5. © 2003 Prentice Hall, Inc. All rights reserved. Outline 5 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3 4 <!-- Fig. 26.1: first.php --> 5 <!-- Our first PHP script --> 6 7 <?php 8 $name = "LunaTic"; // declaration 9 ?> 10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 <head> 13 <title>A simple PHP document</title> 14 </head> 15 16 <body style = "font-size: 2em"> 17 <p> 18 <strong> 19 20 <!-- print variable name’s value --> 21 Welcome to PHP, <?php print( "$name" ); ?>! 22 </strong> 23 </p> 24 </body> 25 </html> first.php (1 of 1) Declare variable $name Scripting delimiters Single-line comment Function print outputs the value of variable $name
  • 6. © 2003 Prentice Hall, Inc. All rights reserved. 6 26.2 PHP Fig. 26.1 Simple PHP program.
  • 7. © 2003 Prentice Hall, Inc. All rights reserved. 7 26.2 PHP • Variables – Can have different types at different times – Variable names inside strings replaced by their value – Type conversions • settype function • Type casting – Concatenation operator • . (period) • Combine strings
  • 8. © 2003 Prentice Hall, Inc. All rights reserved. 8 26.2 PHP Data type Description int, integer Whole numbers (i.e., numbers without a decimal point). float, double Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single ('') or double ("") quotes. bool, Boolean True or false. array Group of elements of the same type. object Group of associated data and methods. Resource An external data source. NULL No value. Fig. 26.2PHP data types.
  • 9. © 2003 Prentice Hall, Inc. All rights reserved. Outline 9 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 --> 5 <!-- Demonstration of PHP data types --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>PHP data types</title> 10 </head> 11 12 <body> 13 14 <?php 15 16 // declare a string, double and integer 17 $testString = "3.5 seconds"; 18 $testDouble = 79.2; 19 $testInteger = 12; 20 ?> 21 data.php (1 of 3) Assign a string to variable $testString Assign a double to variable $testDoubleAssign an integer to variable $testInteger
  • 10. © 2003 Prentice Hall, Inc. All rights reserved. Outline 10 22 <!-- print each variable’s 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 /> 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 print( "Converting back to a string results in 41 $testString <br /><br />" ); 42 43 $data = "98.6 degrees"; data.php (2 of 3)Print each variable’s value Call function settype to convert the data type of variable $testString to a double. Call function settype to convert the data type of variable $testString to an integer. Convert variable $testString back to a string
  • 11. © 2003 Prentice Hall, Inc. All rights reserved. Outline 11 44 45 // use type casting to cast variables to a 46 // different type 47 print( "Now using type casting instead: <br /> 48 As a string - " . (string) $data . 49 "<br />As a double - " . (double) $data . 50 "<br />As an integer - " . (integer) $data ); 51 ?> 52 </body> 53 </html> data.php (3 of 3) Use type casting to cast variable $data to different types
  • 12. © 2003 Prentice Hall, Inc. All rights reserved. 12 26.2 PHP Fig. 26.3 Type conversion.
  • 13. © 2003 Prentice Hall, Inc. All rights reserved. 13 26.2 PHP • Arithmetic operators – Assignment operators • Syntactical shortcuts • Before being assigned values, variables have value undef • Constants – Named values – define function
  • 14. © 2003 Prentice Hall, Inc. All rights reserved. Outline 14 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 --> 5 <!-- Demonstration of operators --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Using arithmetic operators</title> 10 </head> 11 12 <body> 13 <?php 14 $a = 5; 15 print( "The value of variable a is $a <br />" ); 16 17 // define constant VALUE 18 define( "VALUE", 5 ); 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 operators.php (1 of 3) Define constant VALUE. Add constant VALUE to variable $a.
  • 15. © 2003 Prentice Hall, Inc. All rights reserved. Outline 15 25 // multiply variable $a by 2 26 $a *= 2; 27 print( "Multiplying variable a by 2 yields $a <br />" ); 28 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 />" ); 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, 44 inclusive<br />" ); 45 else 46 print( "Variable a is now greater than 100 47 <br />" ); 48 operators.php (2 of 3) Multiply variable $a by two using the multiplication assignment operator *=. Test whether variable $a is less than 50 Add 40 to variable $a using the addition assignment operator +=. Print if variable $a is less than 50.
  • 16. © 2003 Prentice Hall, Inc. All rights reserved. Outline 16 49 // print an uninitialized variable 50 print( "Using a variable before initializing: 51 $nothing <br />" ); 52 53 // add constant VALUE to an uninitialized variable 54 $test = $num + VALUE; 55 print( "An uninitialized variable plus constant 56 VALUE yields $test <br />" ); 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 62 <br />" ); 63 ?> 64 </body> 65 </html> operators.php (3 of 3) Add constant VALUE to an uninitialized variable. Add a string to an integer. Print an uninitialized variable ($nothing).
  • 17. © 2003 Prentice Hall, Inc. All rights reserved. 17 26.2 PHP Fig. 26.4 Using PHP’s arithmetic operators.
  • 18. © 2003 Prentice Hall, Inc. All rights reserved. 18 26.2 PHP • Keywords – Reserved for language features – if…elseif…else • Arrays – Group of related data • Elements – Name plus braces and index • Indices start at zero – count function – array function
  • 19. © 2003 Prentice Hall, Inc. All rights reserved. 19 26.2 PHP • Arrays, cont. – Built-in iterators • Maintain pointer to element currently referenced • reset • key • next • foreach loops
  • 20. © 2003 Prentice Hall, Inc. All rights reserved. 20 26.2 PHP PHP keywords and break case class continue default do else elseif extends false for foreach function global if include list new not or require return static switch this true var virtual xor while Fig. 26.5PHP keywords.
  • 21. © 2003 Prentice Hall, Inc. All rights reserved. Outline 21 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 --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Array manipulation</title> 10 </head> 11 12 <body> 13 <?php 14 15 // create array first 16 print( "<strong>Creating the first array</strong> 17 <br />" ); 18 $first[ 0 ] = "zero"; 19 $first[ 1 ] = "one"; 20 $first[ 2 ] = "two"; 21 $first[] = "three"; 22 23 // print each element’s index and value 24 for ( $i = 0; $i < count( $first ); $i++ ) 25 print( "Element $i is $first[$i] <br />" ); arrays.php (1 of 3) Create the array $first by assigning a value to an array element. Assign a value to the array, omitting the index. Appends a new element to the end of the array.Use a for loop to print out each element’s index and value. Function count returns the total number of elements in the array.
  • 22. © 2003 Prentice Hall, Inc. All rights reserved. Outline 22 26 27 print( "<br /><strong>Creating the second array 28 </strong><br />" ); 29 30 // call function array to create array second 31 $second = array( "zero", "one", "two", "three" ); 32 for ( $i = 0; $i < count( $second ); $i++ ) 33 print( "Element $i is $second[$i] <br />" ); 34 35 print( "<br /><strong>Creating the third array 36 </strong><br />" ); 37 38 // assign values to non-numerical indices 39 $third[ "ArtTic" ] = 21; 40 $third[ "LunaTic" ] = 18; 41 $third[ "GalAnt" ] = 23; 42 43 // iterate through the array elements and print each 44 // element’s name and value 45 for ( reset( $third ); $element = key( $third ); 46 next( $third ) ) 47 print( "$element is $third[$element] <br />" ); 48 arrays.php (2 of 3) Call function array to create an array that contains the arguments passed to it. Store the array in variable $second. Assign values to non-numerical indices in array $third. Function reset sets the internal pointer to the first element of the array. Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element.
  • 23. © 2003 Prentice Hall, Inc. All rights reserved. Outline 23 49 print( "<br /><strong>Creating the fourth array 50 </strong><br />" ); 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" => "fourth", 57 "May" => "fifth", "June" => "sixth", 58 "July" => "seventh", "August" => "eighth", 59 "September" => "ninth", "October" => "tenth", 60 "November" => "eleventh","December" => "twelfth" 61 ); 62 63 // print each element’s name and value 64 foreach ( $fourth as $element => $value ) 65 print( "$element is the $value month <br />" ); 66 ?> 67 </body> 68 </html> arrays.php (3 of 3) Operator => is used in function array to assign each element a string index. The value to the left of the operator is the array index, and the value to the right is the element’s value.
  • 24. © 2003 Prentice Hall, Inc. All rights reserved. 24 26.2 PHP Fig. 26.6 Array manipulation.
  • 25. © 2003 Prentice Hall, Inc. All rights reserved. 25 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
  • 26. © 2003 Prentice Hall, Inc. All rights reserved. Outline 26 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 --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>String Comparison</title> 10 </head> 11 12 <body> 13 <?php 14 15 // create array fruits 16 $fruits = array( "apple", "orange", "banana" ); 17 18 // iterate through each array element 19 for ( $i = 0; $i < count( $fruits ); $i++ ) { 20 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 " ); compare.php (1 of 2) Use a for loop to iterate through each array element. Function strcmp compares two strings. If the first string alphabetically precedes the second, then –1 is returned. If the strings are equal, 0 is returned. If the first string alphabetically follows the second, then 1 is returned.
  • 27. © 2003 Prentice Hall, Inc. All rights reserved. Outline 27 25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) 26 print( $fruits[ $i ]. 27 " is greater than banana " ); 28 else 29 print( $fruits[ $i ]." is equal to banana " ); 30 31 // use relational operators to compare each element 32 // to string "apple" 33 if ( $fruits[ $i ] < "apple" ) 34 print( "and less than apple! <br />" ); 35 elseif ( $fruits[ $i ] > "apple" ) 36 print( "and greater than apple! <br />" ); 37 elseif ( $fruits[ $i ] == "apple" ) 38 print( "and equal to apple! <br />" ); 39 40 } 41 ?> 42 </body> 43 </html> compare.php (2 of 2) Use relational operators to compare each array element to string “apple”.
  • 28. © 2003 Prentice Hall, Inc. All rights reserved. 28 26.3 String Processing and Regular Expressions Fig. 26.7 Using the string comparison operators.
  • 29. © 2003 Prentice Hall, Inc. All rights reserved. 29 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 [ ]
  • 30. © 2003 Prentice Hall, Inc. All rights reserved. Outline 30 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 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Regular expressions</title> 10 </head> 11 12 <body> 13 <?php 14 $search = "Now is the time"; 15 print( "Test string is: '$search'<br /><br />" ); 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 expression.php (1 of 3) Function ereg searches for the literal characters Now inside variable $search.
  • 31. © 2003 Prentice Hall, Inc. All rights reserved. Outline 31 22 // search for pattern 'Now' in the beginning of 23 // the string 24 if ( ereg( "^Now", $search ) ) 25 print( "String 'Now' found at beginning 26 of the line.<br />" ); 27 28 // search for pattern 'Now' at the end of the string 29 if ( ereg( "Now$", $search ) ) 30 print( "String 'Now' was found at the end 31 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 39 // search for any words beginning with 't' 40 print( "Words beginning with 't' found: "); 41 42 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", 43 $search, $match ) ) { 44 print( $match[ 1 ] . " " ); 45 expression.php (2 of 3) The dollar sign special character ($) search for the pattern Now at the end of the string. The expression inside the parentheses, [a-zA-Z]*ow, matches any word ending in ow. The quantifier * matches the preceding pattern 0 or more times. The special bracket expressions [[:<:]] and [[:>:]] match the beginning and end of a word, respectively. Placing a pattern in parentheses stores the matched string in the array that is specified in the third argument to function ereg. The while loop is used to find each occurrence of a word in the string beginning with t. The pattern used in this example, [[:<:]] (t[[:alpha:]]+)[[:>:]], matches any word beginning with the character t followed by one or more characters. Character class [[:alpha:]] recognizes any alphabetic character. Function eregi is used to specify case insensitive pattern matches. The caret special character (^) matches the beginning of a string. Function ereg searches the beginning of the string for pattern Now .
  • 32. © 2003 Prentice Hall, Inc. All rights reserved. Outline 32 expression.php (3 of 3) 46 // remove the first occurrence of a word beginning 47 // with 't' to find other instances in the string 48 $search = ereg_replace( $match[ 1 ], "", $search ); 49 } 50 51 print( "<br />" ); 52 ?> 53 </body> 54 </html> After printing a match of a word beginning with t, function ereg_replace is called to remove the word from the string. This is necessary be because to find multiple instances of a given pattern, the first matched instance must first be removed. Function ereg_replace takes three arguments: the pattern to match, a string to replace the matched string and the string to search.
  • 33. © 2003 Prentice Hall, Inc. All rights reserved. 33 26.3 String Processing and Regular Expressions Fig. 26.8 Regular expressions in PHP.
  • 34. © 2003 Prentice Hall, Inc. All rights reserved. 34 26.3 String Processing and Regular Expressions Quantifier Matches {n} Exactly n times. {m,n} Between m and n times inclusive. {n,} n or more times. + One or more times (same as {1,}). * Zero or more times (same as {0,}). ? Zero or one time (same as {0,1}). Fig. 26.9 Some PHP quantifiers.
  • 35. © 2003 Prentice Hall, Inc. All rights reserved. 35 26.3 String Processing and Regular Expressions 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 Whitespace. lower Lowercase letters. upper Uppercase letters. Fig. 26.10 Some PHP character classes.
  • 36. © 2003 Prentice Hall, Inc. All rights reserved. 36 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
  • 37. © 2003 Prentice Hall, Inc. All rights reserved. 37 26.4 Viewing Client/Server Environment Variables Variable name Description $_SERVER Data about the currently running server. $_ENV Data about the client’s environment. $_GET Data posted to the server by the get method. $_POST Data posted to the server by the post method. $_COOKIE Data contained in cookies on the client’s computer. $GLOBALS Array containing all global variables. Fig. 26.11 Some useful global arrays.
  • 38. © 2003 Prentice Hall, Inc. All rights reserved. Outline 38 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.11: env.php --> 5 <!-- Program to display environment variables --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Environment Variables</title> 10 </head> 11 12 <body> 13 <table border = "0" cellpadding = "2" cellspacing = "0" 14 width = "100%"> 15 <?php 16 17 // print the key and value for each element 18 // in the $_ENV array 19 foreach ( $_ENV as $key => $value ) 20 print( "<tr><td bgcolor = "#11bbff"> 21 <strong>$key</strong></td> 22 <td>$value</td></tr>" ); 23 ?> 24 </table> 25 </body> 26 </html> env.php (1 of 1) The foreach loop is used to print out the keys and values for each element in the $_ENV array. PHP stores environment variables and their values in the $_ENV array.
  • 39. © 2003 Prentice Hall, Inc. All rights reserved. 39 26.4 Viewing Client/Server Environment Variables Fig. 26.12 Displaying environment variables.
  • 40. © 2003 Prentice Hall, Inc. All rights reserved. 40 26.5 Form Processing and Business Logic • Form processing – action property • Where to send form data – method property • post – Each element has unique name
  • 41. © 2003 Prentice Hall, Inc. All rights reserved. Outline 41 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 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample form to take user input in XHTML</title> 10 </head> 11 12 <body> 13 14 <h1>This is a sample registration form.</h1> 15 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 Please fill out the fields below.<br /> 22 </span> 23 form.html (1 of 4) The action attribute of the form element indicates that when the user clicks Register, the form data will be posted to form.php.
  • 42. © 2003 Prentice Hall, Inc. All rights reserved. Outline 42 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 <img src = "images/lname.gif" alt = "Last Name" /> 29 <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 <span style = "font-size: 10pt"> 38 Must be in the form (555)555-5555</span> 39 <br /><br /> 40 41 <img src = "images/downloads.gif" 42 alt = "Publications" /><br /> 43 44 <span style = "color: blue"> 45 Which book would you like information about? 46 </span><br /> 47 form.html (2 of 4) A unique name (e.g., email) is assigned to each of the form’s input fields. When Register is clicked, each field’s name and value are sent to the Web server.
  • 43. © 2003 Prentice Hall, Inc. All rights reserved. Outline 43 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 /> 56 57 <img src = "images/os.gif" alt = "Operating System" /> 58 <br /><span style = "color: blue"> 59 Which operating system are you currently using? 60 <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 /> form.html (3 of 4)
  • 44. © 2003 Prentice Hall, Inc. All rights reserved. Outline 44 form.html (4 of 4) 74 75 <input type = "radio" name = "os" value = "Linux" /> 76 Linux 77 78 <input type = "radio" name = "os" value = "Other" /> 79 Other<br /> 80 81 <!-- create a submit button --> 82 <input type = "submit" value = "Register" /> 83 </form> 84 85 </body> 86 </html>
  • 45. © 2003 Prentice Hall, Inc. All rights reserved. 45 26.5 Form Processing and Business Logic Fig. 26.13 XHTML form for gathering user input.
  • 46. © 2003 Prentice Hall, Inc. All rights reserved. 46 26.5 Form Processing and Business Logic • Business logic – Confirm that valid information was entered – extract function • Creates variables corresponding to each key-value pair in array • Easily retrieve all values sent to PHP page – Regular expressions very helpful – Do checks on client side where possible • JavaScript • Conserves server resources • Ending a script – die function • Remember to close all HTML tags
  • 47. © 2003 Prentice Hall, Inc. All rights reserved. Outline 47 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 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Form Validation</title> 10 </head> 11 12 <body style = "font-family: arial,sans-serif"> 13 14 <?php 15 extract( $_POST ); 16 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 $phone ) ){ 21 form.php (1 of 4) Function ereg is called to determine whether the phone number entered by the user is valid. The expression ( matches the opening parentheses of a phone number. We access the phone field’s value from form.html by using variable $phone. The parentheses in the expression must be followed by three digits ([0-9]{3}), a closing parenthesis, three digits, a literal hyphen and four additional digits.
  • 48. © 2003 Prentice Hall, Inc. All rights reserved. Outline 48 22 print( "<p><span style = "color: red; 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>" ); 31 32 die(); // terminate script execution 33 } 34 ?> 35 36 <p>Hi 37 <span style = "color: blue"> 38 <strong> 39 <?php print( "$fname" ); ?> 40 </strong> 41 </span>. 42 Thank you for completing the survey.<br /> 43 form.php (2 of 4) Function die terminates script execution
  • 49. © 2003 Prentice Hall, Inc. All rights reserved. Outline 49 44 You have been added to the 45 <span style = "color: blue"> 46 <strong> 47 <?php print( "$book " ); ?> 48 </strong> 49 </span> 50 mailing list. 51 </p> 52 <strong>The following information has been saved 53 in our database:</strong><br /> 54 55 <table border = "0" cellpadding = "0" cellspacing = "10"> 56 <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 <tr> 64 <?php 65 form.php (3 of 4)
  • 50. © 2003 Prentice Hall, Inc. All rights reserved. Outline 50 form.php (4 of 4) 66 // print each form field’s value 67 print( "<td>$fname $lname</td> 68 <td>$email</td> 69 <td>$phone</td> 70 <td>$os</td>" ); 71 ?> 72 </tr> 73 </table> 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 </div> 80 </body> 81 </html>
  • 51. © 2003 Prentice Hall, Inc. All rights reserved. 51 26.5 Form Processing and Business Logic Fig. 26.14 Obtaining user input through forms.
  • 52. © 2003 Prentice Hall, Inc. All rights reserved. 52 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 • fopen function • Read, write, append modes – Store data using fputs • n newline character – Close files when done • fclose function
  • 53. © 2003 Prentice Hall, Inc. All rights reserved. 53 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
  • 54. © 2003 Prentice Hall, Inc. All rights reserved. Outline 54 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.15: password.html --> 5 <!-- XHTML form sent to password.php for verification --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Verifying a username and a password.</title> 10 11 <style type = "text/css"> 12 td { background-color: #DDDDDD } 13 </style> 14 </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 </span> 24 </p> 25 password.html (1 of 4)
  • 55. © 2003 Prentice Hall, Inc. All rights reserved. Outline 55 26 <!-- post form data to password.php --> 27 <form action = "password.php" method = "post"> 28 <br /> 29 30 <table border = "0" cellspacing = "0" 31 style = "height: 90px; width: 123px; 32 font-size: 10pt" cellpadding = "0"> 33 34 <tr> 35 <td colspan = "3"> 36 <strong>Username:</strong> 37 </td> 38 </tr> 39 40 <tr> 41 <td colspan = "3"> 42 <input size = "40" name = "USERNAME" 43 style = "height: 22px; width: 115px" /> 44 </td> 45 </tr> 46 password.html (2 of 4) Form data is posted to password.php.
  • 56. © 2003 Prentice Hall, Inc. All rights reserved. Outline 56 47 <tr> 48 <td colspan = "3"> 49 <strong>Password:</strong> 50 </td> 51 </tr> 52 53 <tr> 54 <td colspan = "3"> 55 <input size = "40" name = "PASSWORD" 56 style = "height: 22px; width: 115px" 57 type = "password" /> 58 <br/></td> 59 </tr> 60 61 <tr> 62 <td colspan = "1"> 63 <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> password.html (3 of 4)
  • 57. © 2003 Prentice Hall, Inc. All rights reserved. Outline 57 72 </tr> 73 </table> 74 </form> 75 </body> 76 </html> password.html (4 of 4)
  • 58. © 2003 Prentice Hall, Inc. All rights reserved. 58 26.6 Verifying a Username and Password Fig. 26.15 XHTML form for obtaining a username and password.
  • 59. © 2003 Prentice Hall, Inc. All rights reserved. Outline 59 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 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <?php 10 extract( $_POST ); 11 12 // check if user has left USERNAME or PASSWORD field blank 13 if ( !$USERNAME || !$PASSWORD ) { 14 fieldsBlank(); 15 die(); 16 } 17 18 // check if the New User button was clicked 19 if ( isset( $NewUser ) ) { 20 21 // open password.txt for writing using append mode 22 if ( !( $file = fopen( "password.txt", 23 "a" ) ) ) { 24 password.php (1 of 7) Variable names, when preceded by the logical negation operator (!), return true if they are empty or set to 0. This checks if a user has submitted a form without specifying a username or password. Function fieldsBlank is called if the user has submitted an incomplete form to notify the user that all form fields must be completed. Function isset tests whether the user has pressed the New User button, indicating that a new user must be added. To add a new user, we open the file password.txt in append mode and assign the file handle that is returned to variable $file.
  • 60. © 2003 Prentice Hall, Inc. All rights reserved. Outline 60 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>" ); 30 die(); 31 } 32 33 // write username and password to file and 34 // call function userAdded 35 fputs( $file, "$USERNAME,$PASSWORDn" ); 36 userAdded( $USERNAME ); 37 } 38 else { 39 40 // if a new user is not being added, open file 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>" ); 47 die(); 48 } 49 password.php (2 of 7)Print an error message and terminate script execution if the file cannot be opened. Function fputs writes the name and password to the text file.. Function userAdded is called to print a message to the user to indicate that the username and password were added to the file.
  • 61. © 2003 Prentice Hall, Inc. All rights reserved. Outline 61 50 $userVerified = 0; 51 52 // read each line in file and check username 53 // and password 54 while ( !feof( $file ) && !$userVerified ) { 55 56 // read line from file 57 $line = fgets( $file, 255 ); 58 59 // remove newline character from end of line 60 $line = chop( $line ); 61 62 // split username and password 63 $field = split( ",", $line, 2 ); 64 65 // verify username 66 if ( $USERNAME == $field[ 0 ] ) { 67 $userVerified = 1; 68 69 // call function checkPassword to verify 70 // user’s password 71 if ( checkPassword( $PASSWORD, $field ) 72 == true ) 73 accessGranted( $USERNAME ); 74 else 75 wrongPassword(); password.php (3 of 7) Before entering the while loop, variable $userVerified is set to 0. The while loop executes as long as the there are more lines in the file to read and variable $userVerified is still 0 or empty. Function fgets reads a line from the text file. The result is assigned to variable $line. Function chop removes the newline character from the end of the line. Function split is called to separate the string at the specified delimiter (in this case, a comma). The resulting array is stored in array $field.The username entered by the user is tested against the one returned in the text file (stored in the first element of the array). If they match, variable $userVerified is set to 1. Function checkPassword is called to verify the user’s password. Variable $PASSWORD and array $field are passed to the function. If function checkPassword returns true, function accessGranted is called to notify the client that permission has been granted. Otherwise, function wrongPassword is called.
  • 62. © 2003 Prentice Hall, Inc. All rights reserved. Outline 62 76 } 77 } 78 79 // close text file 80 fclose( $file ); 81 82 // call function accessDenied if username has 83 // not been verified 84 if ( !$userVerified ) 85 accessDenied(); 86 } 87 88 // verify user password and return a boolean 89 function checkPassword( $userpassword, $filedata ) 90 { 91 if ( $userpassword == $filedata[ 1 ] ) 92 return true; 93 else 94 return false; 95 } 96 password.php (4 of 7) After the while loop has executed, function fclose is called to close the file. If variable $userVerified has not been set to a value other than 0, function accessDenied is called to notify the client that access has been denied. Function checkPassword compares the user’s password to the password in the file. If they match, true is returned, whereas false is returned if they do not.
  • 63. © 2003 Prentice Hall, Inc. All rights reserved. Outline 63 97 // print a message indicating the user has been added 98 function userAdded( $name ) 99 { 100 print( "<title>Thank You</title></head> 101 <body style = "font-family: arial; 102 font-size: 1em; color: blue"> 103 <strong>You have been added 104 to the user list, $name. 105 <br />Enjoy the site.</strong>" ); 106 } 107 108 // print a message indicating permission 109 // has been granted 110 function accessGranted( $name ) 111 { 112 print( "<title>Thank You</title></head> 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 password.php (5 of 7) Function userAdded prints a message to the client indicating that the user has been added. Function accessGranted prints a message to the client indicating that permission has been granted.
  • 64. © 2003 Prentice Hall, Inc. All rights reserved. Outline 64 120 // print a message indicating password is invalid 121 function wrongPassword() 122 { 123 print( "<title>Access Denied</title></head> 124 <body style = "font-family: arial; 125 font-size: 1em; color: red"> 126 <strong>You entered an invalid 127 password.<br />Access has 128 been denied.</strong>" ); 129 } 130 131 // print a message indicating access has been denied 132 function accessDenied() 133 { 134 print( "<title>Access Denied</title></head> 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 } 141 password.php (6 of 7) Function wrongPassword prints a message to the client indicating that the password is invalid. Function accessDenied prints a message to the client indicating that access has been denied.
  • 65. © 2003 Prentice Hall, Inc. All rights reserved. Outline 65 142 // print a message indicating that fields 143 // have been left blank 144 function fieldsBlank() 145 { 146 print( "<title>Access Denied</title></head> 147 <body style = "font-family: arial; 148 font-size: 1em; color: red"> 149 <strong> 150 Please fill in all form fields. 151 <br /></strong>" ); 152 } 153 ?> 154 </body> 155 </html> password.php (7 of 7) Function fieldsBlank prints a message to the client indicating that all form fields have not been completed.
  • 66. © 2003 Prentice Hall, Inc. All rights reserved. 66 26.6 Verifying a Username and Password Fig. 26.16 Verifying a username and password.
  • 67. © 2003 Prentice Hall, Inc. All rights reserved. Outline 67 password.txt (1 of 1) 1 account1,password1 2 account2,password2 3 account3,password3 4 account4,password4 5 account5,password5 6 account6,password6 7 account7,password7 8 account8,password8 9 account9,password9 10 account10,password10
  • 68. © 2003 Prentice Hall, Inc. All rights reserved. 68 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
  • 69. © 2003 Prentice Hall, Inc. All rights reserved. Outline 69 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 --> 5 <!-- Querying a MySQL Database --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample Database Query</title> 10 </head> 11 12 <body style = "background-color: #F0E68C"> 13 <h2 style = "font-family: arial color: blue"> 14 Querying a MySQL database. 15 </h2> 16 17 <form method = "post" action = "database.php"> 18 <p>Select a field to display: 19 20 <!-- add a select box containing options --> 21 <!-- for SELECT query --> data.html (1 of 2)
  • 70. © 2003 Prentice Hall, Inc. All rights reserved. Outline 70 22 <select name = "select"> 23 <option selected = "selected">*</option> 24 <option>ID</option> 25 <option>Title</option> 26 <option>Category</option> 27 <option>ISBN</option> 28 </select> 29 </p> 30 31 <input type = "submit" value = "Send Query" 32 style = "background-color: blue; 33 color: yellow; font-weight: bold" /> 34 </form> 35 </body> 36 </html> data.html (2 of 2) Select box containing options for a SELECT query.
  • 71. © 2003 Prentice Hall, Inc. All rights reserved. 71 26.7 Connecting to a Database Fig. 26.18 Form to query a MySQL database.
  • 72. © 2003 Prentice Hall, Inc. All rights reserved. 72 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
  • 73. © 2003 Prentice Hall, Inc. All rights reserved. Outline 73 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.19: database.php --> 5 <!-- Program to query a database and --> 6 <!-- send results to the client. --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Search Results</title> 11 </head> 12 13 <body style = "font-family: arial, sans-serif" 14 style = "background-color: #F0E68C"> 15 <?php 16 17 extract( $_POST ); 18 19 // build SELECT query 20 $query = "SELECT " . $select . " FROM Books"; 21 22 // Connect to MySQL 23 if ( !( $database = mysql_connect( "localhost", 24 "httpd", "" ) ) ) 25 die( "Could not connect to database" ); database.php (1 of 3) Build the select query and assign the string to variable $query. Function mysql_connect returns a database handle which represents PHP’s connection to a database. If this connection is not made, function die is called to terminate script execution.
  • 74. © 2003 Prentice Hall, Inc. All rights reserved. Outline 74 26 27 // open Products database 28 if ( !mysql_select_db( "Products", $database ) ) 29 die( "Could not open Products database" ); 30 31 // query Products database 32 if ( !( $result = mysql_query( $query, $database ) ) ) { 33 print( "Could not execute query! <br />" ); 34 die( mysql_error() ); 35 } 36 ?> 37 38 <h3 style = "color: blue"> 39 Search Results</h3> 40 41 <table border = "1" cellpadding = "3" cellspacing = "2" 42 style = "background-color: #ADD8E6"> 43 44 <?php 45 46 // fetch each record in result set 47 for ( $counter = 0; 48 $row = mysql_fetch_row( $result ); 49 $counter++ ){ 50 database.php (2 of 3) Function mysql_select_db is called to specify the database to be queried. Function mysql_query returns an object containing the result set of the query, which we assign to variable $result. The for loop iterates through each record in the result set while constructing an XHTML table from the results. Variable $counter is incremented by one for each row retrieved. Function mysql_fetch_row returns an array containing the elements of each row in the result set of our query ($result).
  • 75. © 2003 Prentice Hall, Inc. All rights reserved. Outline 75 51 // build table to display results 52 print( "<tr>" ); 53 54 foreach ( $row as $key => $value ) 55 print( "<td>$value</td>" ); 56 57 print( "</tr>" ); 58 } 59 60 mysql_close( $database ); 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 69 <a href = "mailto:[email protected]"> 70 Deitel and Associates, Inc. 71 </a> 72 </h5> 73 74 </body> 75 </html> database.php (3 of 3) The foreach loop iterates through the array containing the elements of each row and prints out each element in an individual table cell. The total number of results are printed to the client.
  • 76. © 2003 Prentice Hall, Inc. All rights reserved. 76 26.7 Connecting to a Database Fig. 26.19 Querying a database and displaying the results.
  • 77. © 2003 Prentice Hall, Inc. All rights reserved. 77 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
  • 78. © 2003 Prentice Hall, Inc. All rights reserved. Outline 78 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 --> 6 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Writing a cookie to the client computer</title> 10 </head> 11 12 <body style = "font-family: arial, sans-serif; 13 background-color: #99CCFF"> 14 15 <h2>Click Write Cookie to save your cookie data.</h2> 16 cookies.html (1 of 2)
  • 79. © 2003 Prentice Hall, Inc. All rights reserved. Outline 79 17 <form method = "post" action = "cookies.php" 18 style = "font-size: 10pt"> 19 <strong>Name:</strong><br /> 20 <input type = "text" name = "NAME" /><br /> 21 22 <strong>Height:</strong><br /> 23 <input type = "text" name = "HEIGHT" /><br /> 24 25 <strong>Favorite Color:</strong><br /> 26 <input type = "text" name = "COLOR" /><br /> 27 28 <input type = "submit" value = "Write Cookie" 29 style = "background-color: #F0E86C; color: navy; 30 font-weight: bold" /></p> 31 </form> 32 </body> 33 </html> cookies.html (2 of 2) Form data is posted to cookies.php.
  • 80. © 2003 Prentice Hall, Inc. All rights reserved. 80 26.8 Cookies Fig. 26.20 Gathering data to be written as a cookie.
  • 81. © 2003 Prentice Hall, Inc. All rights reserved. Outline 81 1 <?php 2 // Fig. 26.21: cookies.php 3 // Program to write a cookie to a client's machine 4 5 extract( $_POST ); 6 // write each form field’s value to a cookie and set the 7 // cookie’s expiration date 8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); 9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); 10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 ); 11 ?> 12 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 15 16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 <head> 18 <title>Cookie Saved</title> 19 </head> 20 21 <body style = "font-family: arial, sans-serif"> 22 <p>The cookie has been set with the following data:</p> 23 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 cookie. The optional third argument specifies the expiration date of the cookie.
  • 82. © 2003 Prentice Hall, Inc. All rights reserved. Outline 82 24 <!-- print each form field’s value --> 25 <br /><span style = "color: blue">Name:</span> 26 <?php print( $NAME ) ?><br /> 27 28 <span style = "color: blue">Height:</span> 29 <?php print( $HEIGHT ) ?><br /> 30 31 <span style = "color: blue">Favorite Color:</span> 32 33 <span style = "color: <?php print( "$COLOR">$COLOR" ) ?> 34 </span><br /> 35 <p>Click <a href = "readCookies.php">here</a> 36 to read the saved cookie.</p> 37 </body> 38 </html> cookies.php (2 of 2) Each form field’s value is printed to confirm the data that has been set as a cookie with the user. Hyperlink to readCookies.php.
  • 83. © 2003 Prentice Hall, Inc. All rights reserved. 83 26.8 Cookies Fig. 26.21 Writing a cookie to the client.
  • 84. © 2003 Prentice Hall, Inc. All rights reserved. 84 26.8 Cookies • Reading cookies – $_COOKIE environment variable • Array – foreach loop to access each element • Split into key and value
  • 85. © 2003 Prentice Hall, Inc. All rights reserved. 85 26.8 Cookies • Cookie storage – Internet Explorer • Stores cookies in Cookies directory • Text file
  • 86. © 2003 Prentice Hall, Inc. All rights reserved. 86 26.8 Cookies Fig. 26.22 Cookies directory before a cookie is written. Fig. 26.23 Cookies directory after a cookie is written.
  • 87. © 2003 Prentice Hall, Inc. All rights reserved. Outline 87 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 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 <p> 13 <strong> 14 The following data is saved in a cookie on your 15 computer. 16 </strong> 17 </p> 18 readCookies.php (1 of 2)
  • 88. © 2003 Prentice Hall, Inc. All rights reserved. Outline 88 19 <table border = "5" cellspacing = "0" cellpadding = "10"> 20 <?php 21 22 // iterate through array $_COOKIE and print 23 // name and value of each cookie 24 foreach ( $_COOKIE as $key => $value ) 25 print( "<tr> 26 <td bgcolor="#F0E68C">$key</td> 27 <td bgcolor="#FFA500">$value</td> 28 </tr>" ); 29 ?> 30 31 </table> 32 </body> 33 </html> readCookies.php (2 of 2) PHP creates array $_COOKIE which contains all cookie values indexed by their names. The foreach loop iterates through the $_COOKIE array and prints the name and value of each cookie in an XHTML table.
  • 89. © 2003 Prentice Hall, Inc. All rights reserved. 89 26.8 Cookies Fig. 26.24 Displaying the cookie’s content.
  • 90. © 2003 Prentice Hall, Inc. All rights reserved. 90 26.9 Dynamic Content in PHP • Dynamically alter XHTML content – Form’s 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
  • 91. © 2003 Prentice Hall, Inc. All rights reserved. Outline 91 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 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample form to take user input in XHTML</title> 10 </head> 11 12 <body> 13 <?php 14 extract ( $_POST ); 15 $iserror = false; 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 dynamicForm.php (1 of 9) Build array of options for the form.
  • 92. © 2003 Prentice Hall, Inc. All rights reserved. Outline 92 23 // array of possible operating systems 24 $systemlist = array( "Windows XP", 25 "Windows 2000", 26 "Windows 98", 27 "Linux", 28 "Other"); 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" => "Phone" ); 35 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 dynamicForm.php (2 of 9) Check for errors or omissions in form field input. If the page is being loaded as a result of a form submission, do error checking and then retrieve information from the database.
  • 93. © 2003 Prentice Hall, Inc. All rights reserved. Outline 93 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 if ( !$iserror ) { 58 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" ); dynamicForm.php (3 of 9) If there were no errors, query the MySQL database.
  • 94. © 2003 Prentice Hall, Inc. All rights reserved. Outline 94 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 } 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> dynamicForm.php (4 of 9)
  • 95. © 2003 Prentice Hall, Inc. All rights reserved. Outline 95 98 <td bgcolor = '#ffffdd'>OS</td> 99 </tr> 100 <tr> 101 102 <!-- print each form field’s value --> 103 <td>$fname $lname</td> 104 <td>$email</td> 105 <td>$phone</td> 106 <td>$os</td> 107 </tr></table> 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>" ); 117 die(); 118 } 119 } 120 121 print( "<h1>This is a sample registration form.</h1> 122 Please fill in all fields and click Register." ); dynamicForm.php (5 of 9) Halt the script so the form-generation code does not execute.
  • 96. © 2003 Prentice Hall, Inc. All rights reserved. Outline 96 123 124 if ( $iserror ) { 125 print( "<br /><span style = 'color : red'> 126 Fields with * need to be filled in properly.</span>" ); 127 } 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 136 <!-- create four text boxes for user input -->" ); 137 foreach ( $inputlist as $inputname => $inputalt ) { 138 $inputtext = $inputvalues[ $inputname ]; 139 140 print( "<img src = 'images/$inputname.gif' 141 alt = '$inputalt' /><input type = 'text' 142 name = '$inputname' value = '" . $$inputname . "' />" ); 143 144 if ( $formerrors[ ( $inputname )."error" ] == true ) 145 print( "<span style = 'color : red'>*</span>" ); 146 147 print( "<br />" ); 148 } dynamicForm.php (6 of 9) If the form input contained errors, place a red asterisk (*) next to the text field. Fill in the forms using $$variable syntax.
  • 97. © 2003 Prentice Hall, Inc. All rights reserved. Outline 97 149 150 print( "<span style = 'font-size : 10pt" ); 151 152 if ( $formerrors[ "phoneerror" ] ) 153 print( "; color : red" ); 154 155 print( "'>Must be in the form (555)555-5555 156 </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 foreach ( $booklist as $currbook ) { 169 print( "<option" ); 170 171 if ( ( $currbook == $book ) ) 172 print( " selected = 'true'" ); 173 dynamicForm.php (7 of 9) Make sure the correct book is selected in the dropdown box.
  • 98. © 2003 Prentice Hall, Inc. All rights reserved. Outline 98 174 print( ">$currbook</option>" ); 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> 182 183 <!-- create five radio buttons -->" ); 184 185 $counter = 0; 186 187 foreach ( $systemlist as $currsystem ) { 188 print( "<input type = 'radio' name = 'os' 189 value = '$currsystem'" ); 190 191 if ( $currsystem == $os ) print( "checked = 'checked'" ); 192 if ( $iserror && $counter == 0 ) print( "checked = 'checked'" ); 193 194 print( " />$currsystem" ); 195 196 if ( $counter == 2 ) print( "<br />" ); 197 $counter++; 198 } 199 dynamicForm.php (8 of 9) Make sure the correct OS is checked in the checkbox.
  • 99. © 2003 Prentice Hall, Inc. All rights reserved. Outline 99 200 print( "<!-- create a submit button --> 201 <br /> 202 <input type = 'submit' name = 'submit' value = 'Register' /> 203 </form></body></html>" ); 204 ?> dynamicForm.php (9 of 9)
  • 100. © 2003 Prentice Hall, Inc. All rights reserved. 100 26.9 Dynamic Content in PHP Fig. 26.25 Dynamic form using PHP.
  • 101. © 2003 Prentice Hall, Inc. All rights reserved. 101 26.9 Dynamic Content in PHP Fig. 26.25 Dynamic form using PHP.
  • 102. © 2003 Prentice Hall, Inc. All rights reserved. Outline 102 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. --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Search Results</title> 11 </head> 12 13 <body style = "font-family: arial, sans-serif" 14 style = "background-color: #F0E68C"> 15 <?php 16 17 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" ); formDatabase.php (1 of 3) Build the query string.
  • 103. © 2003 Prentice Hall, Inc. All rights reserved. Outline 103 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 ?> 37 38 <h3 style = "color: blue"> 39 Mailing List Contacts</h3> 40 41 <table border = "1" cellpadding = "3" cellspacing = "2" 42 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> formDatabase.php (2 of 3)
  • 104. © 2003 Prentice Hall, Inc. All rights reserved. Outline 104 51 <td>Operating System</td> 52 </tr> 53 <?php 54 55 // fetch each record in result set 56 for ( $counter = 0; 57 $row = mysql_fetch_row( $result ); 58 $counter++ ){ 59 60 // build table to display results 61 print( "<tr>" ); 62 63 foreach ( $row as $key => $value ) 64 print( "<td>$value</td>" ); 65 66 print( "</tr>" ); 67 } 68 69 mysql_close( $database ); 70 ?> 71 72 </table> 73 74 </body> 75 </html> formDatabase.php (3 of 3) Dynamically create a table containing each mailing list member. Retrieve each mailing list member record from the database.
  • 105. © 2003 Prentice Hall, Inc. All rights reserved. 105 26.9 Dynamic Content in PHP Fig. 26.26 Displaying the MailingList database.
  • 106. © 2003 Prentice Hall, Inc. All rights reserved. 106 26.10 Operator Precedence 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 << >> bitwise shift left bitwise shift right left to right < > <= >= less than greater than less than or equal greater than or equal none == != === !== equal not equal identical not identical none Fig. 26.27 PHP operator precedence and associativity.
  • 107. © 2003 Prentice Hall, Inc. All rights reserved. 107 26.10 Operator Precedence Operator Type Associativity & 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 = += -= *= /= &= |= ^= .= <<= >>= 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 left to right and logical AND left to right xor exclusive OR left to right or logical OR left to right , list left to right Fig. 26.27 PHP operator precedence and associativity.