Top Banner
1 2008 Pearson Education, Inc. All rights rese 2 3 PHP
95

2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

Dec 26, 2015

Download

Documents

Belinda Cannon
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

1

2008 Pearson Education, Inc. All rights reserved.

2323

PHP

Page 2: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

2

2008 Pearson Education, Inc. All rights reserved.

Page 3: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

3

2008 Pearson Education, Inc. All rights reserved.

Conversion for me was not a Damascus Road experience. I slowly moved into a intellectual acceptance of what my intuition had always known.

— Madeleine L’Engle

Be careful when reading health books;you may die of a misprint.

— Mark Twain

Page 4: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

4

2008 Pearson Education, Inc. All rights reserved.

Reckoners without their host must reckon twice.— John Heywood

There was a door to which I found no key; There was the veil through which I might not see.

— Omar Khayyam

Page 5: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

5

2008 Pearson Education, Inc. All rights reserved.

OBJECTIVES

In this chapter you will learn: To manipulate data of various types. To use operators, arrays and control statements. To use regular expressions to search for patterns. To construct programs that process form data. To store data on the client using cookies. To create programs that interact with MySQL

databases.

Page 6: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

6

2008 Pearson Education, Inc. All rights reserved.

23.1 Introduction

23.2   PHP Basics

23.3   String Processing and Regular Expressions

23.3.1  Comparing Strings

23.3.2  Regular Expressions

23.4   Form Processing and Business Logic

23.5   Connecting to a Database

23.6   Using Cookies

23.7   Dynamic Content

23.8   Operator Precedence Chart

23.9   Wrap-Up

23.10 Web Resources

Page 7: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

7

2008 Pearson Education, Inc. All rights reserved.

23.1 Introduction

• PHP, or PHP: Hypertext Preprocessor, has become one of the most popular server-side scripting languages for creating dynamic web pages.

• PHP is open source and platform independent—implementations exist for all major UNIX, Linux, Mac and Windows operating systems. PHP also supports a large number of databases.

Page 8: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

8

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics

• The power of the web resides not only in serving content to users, but also in responding to requests from users and generating web pages with dynamic content.

• PHP code is embedded directly into XHTML documents, though these script segments are interpreted by a server before being delivered to the client.

• PHP script file names end with .php. • Although PHP can be used from the command line, a web server is

necessary to take full advantage of the scripting language.• In PHP, code is inserted between the scripting delimiters <?php

and ?>. PHP code can be placed anywhere in XHTML markup, as long as the code is enclosed in these delimiters.

Page 9: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

9

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics (Cont.)

• Variables are preceded by a $ and are created the first time they are encountered.

• PHP statements terminate with a semicolon (;). • Single-line comments which begin with two forward slashes (//) or a

pound sign (#). Text to the right of the delimiter is ignored by the interpreter. Multiline comments begin with delimiter /* and end with delimiter */.

• When a variable is encountered inside a double-quoted ("") string, PHP interpolates the variable. In other words, PHP inserts the variable’s value where the variable name appears in the string.

• All operations requiring PHP interpolation execute on the server before the XHTML document is sent to the client.

• PHP variables are loosely typed—they can contain different types of data at different times.

Page 10: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

10

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

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

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

4

5 <!-- Fig. 23.1: first.php -->

6 <!-- Simple PHP program. -->

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

8 <?php

9 $name = "Harvey"; // declaration and initialization

10 ?><!-- end PHP script -->

11 <head>

12 <title>Using PHP document</title>

13 </head>

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

15 <p>

16 <strong>

17 <!-- print variable name’s value -->

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

19 </strong>

20 </p>

21 </body>

22 </html>

Outline

first.php Delimiters enclosing PHP script

Declares and initializes a PHP variable

Interpolates the variable so that its value will be output to the XHTML document

Page 11: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

11

2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.1

Failing to precede a variable namewith a $ is a syntax error.

Page 12: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

12

2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.2

Variable names in PHP are case sensitive. Failure to use the proper mixture of cases to refer to a variable will result in a logic error, since the script will create a new variable for any name it doesn’t recognize as a previously used variable.

Page 13: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

13

2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.3

Forgetting to terminate a statementwith a semicolon (;) is a syntax error.

Page 14: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

14

2008 Pearson Education, Inc. All rights reserved.

Type Description

int, integer Whole numbers (i.e., numbers without a decimal point).

float, double, real Real numbers (i.e., numbers containing a decimal point).

string Text enclosed in either single ('') or double ("") quotes. [Note: Using double quotes allows PHP to recognize more escape sequences.]

bool, boolean True or false.

array Group of elements.

object Group of associated data and methods.

resource An external source—usually information from a database.

NULL No value.

Fig. 23.2 | PHP types.

Page 15: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

15

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics (Cont.)

• Type conversions can be performed using function settype. This function takes two arguments—a variable whose type is to be changed and the variable’s new type.

• Variables are automatically converted to the type of the value they are assigned.

• Function gettype returns the current type of its argument. • Calling function settype can result in loss of data. For example, doubles are

truncated when they are converted to integers. • When converting from a string to a number, PHP uses the value of the

number that appears at the beginning of the string. If no number appears at the beginning, the string evaluates to 0.

• Another option for conversion between types is casting (or type casting). Casting does not change a variable’s content—it creates a temporary copy of a variable’s value in memory.

• The concatenation operator (.) combines multiple strings.• A print statement split over multiple lines prints all the data that is enclosed

in its parentheses.

Page 16: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

16

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

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

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

4

5 <!-- Fig. 23.3: data.php -->

6 <!-- Data type conversion. -->

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

8 <head>

9 <title>Data type conversion</title>

10 </head>

11 <body>

12 <?php

13 // declare a string, double and integer

14 $testString = "3.5 seconds";

15 $testDouble = 79.2;

16 $testInteger = 12;

17 ?><!-- end PHP script -->

18

19 <!-- print each variable’s value and type -->

20 <?php

21 print( "$testString is a(n) " . gettype( $testString )

22 . "<br />" );

Outline

data.php

(1 of 3)

Automatically declares a string

Automatically declares a double

Automatically declares an integer

Outputs the type of $testString

Page 17: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

17

2008 Pearson Education, Inc. All rights reserved.

23 print( "$testDouble is a(n) " . gettype( $testDouble )

24 . "<br />" );

25 print( "$testInteger is a(n) " . gettype( $testInteger)

26 . "<br />" );

27 ?><!-- end PHP script -->

28 <br />

29 converting to other data types:<br />

30 <?php

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

Outline

data.php

(2 of 3)

Modifies $testString to be a double

Modifies $testString to be an integer

Modifies $testString to be a string

Page 18: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

18

2008 Pearson Education, Inc. All rights reserved.

43 // use type casting to cast variables to a different type

44 $data = "98.6 degrees";

45 print( "before casting, $data is a " .

46 gettype( $data ) . "<br /><br />" );

47 print( "using type casting instead: <br />

48 as a double: " . (double) $data .

49 "<br />as an integer: " . (integer) $data );

50 print( "<br /><br />after casting, $data is a " .

51 gettype( $data ) );

52 ?><!-- end PHP script -->

53 </body>

54 </html>

Outline

data.php

(3 of 3)

Temporarily casts $data as a double and an integer

Concatenation

Page 19: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

19

2008 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 23.1

Function print can be used to displaythe value of a variable at a particularpoint during a program’s execution.This is often helpful in debugging a script.

Page 20: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

20

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics (Cont.)

• Function define creates a named constant. It takes two arguments—the name and value of the constant. An optional third argument accepts a boolean value that specifies whether the constant is case insensitive—constants are case sensitive by default.

• Uninitialized variables have the value undef, which has different values, depending on its context. In a numeric context, it evaluates to 0. In a string context, it evaluates to an empty string ("").

• Keywords may not be used as identifiers.

Page 21: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

21

2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.4

Assigning a value to a constant afterit is declared is a syntax error.

Page 22: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

22

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.4: operators.php --> 6 <!-- Using arithmetic operators. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Using arithmetic operators</title> 10 </head> 11 <body> 12 <?php 13 $a = 5; 14 print( "The value of variable a is $a <br />" ); 15

16 // define constant VALUE 17 define( "VALUE", 5 ); 18

19 // add constant VALUE to variable $a 20 $a = $a + VALUE; 21 print( "Variable a after adding constant VALUE 22 is $a <br />" ); 23

24 // multiply variable $a by 2 25 $a *= 2; 26 print( "Multiplying variable a by 2 yields $a <br />" ); 27

Outline

operators.php

(1 of 3)

Creates the named constant VALUE with a value of 5

Equivalent to $a = $a * 2

Page 23: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

23

2008 Pearson Education, Inc. All rights reserved.

28 // test if variable $a is less than 50 29 if ( $a < 50 ) 30 print( "Variable a is less than 50 <br />" ); 31

32 // add 40 to variable $a 33 $a += 40; 34 print( "Variable a after adding 40 is $a <br />" ); 35

36 // test if variable $a is 50 or less 37 if ( $a < 51 ) 38 print( "Variable a is still 50 or less<br />" ); 39

40 // test if variable $a is between 50 and 100, inclusive 41 elseif ( $a < 101 ) 42 print( "Variable a is now between 50 and 100, 43 inclusive<br />" ); 44 else 45 print( "Variable a is now greater than 100 <br />" ); 46

47 // print an uninitialized variable 48 print( "Using a variable before initializing: 49 $nothing <br />" ); // nothing evaluates to "" 50

51 // add constant VALUE to an uninitialized variable 52 $test = $num + VALUE; // num evaluates to 0

Outline

operators.php

(2 of 3)Uses a comparison operator with a variable and an integer

Uninitialized variable $num evaluates to 0

Page 24: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

24

2008 Pearson Education, Inc. All rights reserved.

53 print( "An uninitialized variable plus constant

54 VALUE yields $test <br />" );

55

56 // add a string to an integer

57 $str = "3 dollars";

58 $a += $str;

59 print( "Adding a string to variable a yields $a <br />" );

60 ?><!-- end PHP script -->

61 </body>

62 </html>

Outline

operators.php

(3 of 3)

$str is converted to an integer for this operation

Page 25: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

25

2008 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 23.2

Initialize variables before they are usedto avoid subtle errors. For example, multiplying a number by an uninitialized variable results in 0.

Page 26: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

26

2008 Pearson Education, Inc. All rights reserved.

PHP keywords

abstract die exit interface require and do extends isset require_once array echo __FILE__ __LINE__ return as else file line static break elseif final list switch case empty for __METHOD__ throw catch enddeclare foreach method try __CLASS__ endfor __FUNCTION__ new unset

class endforeach function or use clone endif global php_user_filter var

const endswitch if print while continue endwhile implements private xor declare eval include protected default exception include_once public

Fig. 23.5 | PHP keywords.

Page 27: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

27

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics (Cont.)

• PHP provides the capability to store data in arrays. Arrays are divided into elements that behave as individual variables. Array names, like other variables, begin with the $ symbol.

• Individual array elements are accessed by following the array’s variable name with an index enclosed in square brackets ([]).

• If a value is assigned to an array that does not exist, then the array is created. Likewise, assigning a value to an element where the index is omitted appends a new element to the end of the array.

• Function count returns the total number of elements in the array. • Function array creates an array that contains the arguments passed

to it. The first item in the argument list is stored as the first array element (index 0), the second item is stored as the second array element and so on.

Page 28: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

28

2008 Pearson Education, Inc. All rights reserved.

23.2 PHP Basics (Cont.)

• Arrays with nonnumeric indices are called associative arrays. You can create an associative array using the operator =>, where the value to the left of the operator is the array index and the value to the right is the element’s value.

• PHP provides functions for iterating through the elements of an array. Each array has a built-in internal pointer, which points to the array element currently being referenced. Function reset sets the internal pointer to the first array element. Function key returns the index of the element currently referenced by the internal pointer, and function next moves the internal pointer to the next element.

• The foreach statement, designed for iterating through arrays, starts with the array to iterate through, followed by the keyword as, followed by two variables—the first is assigned the index of the element and the second is assigned the value of that index’s element. (If only one variable is listed after as, it is assigned the value of the array element.)

Page 29: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

29

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.6: arrays.php --> 6 <!-- Array manipulation. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Array manipulation</title> 10 </head> 11 <body> 12 <?php 13 // create array first 14 print( "<strong>Creating the first array</strong><br />" ); 15 $first[ 0 ] = "zero"; 16 $first[ 1 ] = "one"; 17 $first[ 2 ] = "two"; 18 $first[] = "three"; 19

20 // print each element’s index and value 21 for ( $i = 0; $i < count( $first ); $i++ ) 22 print( "Element $i is $first[$i] <br />" ); 23

Outline

arrays.php

(1 of 4)

Sets the first element of array $first to the string “zero”

Automatically creates array $first

“three” is appended to the end of array $first

Returns the number of elements in the array

Page 30: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

30

2008 Pearson Education, Inc. All rights reserved.

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

25 </strong><br />" );

26

27 // call function array to create array second

28 $second = array( "zero", "one", "two", "three" );

29

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

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

32

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

34 </strong><br />" );

35

36 // assign values to entries using nonnumeric indices

37 $third[ "Amy" ] = 21;

38 $third[ "Bob" ] = 18;

39 $third[ "Carol" ] = 23;

40

41 // iterate through the array elements and print each

42 // element’s name and value

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

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

45

Outline

arrays.php

(2 of 4)

Function array creates array $second with its arguments as elements

Creates associative array $third

Sets the internal pointer to the first array element in $third

Returns the index of the element being pointed to

Moves the internal pointer to the next element and returns it

Page 31: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

31

2008 Pearson Education, Inc. All rights reserved.

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

47 </strong><br />" );

48

49 // call function array to create array fourth using

50 // string indices

51 $fourth = array(

52 "January" => "first", "February" => "second",

53 "March" => "third", "April" => "fourth",

54 "May" => "fifth", "June" => "sixth",

55 "July" => "seventh", "August" => "eighth",

56 "September" => "ninth", "October" => "tenth",

57 "November" => "eleventh","December" => "twelfth"

58 );

59

60 // print each element’s name and value

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

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

63 ?><!-- end PHP script -->

64 </body>

65 </html>

Outline

arrays.php

(3 of 4)

Uses operator => to initialize the element with index “January” to have value “first”

Iterates through each element in array $fourth

Stores the index of the element

Stores the value of the element

Page 32: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

32

2008 Pearson Education, Inc. All rights reserved.

Outline

arrays.php

(4 of 4)

Page 33: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

33

2008 Pearson Education, Inc. All rights reserved.

23.3 String Processing and Regular Expressions

• A regular expression is a series of characters used for pattern-matching templates in strings, text files and databases.

• Many string-processing tasks can be accomplished using the equality and relational operators (==, !=, <, <=, > and >=).

• Function strcmp compares two strings. The function returns -1 if the first string alphabetically precedes the second string, 0 if the strings are equal, and 1 if the first string alphabetically follows the second.

Page 34: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

34

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.7: compare.php --> 6 <!-- Using the string-comparison operators. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>String Comparison</title> 10 </head> 11 <body> 12 <?php 13 // create array fruits 14 $fruits = array( "apple", "orange", "banana" ); 15

16 // iterate through each array element 17 for ( $i = 0; $i < count( $fruits ); $i++ ) 18 { 19 // call function strcmp to compare the array element 20 // to string "banana" 21 if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) 22 print( $fruits[ $i ] . " is less than banana " ); 23 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) 24 print( $fruits[ $i ] . " is greater than banana " ); 25 else 26 print( $fruits[ $i ] . " is equal to banana " ); 27

28 // use relational operators to compare each element 29 // to string "apple"

Outline

compare.php

(1 of 2)

Checks whether the ith element of the fruits array preceeds the string banana

Page 35: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

35

2008 Pearson Education, Inc. All rights reserved.

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

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

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

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

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

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

36 } // end for

37 ?><!-- end PHP script -->

38 </body>

39 </html>

Outline

compare.php

(2 of 2)

Uses relational operators to compare the element of the fruits array with the string apple

Page 36: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

36

2008 Pearson Education, Inc. All rights reserved.

23.3 String Processing and Regular Expressions (Cont.)

• Functions ereg and preg_match use regular expressions to search a string for a specified pattern.

• If a pattern is found using ereg, it returns the length of the matched string—which evaluates to true in a boolean context.

• Anything enclosed in single quotes in a print statement is not interpolated (unless the single quotes are nested in a double-quoted string literal).

• Function ereg receives a regular expression pattern to search for and the string to search.

• Function eregi performs case-insensitive pattern matches.• Regular expressions can include metacharacters that specify patterns. For

example, the caret (^) metacharacter matches the beginning of a string, while the dollar sign ($) matches the end of a string. The period (.) metacharacter matches any single character.

• Bracket expressions are lists of characters enclosed in square brackets ([]) that match any single character from the list. Ranges can be specified by supplying the beginning and the end of the range separated by a dash (-).

Page 37: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

37

2008 Pearson Education, Inc. All rights reserved.

23.3 String Processing and Regular Expressions (Cont.)

• The special bracket expressions [[:<:]] and [[:>:]] match the beginning and end of a word, respectively.

• Quantifiers are used in regular expressions to denote how often a particular character or set of characters can appear in a match.

• The optional third argument to function ereg is an array that stores matches to each parenthetical statement of the regular expression. The first element stores the string matched for the entire pattern, and the remaining elements are indexed from left to right.

• To find multiple instances of a given pattern, we must make multiple calls to ereg, and remove matched instances before calling the function again by using a function such as ereg_replace.

• Character classes, or sets of specific characters, are enclosed by the delimiters [: and :]. When this expression is placed in another set of brackets, it is a regular expression matching all of the characters in the class.

• A bracketed expression containing two or more adjacent character classes in the class delimiters represents those character sets combined.

• Function ereg_replace takes three arguments—the pattern to match, a string to replace the matched string and the string to search. The modified string is returned.

Page 38: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

38

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.8: expression.php --> 6 <!-- Regular expressions. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Regular expressions</title> 10 </head> 11 <body> 12 <?php 13 $search = "Now is the time"; 14 print( "Test string is: '$search'<br /><br />" ); 15

16 // call ereg to search for pattern 'Now' in variable search 17 if ( ereg( "Now", $search ) ) 18 print( "String 'Now' was found.<br />" ); 19

20 // search for pattern 'Now' in the beginning of the string 21 if ( ereg( "^Now", $search ) ) 22 print( "String 'Now' found at beginning 23 of the line.<br />" ); 24

25 // search for pattern 'Now' at the end of the string 26 if ( ereg( "Now$", $search ) ) 27 print( "String 'Now' was found at the end 28 of the line.<br />" ); 29

Outline

expression.php

(1 of 2)

String to search

Searches for the string “Now” in $search

Checks if string “Now” appears at the beginning of $search

Checks if string “Now” appears at the end of $search

Page 39: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

39

2008 Pearson Education, Inc. All rights reserved.

30 // search for any word ending in 'ow'

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

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

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

34

35 // search for any words beginning with 't'

36 print( "Words beginning with 't' found: ");

37

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

39 $search, $match ) )

40 {

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

42

43 // remove the first occurrence of a word beginning

44 // with 't' to find other instances in the string

45 $search = ereg_replace( $match[ 1 ], "", $search );

46 } // end while

47 ?><!-- end PHP script -->

48 </body>

49 </html>

Outline

expression.php

(2 of 2)

Searches for a word ending in “ow” and stores matches in $match array

Prints first encountered instance of word ending in “ow”

Performs a case-insensitive search for words beginning with the letter “t”

Replaces the found instance from the previous call to eregi with an empty string so that the next instance of the pattern can be found and stored in $match

Page 40: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

40

2008 Pearson Education, Inc. All rights reserved.

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. 23.9 | Some PHP quantifiers.

Page 41: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

41

2008 Pearson Education, Inc. All rights reserved.

Character class Description

alnum Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]).

alpha Word characters (i.e., letters [a-zA-Z]).

digit Digits.

space White space.

lower Lowercase letters.

upper Uppercase letters.

Fig. 23.10 | Some PHP character classes.

Page 42: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

42

2008 Pearson Education, Inc. All rights reserved.

23.4 Form Processing and Business Logic

• Superglobal arrays are associative arrays predefined by PHP that hold variables acquired from user input, the environment or the web server and are accessible in any variable scope.

• The arrays $_GET and $_POST retrieve information sent to the server by HTTP get and post requests, respectively.

• Using method = "post" appends form data to the browser request that contains the protocol and the requested resource’s URL. Scripts located on the web server’s machine can access the form data sent as part of the request.

Page 43: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

43

2008 Pearson Education, Inc. All rights reserved.

Variable name Description

$_SERVER Data about the currently running server.

$_ENV Data about the client’s environment.

$_GET Data sent to the server by a get request.

$_POST Data sent to the server by a post request.

$_COOKIE Data contained in cookies on the client’s computer.

$GLOBALS Array containing all global variables.

Fig. 23.11 | Some useful superglobal arrays.

Page 44: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

44

2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.12: form.html --> 6 <!-- XHTML form for gathering user input. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample form to take user input in XHTML</title> 10 <style type = "text/css"> 11 .prompt { color: blue; 12 font-family: sans-serif; 13 font-size: smaller } 14 </style> 15 </head> 16 <body> 17 <h1>Sample Registration Form</h1> 18 <p>Please fill in all fields and click Register.</p> 19

20 <!-- post form data to form.php --> 21 <form method = "post" action = "form.php"> 22 <div> 23 <img src = "images/user.gif" alt = "User" /><br /> 24 <span class = "prompt"> 25 Please fill out the fields below.<br /> 26 </span> 27

Outline

form.html

(1 of 4)

Appends form data to the browser request that contains the protocol and the URL of the requested resource

Form data is posted to form.php to be processed

Page 45: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

45

2008 Pearson Education, Inc. All rights reserved.

28 <!-- create four text boxes for user input --> 29 <img src = "images/fname.gif" alt = "First Name" /> 30 <input type = "text" name = "fname" /><br /> 31

32 <img src = "images/lname.gif" alt = "Last Name" /> 33 <input type = "text" name = "lname" /><br /> 34

35 <img src = "images/email.gif" alt = "Email" /> 36 <input type = "text" name = "email" /><br /> 37

38 <img src = "images/phone.gif" alt = "Phone" /> 39 <input type = "text" name = "phone" /><br /> 40

41 <span style = "font-size: 10pt"> 42 Must be in the form (555)555-5555</span> 43 <br /><br /> 44

45 <img src = "images/downloads.gif" 46 alt = "Publications" /><br /> 47

48 <span class = "prompt"> 49 Which book would you like information about? 50 </span><br /> 51

52 <!-- create drop-down list containing book names --> 53 <select name = "book">

Outline

form.html

(2 of 4)

Creates form fields

Creates drop-down list with book names

Page 46: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

46

2008 Pearson Education, Inc. All rights reserved.

54 <option>Internet and WWW How to Program 4e</option> 55 <option>C++ How to Program 6e</option> 56 <option>Java How to Program 7e</option> 57 <option>Visual Basic 2005 How to Program 3e</option> 58 </select> 59 <br /><br /> 60

61 <img src = "images/os.gif" alt = "Operating System" /> 62 <br /><span class = "prompt"> 63 Which operating system are you currently using? 64 <br /></span> 65

66 <!-- create five radio buttons --> 67 <input type = "radio" name = "os" value = "Windows XP" 68 checked = "checked" /> Windows XP 69 <input type = "radio" name = "os" value = 70 "Windows Vista" /> Windows Vista<br /> 71 <input type = "radio" name = "os" value = 72 "Mac OS X" /> Mac OS X 73 <input type = "radio" name = "os" value = "Linux" /> Linux 74 <input type = "radio" name = "os" value = "Other" /> 75 Other<br /> 76

Outline

form.html

(3 of 4)

Creates radio buttons with “Windows XP” initially selected

Page 47: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

47

2008 Pearson Education, Inc. All rights reserved.

77 <!-- create a submit button -->

78 <input type = "submit" value = "Register" />

79 </div>

80 </form>

81 </body>

82 </html>

Outline

form.html

(4 of 4)

Page 48: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

48

2008 Pearson Education, Inc. All rights reserved.

Good Programming Practice 23.1

Use meaningful XHTML object names for input fields. This makes PHP scripts that retrieve form data easier to understand.

Page 49: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

49

2008 Pearson Education, Inc. All rights reserved.

23.4 Form Processing and Business Logic (Cont.)

• Function extract creates a variable/value pair corresponding to each key/value pair in the associative array passed as an argument.

• Business logic, or business rules, ensures that only valid information is stored in databases.

• We escape the normal meaning of a character in a string by preceding it with the backslash character (\).

• Function die terminates script execution. The function’s optional argument is a string, which is printed as the script exits.

Page 50: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

50

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.13: form.php --> 6 <!-- Process information sent from form.html. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Form Validation</title> 10 <style type = "text/css"> 11 body { font-family: arial, sans-serif } 12 div { font-size: 10pt; 13 text-align: center } 14 table { border: 0 } 15 td { padding-top: 2px; 16 padding-bottom: 2px; 17 padding-left: 10px; 18 padding-right: 10px } 19 .error { color: red } 20 .distinct { color: blue } 21 .name { background-color: #ffffaa } 22 .email { background-color: #ffffbb } 23 .phone { background-color: #ffffcc } 24 .os { background-color: #ffffdd } 25 </style> 26 </head> 27 <body>

Outline

form.php

(1 of 5)

Page 51: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

51

2008 Pearson Education, Inc. All rights reserved.

28 <?php 29 extract( $_POST ); 30

31 // determine whether phone number is valid and print 32 // an error message if not 33 if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) 34 { 35 print( "<p><span class = 'error'> 36 Invalid phone number</span><br /> 37 A valid phone number must be in the form 38 <strong>(555)555-5555</strong><br /> 39 <span class = 'distinct'> 40 Click the Back button, enter a valid phone 41 number and resubmit.<br /><br /> 42 Thank You.</span></p>" ); 43 die( "</body></html>" ); // terminate script execution 44 } 45 ?><!-- end PHP script --> 46 <p>Hi 47 <span class = "distinct"> 48 <strong><?php print( "$fname" ); ?></strong> 49 </span>. 50 Thank you for completing the survey.<br /> 51 You have been added to the 52 <span class = "distinct"> 53 <strong><?php print( "$book " ); ?></strong> 54 </span> 55 mailing list.

Outline

form.php

(2 of 5)

Creates a variable/value pair for each key/value pair in $_POST

Ensures that phone number is in proper format

Terminates execution and closes the document properly

Page 52: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

52

2008 Pearson Education, Inc. All rights reserved.

56 </p> 57 <p><strong>The following information has been saved 58 in our database:</strong></p> 59 <table> 60 <tr> 61 <td class = "name">Name </td> 62 <td class = "email">Email</td> 63 <td class = "phone">Phone</td> 64 <td class = "os">OS</td> 65 </tr> 66 <tr> 67 <?php 68 // print each form field’s value 69 print( "<td>$fname $lname</td> 70 <td>$email</td> 71 <td>$phone</td> 72 <td>$os</td>" ); 73 ?><!-- end PHP script --> 74 </tr> 75 </table> 76 <br /><br /><br /> 77 <div>This is only a sample form. 78 You have not been added to a mailing list.</div> 79 </body> 80 </html>

Outline

form.php

(3 of 5)

Prints the value entered in the email field in form.html

Page 53: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

53

2008 Pearson Education, Inc. All rights reserved.

Outline

form.php

(4 of 5)

Page 54: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

54

2008 Pearson Education, Inc. All rights reserved.

Outline

form.php

(5 of 5)

Page 55: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

55

2008 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 23.1

Use business logic to ensure that invalid information is not stored in databases. When possible, validate important or sensitive form data on the server, since JavaScript may be disabled by the client. Some data, such as passwords, must always be validated on the server side.

Page 56: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

56

2008 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 23.3

Be sure to close any open XHTML tags when calling function die. Not doing so can produce invalid XHTML output that will not display properly in the client browser. Function die has an optional parameter that specifies a message to output when exiting, so one technique for closing tags is to close all open tags using die, as in die("</body></html>").

Page 57: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

57

2008 Pearson Education, Inc. All rights reserved.

23.5 Connecting to a Database

• Function mysql_connect connects to the MySQL database. It takes three arguments—the server’s hostname, a username and a password, and returns a database handle—a representation of PHP’s connection to the database, or false if the connection fails.

• Function mysql_select_db specifies the database to be queried, and returns a bool indicating whether or not it was successful.

• To query the database, we call function mysql_query, specifying the query string and the database to query. This returns a resource containing the result of the query, or false if the query fails. It can also execute SQL statements such as INSERT or DELETE that do not return results.

• Function mysql_error returns any error strings from the database. • mysql_close closes the connection to the database specified in its

argument.

Page 58: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

58

2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.14: data.html --> 6 <!-- Form to query a MySQL database. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample Database Query</title> 10 <style type = "text/css"> 11 body { background-color: #F0E68C } 12 h2 { font-family: arial, sans-serif; 13 color: blue } 14 input { background-color: blue; 15 color: yellow; 16 font-weight: bold } 17 </style> 18 </head> 19 <body> 20 <h2> Querying a MySQL database.</h2> 21 <form method = "post" action = "database.php"> 22 <div> 23 <p>Select a field to display: 24 <!-- add a select box containing options --> 25 <!-- for SELECT query -->

Outline

data.html

(1 of 2)

Posts data to database.php

Page 59: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

59

2008 Pearson Education, Inc. All rights reserved.

26 <select name = "select">

27 <option selected = "selected">*</option>

28 <option>ID</option>

29 <option>Title</option>

30 <option>Category</option>

31 <option>ISBN</option>

32 </select></p>

33 <input type = "submit" value = "Send Query" />

34 </div>

35 </form>

36 </body>

37 </html>

Outline

data.html

(2 of 2)

Creates drop-down menu specifying which data to output to the screen, with * (all data) as the default selection

Page 60: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

60

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.15: database.php --> 6 <!-- Querying a database and displaying the results. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Search Results</title> 10 <style type = "text/css"> 11 body { font-family: arial, sans-serif; 12 background-color: #F0E68C } 13 table { background-color: #ADD8E6 } 14 td { padding-top: 2px; 15 padding-bottom: 2px; 16 padding-left: 4px; 17 padding-right: 4px; 18 border-width: 1px; 19 border-style: inset } 20 </style> 21 </head> 22 <body> 23 <?php 24 extract( $_POST ); 25

26 // build SELECT query 27 $query = "SELECT " . $select . " FROM books"; 28

Outline

database.php

(1 of 3)

Builds a SELECT query with the selection made in data.html

Page 61: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

61

2008 Pearson Education, Inc. All rights reserved.

29 // Connect to MySQL 30 if ( !( $database = mysql_connect( "localhost", 31 "iw3htp4", "iw3htp4" ) ) ) 32 die( "Could not connect to database </body></html>" ); 33

34 // open Products database 35 if ( !mysql_select_db( "products", $database ) ) 36 die( "Could not open products database </body></html>" ); 37

38 // query Products database 39 if ( !( $result = mysql_query( $query, $database ) ) ) 40 { 41 print( "Could not execute query! <br />" ); 42 die( mysql_error() . "</body></html>" ); 43 } // end if 44

45 mysql_close( $database ); 46 ?><!-- end PHP script --> 47 <h3>Search Results</h3> 48 <table> 49 <?php 50 // fetch each record in result set 51 for ( $counter = 0; $row = mysql_fetch_row( $result ); 52 $counter++ ) 53 { 54 // build table to display results 55 print( "<tr>" ); 56

Outline

database.php

(2 of 3)

Connects to database using server hostname localhost and username and password “iw3htp4”

Specifies products as the database to be queried

Queries $database with $query

Returns any error strings from the database

Closes the connection to the database

Returns an array with the values for each column of the current row in $result

Page 62: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

62

2008 Pearson Education, Inc. All rights reserved.

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

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

59

60 print( "</tr>" );

61 } // end for

62 ?><!-- end PHP script -->

63 </table>

64 <br />Your search yielded <strong>

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

66 <h5>Please email comments to

67 <a href = "mailto:[email protected]">

68 Deitel and Associates, Inc.</a>

69 </h5>

70 </body>

71 </html>

Outline

database.php

(3 of 3)

Page 63: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

63

2008 Pearson Education, Inc. All rights reserved.

23.6 Using Cookies

• A cookie is a text file that a website stores on a client’s computer to maintain information about the client during and between browsing sessions.

• A server can access only the cookies that it has placed on the client.• Function setcookie takes the name of the cookie to be set as the

first argument, followed by the value to be stored in the cookie. The optional third argument indicates the expiration date of the cookie. A cookie without a third argument is known as a session cookie, while one with an expiration date is a persistent cookie. If only the name argument is passed to function setcookie, the cookie is deleted from the client’s computer.

• Cookies defined in function setcookie are sent to the client at the same time as the information in the HTTP header; therefore, it needs to be called before any XHTML is printed.

• The current time is returned by function time.

Page 64: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

64

2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.16: cookies.html --> 6 <!-- Gathering data to be written as a cookie. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Writing a cookie to the client computer</title> 10 <style type = "text/css"> 11 body { font-family: arial, sans-serif; 12 background-color: #99CCFF } 13 form { font-size: 10pt } 14 .submit { background-color: #F0E86C; 15 color: navy; 16 font-weight: bold } 17 </style> 18 </head> 19 <body> 20 <h2>Click Write Cookie to save your cookie data.</h2> 21 <form method = "post" action = "cookies.php"> 22 <div> 23 <strong>Name:</strong><br /> 24 <input type = "text" name = "Name" /><br /> 25

26 <strong>Height:</strong><br /> 27 <input type = "text" name = "Height" /><br /> 28

Outline

cookies.html

(1 of 2)

Posts form data to cookies.php

Creates fields to gather information to be written into a cookie

Page 65: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

65

2008 Pearson Education, Inc. All rights reserved.

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

30 <input type = "text" name = "Color" /><br />

31

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

33 class = "submit" />

34 </div>

35 </form>

36 </body>

37 </html>

Outline

cookies.html

(2 of 2)

Form field

Page 66: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

66

2008 Pearson Education, Inc. All rights reserved.

1 <?php 2 // Fig. 23.17: cookies.php 3 // Writing a cookie to the client. 4 extract( $_POST ); 5

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 ?><!-- end PHP script --> 12

13 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 14 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 15 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 16

17 <html xmlns = "http://www.w3.org/1999/xhtml"> 18 <head> 19 <title>Cookie Saved</title> 20 <style type = "text/css"> 21 body { font-family: arial, sans-serif } 22 span { color: blue } 23 </style> 24 </head> 25 <body> 26 <p>The cookie has been set with the following data:</p> 27

28 <!-- print each form field’s value --> 29 <br /><span>Name:</span><?php print( $Name ) ?><br />

Outline

cookies.php

(1 of 2)

Creates a cookie for each entered value and sets the expiration date to be five days after the current time

Page 67: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

67

2008 Pearson Education, Inc. All rights reserved.

30 <span>Height:</span><?php print( $Height ) ?><br />

31 <span>Favorite Color:</span>

32 <span style = "color: <?php print( "$Color\">$Color" ) ?>

33 </span><br />

34 <p>Click <a href = "readCookies.php">here</a>

35 to read the saved cookie.</p>

36 </body>

37 </html>

Outline

cookies.php

(2 of 2)

Links to the page that displays the contents of the cookie

Page 68: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

68

2008 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 23.2

Some clients do not accept cookies. Whena client declines a cookie, the browser application normally informs the user thatthe site may not function correctly without cookies enabled.

Page 69: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

69

2008 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 23.3

Cookies should not be used to storee-mail addresses or private data on aclient’s computer.

Page 70: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

70

2008 Pearson Education, Inc. All rights reserved.

23.6 Using Cookies (Cont.)

• When using Internet Explorer, cookies are stored in a Cookies directory on the client’s machine. In Firefox, cookies are stored in a file named cookies.txt.

Page 71: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

71

2008 Pearson Education, Inc. All rights reserved.

Fig. 23.18 | IE7’s Cookies directory before a cookie is written.

Page 72: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

72

2008 Pearson Education, Inc. All rights reserved.

Fig. 23.19 | IE7’s Cookies directory after a cookie is written.

Page 73: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

73

2008 Pearson Education, Inc. All rights reserved.

23.6 Using Cookies (Cont.)

• PHP creates the superglobal array $_COOKIE, which contains all the cookie values indexed by their names.

Page 74: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

74

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.20: readCookies.php --> 6 <!-- Displaying the cookie’s contents. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Read Cookies</title> 10 <style type = "text/css"> 11 body { font-family: arial, sans-serif } 12 table { border-width: 5px; 13 border-style: outset } 14 td { padding: 10px } 15 .key { background-color: #F0E68C } 16 .value { background-color: #FFA500 } 17 </style> 18 </head> 19 <body> 20 <p> 21 <strong>The following data is saved in a cookie on your 22 computer.</strong> 23 </p> 24 <table> 25 <?php 26 // iterate through array $_COOKIE and print 27 // name and value of each cookie

Outline

readCookies.php

(1 of 2)

Page 75: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

75

2008 Pearson Education, Inc. All rights reserved.

28 foreach ( $_COOKIE as $key => $value )

29 print( "<tr><td class = 'key' >$key</td>

30 <td class = 'value' >$value</td></tr>" );

31 ?><!-- end PHP script -->

32 </table>

33 </body>

34 </html>

Outline

readCookies.php

(2 of 2)

Iterates through all values in $_COOKIE

Page 76: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

76

2008 Pearson Education, Inc. All rights reserved.

23.7 Dynamic Content

• Function isset allows you to find out if a variable has a value.

• A variable variable ($$variable) allows the code to reference variables dynamically. You can use this expression to obtain the value of the variable whose name is equal to the value of $variable.

• The quotemeta function inserts a backslash (\) before any special characters in the passed string.

Page 77: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

77

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.21: dynamicForm.php --> 6 <!-- Dynamic form. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sample form to take user input in XHTML</title> 10 <style type = "text/css"> 11 td { padding-top: 2px; 12 padding-bottom: 2px; 13 padding-left: 10px; 14 padding-right: 10px } 15 div { text-align: center } 16 div div { font-size: larger } 17 .name { background-color: #ffffaa } 18 .email { background-color: #ffffbb } 19 .phone { background-color: #ffffcc } 20 .os { background-color: #ffffdd } 21 .smalltext { font-size: smaller } 22 .prompt { color: blue; 23 font-family: sans-serif; 24 font-size: smaller } 25 .largeerror { color: red } 26 .error { color: red; 27 font-size: smaller } 28 </style> 29 </head>

Outline

dynamicForm.php

(1 of 12)

Page 78: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

78

2008 Pearson Education, Inc. All rights reserved.

30 <body> 31 <?php 32 extract( $_POST ); 33 $iserror = false; 34

35 // array of book titles 36 $booklist = array( "Internet and WWW How to Program 4e", 37 "C++ How to Program 6e", "Java How to Program 7e", 38 "Visual Basic 2005 How to Program 3e" ); 39

40 // array of possible operating systems 41 $systemlist = array( "Windows XP", "Windows Vista", 42 "Mac OS X", "Linux", "Other"); 43

44 // array of name values for the text input fields 45 $inputlist = array( "fname" => "First Name", 46 "lname" => "Last Name", "email" => "Email", 47 "phone" => "Phone" ); 48

49 // ensure that all fields have been filled in correctly 50 if ( isset ( $submit ) ) 51 { 52 if ( $fname == "" ) 53 { 54 $formerrors[ "fnameerror" ] = true; 55 $iserror = true; 56 } // end if 57

Outline

dynamicForm.php

(2 of 12)

Checks whether the Register button has been pressed

Checks that the first name field is not blank

Makes an entry in the error array

Sets $iserror to true

Page 79: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

79

2008 Pearson Education, Inc. All rights reserved.

58 if ( $lname == "" ) 59 { 60 $formerrors[ "lnameerror" ] = true; 61 $iserror = true; 62 } // end if 63

64 if ( $email == "" ) 65 { 66 $formerrors[ "emailerror" ] = true; 67 $iserror = true; 68 } // end if 69

70 if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) 71 { 72 $formerrors[ "phoneerror" ] = true; 73 $iserror = true; 74 } // end if 75

76 if ( !$iserror ) 77 { 78 // build INSERT query 79 $query = "INSERT INTO contacts " . 80 "( LastName, FirstName, Email, Phone, Book, OS ) " . 81 "VALUES ( '$lname', '$fname', '$email', " . 82 "'" . quotemeta( $phone ) . "', '$book', '$os' )";

Outline

dynamicForm.php

(3 of 12)

Checks that all other form fields are filled in correctly

Inserts a backslash before the parentheses in the phone number

Page 80: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

80

2008 Pearson Education, Inc. All rights reserved.

83

84 // Connect to MySQL 85 if ( !( $database = mysql_connect( "localhost", 86 "iw3htp4", "iw3htp4" ) ) ) 87 die( "Could not connect to database" ); 88

89 // open MailingList database 90 if ( !mysql_select_db( "MailingList", $database ) ) 91 die( "Could not open MailingList database" ); 92

93 // execute query in MailingList database 94 if ( !( $result = mysql_query( $query, $database ) ) ) 95 { 96 print( "Could not execute query! <br />" ); 97 die( mysql_error() ); 98 } // end if 99

100 mysql_close( $database ); 101

102 print( "<p>Hi<span class = 'prompt'> 103 <strong>$fname</strong></span>. 104 Thank you for completing the survey.<br /> 105

106 You have been added to the 107 <span class = 'prompt'> 108 <strong>$book</strong></span> 109 mailing list.</p> 110 <strong>The following information has been saved 111 in our database:</strong><br /> 112

Outline

dynamicForm.php

(4 of 12)

Page 81: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

81

2008 Pearson Education, Inc. All rights reserved.

113 <table><tr> 114 <td class = 'name'>Name </td> 115 <td class = 'email'>Email</td> 116 <td class = 'phone'>Phone</td> 117 <td class = 'os'>OS</td> 118 </tr><tr> 119

120 <!-- print each form field’s value --> 121 <td>$fname $lname</td> 122 <td>$email</td> 123 <td>$phone</td> 124 <td>$os</td> 125 </tr></table> 126

127 <br /><br /><br /> 128 <div><div> 129 <a href = 'formDatabase.php'> 130 Click here to view entire database.</a> 131 </div>This is only a sample form. 132 You have not been added to a mailing list. 133 </div></body></html>" ); 134 die(); 135 } // end if 136 } // end if 137

138 print( "<h1>Sample Registration Form.</h1> 139 Please fill in all fields and click Register." ); 140

Outline

dynamicForm.php

(5 of 12)

Ends script here if there were no errors in the user input

Section to be executed only if $iserror is true

Page 82: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

82

2008 Pearson Education, Inc. All rights reserved.

141 if ( $iserror ) 142 { 143 print( "<br /><span class = 'largeerror'> 144 Fields with * need to be filled in properly.</span>" ); 145 } // end if 146

147 print( "<!-- post form data to form.php --> 148 <form method = 'post' action = 'dynamicForm.php'> 149 <img src = 'images/user.gif' alt = 'User' /><br /> 150 <span class = 'prompt'> 151 Please fill out the fields below.<br /> </span> 152

153 <!-- create four text boxes for user input -->" ); 154 foreach ( $inputlist as $inputname => $inputalt ) 155 { 156 $inputtext = $inputvalues[ $inputname ]; 157

158 print( "<img src = 'images/$inputname.gif' 159 alt = '$inputalt' /><input type = 'text' 160 name = '$inputname' value = '" . $$inputname . "' />" ); 161

162 if ( $formerrors[ ( $inputname )."error" ] == true ) 163 print( "<span class = 'error'>*</span>" ); 164

165 print( "<br />" ); 166 } // end foreach 167

168 if ( $formerrors[ "phoneerror" ] ) 169 print( "<span class = 'error'>" );

Outline

dynamicForm.php

(6 of 12)

Alerts the user that there are errors

Iterates through $inputlist to create the form’s text boxes

Outputs the field’s image

Sets the name attribute of the text field to $inputname

Sets the value attribute of the text field to the value of the variable with the name of $inputname’s value Puts an asterisk

next to fields that have errors

Page 83: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

83

2008 Pearson Education, Inc. All rights reserved.

170 else 171 print("<span class = 'smalltext'>"); 172

173 print( "Must be in the form (555)555-5555 174 </span><br /><br /> 175

176 <img src = 'images/downloads.gif' 177 alt = 'Publications' /><br /> 178

179 <span class = 'prompt'> 180 Which book would you like information about? 181 </span><br /> 182

183 <!-- create drop-down list containing book names --> 184 <select name = 'book'>" ); 185

186 foreach ( $booklist as $currbook ) 187 { 188 print( "<option" ); 189

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

193 print( ">$currbook</option>" ); 194 } // end foreach 195

Outline

dynamicForm.php

(7 of 12)

Creates drop-down list for books, keeping the previously selected one selected

Page 84: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

84

2008 Pearson Education, Inc. All rights reserved.

196 print( "</select><br /><br /> 197 <img src = 'images/os.gif' alt = 'Operating System' /> 198 <br /><span class = 'prompt'> 199 Which operating system are you currently using? 200 <br /></span> 201

202 <!-- create five radio buttons -->" ); 203

204 $counter = 0; 205

206 foreach ( $systemlist as $currsystem ) 207 { 208 print( "<input type = 'radio' name = 'os' 209 value = '$currsystem'" ); 210

211 if ( $currsystem == $os ) 212 print( "checked = 'checked'" ); 213 elseif ( !$os && $counter == 0 ) 214 print( "checked = 'checked'" ); 215

216 print( " />$currsystem" ); 217

218 // put a line break in list of operating systems 219 if ( $counter == 1 ) print( "<br />" ); 220 ++$counter; 221 } // end foreach 222

Outline

dynamicForm.php

(8 of 12)

Creates radio buttons for operating-system selection, keeping the previously selected option selected

Page 85: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

85

2008 Pearson Education, Inc. All rights reserved.

223 print( "<!-- create a submit button -->

224 <br /><input type = 'submit' name = 'submit'

225 value = 'Register' /></form></body></html>" );

226 ?><!-- end PHP script -->

Outline

dynamicForm.php

(9 of 12)

Page 86: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

86

2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(10 of 12)

Page 87: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

87

2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(11 of 12)

Page 88: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

88

2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(12 of 12)

Page 89: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

89

2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4

5 <!-- Fig. 23.22: formDatabase.php --> 6 <!-- Displaying the MailingList database. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Search Results</title> 10 <style type = "text/css"> 11 body { font-family: arial, sans-serif; 12 background-color: #F0E68C } 13 h3 { color: blue } 14 table { background-color: #ADD8E6 } 15 td { padding-top: 2px; 16 padding-bottom: 2px; 17 padding-left: 4px; 18 padding-right: 4px; 19 border-width: 1px; 20 border-style: inset } 21 </style> 22 </head> 23 <body> 24 <?php 25 extract( $_POST ); 26

27 // build SELECT query 28 $query = "SELECT * FROM contacts"; 29

Outline

formDatabase.php

(1 of 3)

Selects all fields from the contacts database to display

Page 90: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

90

2008 Pearson Education, Inc. All rights reserved.

30 // Connect to MySQL 31 if ( !( $database = mysql_connect( "localhost", 32 "iw3htp4", "iw3htp4" ) ) ) 33 die( "Could not connect to database </body></html>" ); 34

35 // open MailingList database 36 if ( !mysql_select_db( "MailingList", $database ) ) 37 die( "Could not open MailingList database </body></html>" ); 38

39 // query MailingList database 40 if ( !( $result = mysql_query( $query, $database ) ) ) 41 { 42 print( "Could not execute query! <br />" ); 43 die( mysql_error() . "</body></html>" ); 44 } // end if 45 ?><!-- end PHP script --> 46

47 <h3>Mailing List Contacts</h3> 48 <table> 49 <tr> 50 <td>ID</td> 51 <td>Last Name</td> 52 <td>First Name</td> 53 <td>E-mail Address</td> 54 <td>Phone Number</td> 55 <td>Book</td> 56 <td>Operating System</td> 57 </tr> 58 <?php

Outline

formDatabase.php

(2 of 3)

Page 91: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

91

2008 Pearson Education, Inc. All rights reserved.

59 // fetch each record in result set

60 for ( $counter = 0; $row = mysql_fetch_row( $result );

61 $counter++ )

62 {

63 // build table to display results

64 print( "<tr>" );

65

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

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

68

69 print( "</tr>" );

70 } // end for

71

72 mysql_close( $database );

73 ?><!-- end PHP script -->

74 </table>

75 </body>

76 </html>

Outline

formDatabase.php

(3 of 3)

Page 92: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

92

2008 Pearson Education, Inc. All rights reserved.

23.8 Operator Precedence Chart

• The following table contains a list of PHP operators in decreasing order of precedence.

Page 93: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

93

2008 Pearson Education, Inc. All rights reserved.

Operator Type Associativity

new constructor none

[] subscript right to left

~ ! ++ -- - @

bitwise not not increment

decrement

unary negative

error control

right to left

* / %

multiplication

division

modulus

left to right

+ - .

addition

subtraction

concatenation

left to right

Fig. 23.23 | PHP operator precedence and associativity. (Part 1 of 3.)

Page 94: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

94

2008 Pearson Education, Inc. All rights reserved.

Operator Type Associativity

<<

>>

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

& bitwise AND left to right

^ bitwise XOR left to right

| bitwise OR left to right

&& logical AND left to right

|| logical OR left to right

Fig. 23.23 | PHP operator precedence and associativity. (Part 2 of 3.)

Page 95: 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP.

95

2008 Pearson Education, Inc. All rights reserved.

Operator Type Associativity

= += -= *= /= &= |= ^= .= <<= >>=

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. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)