Sunteți pe pagina 1din 128

1

Chapter 26 - PHP
Outline
26.1 26.2 26.3 26.4 26.5 26.6 26.7 26.8 26.9 26.10 26.11 Introduction PHP String Processing and Regular Expressions Viewing Client/Server Environment Variables Form Processing and Business Logic Verifying a Username and Password Connecting to a Database Cookies Dynamic Content in PHP Operator Precedence Web Resources

2004 Prentice Hall, Inc. All rights reserved.

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.

2004 Prentice Hall, Inc. All rights reserved.

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

2004 Prentice Hall, Inc. All rights reserved.

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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 26.1: first.php --> <!-- Our first PHP script -->

Outline
first.php (1 of 1)

Scripting delimiters
<?php $name = "LunaTic"; ?> // declaration

Declare variable $name

11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 14 15 16 17 18 19 20 21 22 23 24 </p> </body> <!-- print variable names value --> Welcome to PHP, <?php print( "$name" ); ?>! </strong> <body style = "font-size: 2em"> <p> <strong> <head> <title>A simple PHP document</title>Single-line </head>

comment

Function print outputs the value of variable


$name

25 </html>

2004 Prentice Hall, Inc.


All rights reserved.

26.2 PHP
Fig. 26.1 Simple PHP program.

2004 Prentice Hall, Inc. All rights reserved.

26.2 PHP Variables


-Variables in PHP starts with a $ sign, followed by the name of the variable -The variable name must begin with a letter or the underscore character -A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) -A variable name should not contain spaces -Variable names are case sensitive (y and Y are two different variables) -An unassigned (unbound) variable has the value NULL -The unset function sets a variable to NULL -The IsSet function is used to determine

2004 Prentice Hall, Inc. All rights reserved.

26.2 PHP Variables


Can have different types at different times Type conversions settype function Type casting Concatenation operator . (period) Combine strings

2004 Prentice Hall, Inc. All rights reserved.

26.2 PHP
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.2 PHP data types. Data type

2004 Prentice Hall, Inc. All rights reserved.

10

PHP is a Loosely Typed Language


In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.3: data.php -->

11

Outline
data.php (1 of 3)

<!-- Demonstration of PHP data types --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>PHP data types</title> </head> <body> <?php // declare a string, double and integer $testString = "3.5 seconds"; $testDouble = 79.2; $testInteger = 12; ?>

2004 Prentice Hall, Inc.


All rights reserved.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

<!-- print each variables value --> <?php print( $testString ); ?> is a string.<br /> <?php print( $testDouble ); ?> is a double.<br /> <?php print( $testInteger ); ?> is an integer.<br /> <br /> Now, converting to other types:<br /> <?php // call function settype to convert variable // testString to different data types print( "$testString" ); settype( $testString, "double" ); print( " as a double is $testString <br />" ); print( "$testString" ); settype( $testString, "integer" ); print( " as an integer is $testString <br />" ); settype( $testString, "string" ); print( "Converting back to a string results in $testString <br /><br />" ); $data = "98.6 degrees";

12

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

2004 Prentice Hall, Inc.


All rights reserved.

44 45 46 47 48 49 50 51 52 ?> </body> // use type casting to cast variables to a // different type print( "Now using type casting instead: <br /> As a string - " . (string) $data . "<br />As a double - " . (double) $data . "<br />As an integer - " . (integer) $data );

13

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

53 </html>

2004 Prentice Hall, Inc.


All rights reserved.

14

26.2 PHP
Fig. 26.3 Type conversion.

2004 Prentice Hall, Inc. All rights reserved.

15

Arithmetic operators
Operator Name Description Example Result

x+y
x-y x*y x/y

Addition
Subtraction Multiplication Division

Sum of x and y
Difference of x and y Product of x and y Quotient of x and y

2+2
5-2 5*2 15 / 5

4
3 10 3

x%y

Modulus

-x a.b

Negation Concatenation

Remainder of x divided by 5 % 2 y 10 % 8 10 % 2 Opposite of x -2


Concatenate two strings "Hi" . "Ha"

1 2 0
HiHa

2004 Prentice Hall, Inc. All rights reserved.

16

Assignment operators
Assignment
x=y x += y x -= y x *= y x /= y x %= y a .= b

Same as...
x=y x=x+y x=x-y x=x*y x=x/y x=x%y a=a.b

Description
The left operand gets set to the value of the expression on the right Addition Subtraction Multiplication Division Modulus Concatenate two strings

Before being assigned values, variables have value undef

2004 Prentice Hall, Inc. All rights reserved.

17

Increment/ Decrement Operators


Operato Name Description r ++ x Pre-increment Increments x by one, then returns x x ++ Post-increment Returns x, then increments x by one -- x Pre-decrement Decrements x by one, then returns x x -PostReturns x, then decrements x by one decrement

2004 Prentice Hall, Inc. All rights reserved.

18

Comparison Operators
Operator x == y x === y x != y x <> y x !== y x>y x<y x >= y x <= y Name Equal Identical Not equal Not equal Not identical Greater than Less than Description True if x is equal to y True if x is equal to y, and they are of same type True if x is not equal to y True if x is not equal to y True if x is not equal to y, or they are not of same type True if x is greater than y True if x is less than y Example 5==8 returns false 5==="5" returns false 5!=8 returns true 5<>8 returns true 5!=="5" returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true

Greater than or equal True if x is greater than or equal to y to Less than or equal to True if x is less than or equal to y

2004 Prentice Hall, Inc. All rights reserved.

19

26.2 PHP Constants - A way of associating a scalar value with a string taken - Defined by the define construct define(myconstant, 12); - Same rules apply for naming variable names - No $ before the constant name - Once defined their values cannot be changed.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.4: operators.php -->

20

Outline
operators.php (1 of 3)

<!-- Demonstration of operators --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using arithmetic operators</title> </head> <body> <?php $a = 5;

Define constant VALUE.

print( "The value of variable a is $a <br />" ); // define constant VALUE define( "VALUE", 5 );

Add constant VALUE to variable $a.

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

2004 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

// multiply variable $a by 2 $a *= 2; print( "Multiplying variable a by 2 yields $a <br />" ); // test if variable $a is less than 50 if ( $a < 50 ) print( "Variable a is less than 50 <br />" ); // add 40 to variable $a $a += 40; print( "Variable a after adding 40 is $a <br />" ); // test if variable $a is 50 or less if ( $a < 51 ) print( "Variable a is still 50 or less<br />" ); // test if variable $a is between 50 and 100, inclusive elseif ( $a < 101 ) print( "Variable a is now between 50 and 100, inclusive<br />" ); else print( "Variable a is now greater than 100 <br />" );

21

Outline
operators.php (2 of 3)

2004 Prentice Hall, Inc.


All rights reserved.

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ?>

// print an uninitialized variable print( "Using a variable before initializing: $nothing <br />" ); // add constant VALUE to an uninitialized variable $test = $num + VALUE; print( "An uninitialized variable plus constant VALUE yields $test <br />" ); // add a string to an integer $str = "3 dollars"; $a += $str; print( "Adding a string to variable a yields $a <br />" ); </body>

22

Outline
operators.php (3 of 3)

65 </html>

2004 Prentice Hall, Inc.


All rights reserved.

23

26.2 PHP
Fig. 26.4 Using PHPs arithmetic operators.

2004 Prentice Hall, Inc. All rights reserved.

24

IF statement
Syntax

if (condition) code to be executed if condition is true;


The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html>

2004 Prentice Hall, Inc. All rights reserved.

25

The if...else Statement


Example

The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } else { echo "Have a nice day!"; } ?> </body> </html>

2004 Prentice Hall, Inc. All rights reserved.

26

The if...elseif....else Statement


Example
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } elseif ($d=="Sun") { echo "Have a nice Sunday!"; } else { echo "Have a nice day!"; } ?> /body> </html>
2004 Prentice Hall, Inc. All rights reserved.

27

The PHP Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; }
2004 Prentice Hall, Inc. All rights reserved.

28

The PHP Switch Statement


Example <html> <body> <?php $x=1; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
2004 Prentice Hall, Inc. All rights reserved.

29

The while Loop

The while loop executes a block of code while a condition is true.

Syntax
while (condition) { code to be executed; }
Example: $i=0; while ($i<10){ echo $i; $i++; }
2004 Prentice Hall, Inc. All rights reserved.

30

The do...while Statement


Syntax do { code to be executed; } while (condition);

Example <html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>

2004 Prentice Hall, Inc. All rights reserved.

31

The for Loop


The for loop is used when you know in advance how many times the script should run.

Syntax
for (init; condition; increment) { code to be executed; } Example <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html>

2004 Prentice Hall, Inc. All rights reserved.

32

Arrays Not like the arrays of any other programming language A PHP array is a generalization of the arrays of other languages A PHP array is really a mapping of keys to values, where the keys can be numbers (to get a traditional array) or strings.

2004 Prentice Hall, Inc. All rights reserved.

33

Array Creation
Use the array() construct, which takes one or more key => value pairs as parameters and returns an array of them The keys are non-negative integer literals or string literals The values can be anything
$list1 = array(); $list2 = array (17, 24, 45, 90); $list3 = array(0 => "apples",1 => "oranges", 2 => "grapes")

$list4 = array(Joe => 42, Mary => 41, Jan => 17);
$list5 = $list2;

2004 Prentice Hall, Inc. All rights reserved.

34

Numeric Arrays
A numeric array stores each array element with a numeric index. There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("Saab","Volvo","BMW","Toyota"); 2. In the following example we assign the index manually: $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota";

2004 Prentice Hall, Inc. All rights reserved.

35

Numeric Arrays
Example In the following example you access the variable values by referring to the array name and index: <?php $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; ?> The code above will output: Saab and Volvo are Swedish cars.

2004 Prentice Hall, Inc. All rights reserved.

36

Associative Arrays
An associative array, each ID key is associated with a value. Example 1 In this example we use an array to assign ages to the different persons: $ages = array("Peter"=>32, John"=>30, "Joe"=>34); Example 2 This example is the same as example 1, but shows a different way of creating the array: $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; The ID keys can be used in a script: <?php $ages['Peter'] = "32"; $ages[John'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>
2004 Prentice Hall, Inc. All rights reserved.

37

Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on

Example In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array ( "Griffin"=>array( "Peter", "Lois", "Megan"), "Quagmire"=>array ( "Glenn"), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
2004 Prentice Hall, Inc. All rights reserved.

38

Dealing with Arrays


The keys or values can be extracted from an array $highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67, "Thu" => 62, "Fri" => 65); $days = array_keys($highs); $temps = array_values($highs); sort - to sort the values of an array e.g., sort($list); An array can be deleted with unset unset($highs); unset($highs[4]); # No index 4 element now is_array($highs) returns true if $highs is an array in_array(17, $highs) returns true if 17 is an element of $highs count ($highs) returns the number of elements in $highs
2004 Prentice Hall, Inc. All rights reserved.

39

Sequential Acces to Array elements foreach statement to build loops that process all of the elements in an array foreach (array as key=>value) loop body E.g. foreach ($highs as $day=>$temp) print(The low temperature on $day was $temp <br />);

2004 Prentice Hall, Inc. All rights reserved.

40

26.2 PHP Arrays, cont.


Built-in iterators
Maintain pointer to element currently referenced
reset key next

foreach loops

2004 Prentice Hall, Inc. All rights reserved.

41

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.5 PHP keywords.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.6: arrays.php --> <!-- Array manipulation -->

42

Outline
arrays.php (1 of 3)

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Array manipulation</title> </head> <body> <?php // create array first print( "<strong>Creating the first array</strong> <br />" ); $first[ 0 ] = "zero"; $first[ 1 ] = "one"; $first[ 2 ] = "two"; $first[] = "three";

Create the array $first by assigning a value to an array element.

Use a for loop to print out each elements index and value. Function count returns the total number of elements in the array.

// print each elements index and value for ( $i = 0; $i < count( $first ); $i++ ) print( "Element $i is $first[$i] <br />" );

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // assign values to non-numerical indices $third[ "ArtTic" ] = 21; $third[ "LunaTic" ] = 18; $third[ "GalAnt" ] = 23; print( "<br /><strong>Creating the third array </strong><br />" ); // call function $second = array( print( "<br /><strong>Creating the second array </strong><br />" );

43

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

Outline

for ( $i = 0; $i < count( $second ); $i++ ) print( "Element $i is $second[$i] <br />" );

Function reset sets the internal pointer to the first element of the array.

// iterate through the array elements and print each // elements name and value for ( reset( $third ); $element = key( $third ); next( $third ) ) print( "$element is $third[$element] <br />" );

Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element.
2004 Prentice Hall, Inc.
All rights reserved.

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 ?>

print( "<br /><strong>Creating the fourth array </strong><br />" ); // call function array to create array fourth using // string indices $fourth = array( "January" "March" "May" "July" "November" ); // print each elements name and value foreach ( $fourth as $element => $value ) print( "$element is the $value month <br />" ); </body> => "first", => "third", => => => "February" => "second", "April" => "fourth",

44

Outline
arrays.php (3 of 3)

"September" =>

is "sixth", used in function array to assign each "fifth", Operator "June" =>=> a string index. The value to the left of the "seventh",element "August" => "eighth", is the index, and the value to the right is "ninth", operator "October" => array "tenth", the elements value. "eleventh","December" => "twelfth"

68 </html>

2004 Prentice Hall, Inc.


All rights reserved.

45

26.2 PHP
Fig. 26.6 Array manipulation.

2004 Prentice Hall, Inc. All rights reserved.

46

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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.7: compare.php --> <!-- String Comparison -->

47

Outline
compare.php (1 of 2)

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>String Comparison</title> </head> <body> <?php

Use a for loop to iterate through each array element.

// create array fruits $fruits = array( "apple", "orange", "banana" ); // iterate through each array element for ( $i = 0; $i < count( $fruits ); $i++ ) { // call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " );

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 2004 Prentice Hall, Inc. All rights reserved. alphabetically follows the second, then 1 is returned.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 ?> </body> }

elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) print( $fruits[ $i ]. " is greater than banana " ); else

48

Outline
to compare each array compare.php element to string apple. (2 of 2)

relational operators print( $fruits[ $i ]." is Use equal to banana " );


// use relational operators to compare each element // to string "apple" if ( $fruits[ $i ] < "apple" ) print( "and less than apple! <br />" ); elseif ( $fruits[ $i ] > "apple" ) print( "and greater than apple! <br />" ); elseif ( $fruits[ $i ] == "apple" ) print( "and equal to apple! <br />" );

43 </html>

2004 Prentice Hall, Inc.


All rights reserved.

49

26.3 String Processing and Regular Expressions


Fig. 26.7 Using the string comparison operators.

2004 Prentice Hall, Inc. All rights reserved.

50

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 [ ]

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.8: expression.php --> <!-- Using regular expressions --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Regular expressions</title> </head> <body> <?php

51

Outline
expression.php (1 of 3)

Function ereg searches for the literal characters Now inside variable $search.

$search = "Now is the time"; print( "Test string is: '$search'<br /><br />" ); // call function ereg to search for pattern 'Now' // in variable search if ( ereg( "Now", $search ) ) print( "String 'Now' was found.<br />" );

2004 Prentice Hall, Inc.


All rights reserved.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// search for pattern 'Now' in the beginning of // the string if ( ereg( "^Now", $search ) ) print( "String 'Now' found at beginning of the line.<br />" ); // search for pattern 'Now' at the end of the string if ( ereg( "Now$", $search ) ) (now ile balayan varm diye bakyor ^) print( "String 'Now' was found at the end of the line.<br />" ); // search for any word ending in 'ow' if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) ) print( "Word found ending in 'ow': " . $match[ 1 ] . "<br />" ); // search for any words beginning with 't' print( "Words beginning with 't' found: "); // eregi( "[[:<:]](t[[a-zA-Z]]+)[[:>:]]", yerine alpha yazabiliriz. while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", $search, $match ) ) { print( $match[ 1 ] . " " );

52

Outline
expression.php (2 of 3)

Function eregi is used to specify case insensitive pattern matches.

2004 Prentice Hall, Inc.


All rights reserved.

46 47 48 49 50 51 52 53 ?> </body> }

// remove the first occurrence of a word beginning // with 't' to find other instances in the string $search = ereg_replace( $match[ 1 ], "", $search );

53

Outline

print( "<br />" );

54 </html>

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

2004 Prentice Hall, Inc.


All rights reserved.

54

26.3 String Processing and Regular Expressions


Fig. 26.8 Regular expressions in PHP.

2004 Prentice Hall, Inc. All rights reserved.

55

26.3 String Processing and Regular Expressions

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

Matches
Exactly n times. Between m and n times inclusive. n or more times. One or more times (same as {1,}). Zero or more times (same as {0,}). Zero or one time (same as {0,1}).

Fig. 26.9

Some PHP quantifiers.

2004 Prentice Hall, Inc. All rights reserved.

56

26.3 String Processing and Regular Expressions

Character class
alnum alpha digit space lower upper

Description
Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]). Word characters (i.e., letters [a-zA-Z]). Digits. Whitespace. Lowercase letters. Uppercase letters.

Fig. 26.10

Some PHP character classes.

2004 Prentice Hall, Inc. All rights reserved.

57

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

2004 Prentice Hall, Inc. All rights reserved.

58

26.4 Viewing Client/Server Environment Variables


Variable name Description $_SERVER Data about the currently running server. $_ENV Data about the clients 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 clients computer. $GLOBALS Array containing all global variables. Fig. 26.11 Some useful global arrays.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.11: env.php -->

59

Outline
env.php (1 of 1)

<!-- Program to display environment variables --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Environment Variables</title> </head> <body> <table border = "0" cellpadding = "2" cellspacing = "0" width = "100%"> <?php // print the key and value for each element // in the $_ENV array foreach ( $_ENV as $key => $value ) print( "<tr><td bgcolor = \"#11bbff\"> <strong>$key</strong></td> <td>$value</td></tr>" ); ?> </table> </body>

26 </html>

2004 Prentice Hall, Inc.


All rights reserved.

60

26.4 Viewing Client/Server Environment Variables


Fig. 26.12 Displaying environment variables.

2004 Prentice Hall, Inc. All rights reserved.

61

26.5 Form Processing and Business Logic Form processing


action property Where to send form data method property
post

Each element has unique name

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.13: form.html -->

62

Outline
form.html (1 of 4)

<!-- Form for use with the form.php program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample form to take user input in XHTML</title> </head> <body> <h1>This is a sample registration form.</h1> Please fill in all fields and click Register. <!-- post form data to form.php --> <form method = "post" action = "form.php"> <img src = "images/user.gif" alt = "User" /><br /> <span style = "color: blue"> Please fill out the fields below.<br /> </span>

The action attribute of the form element indicates that when the user clicks Register, the form data will be posted to form.php.

2004 Prentice Hall, Inc.


All rights reserved.

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

<!-- create four text boxes for user input --> <img src = "images/fname.gif" alt = "First Name" /> <input type = "text" name = "fname" /><br /> <img src = "images/lname.gif" alt = "Last Name" /> <input type = "text" name = "lname" /><br /> <img src = "images/email.gif" alt = "Email" /> <input type = "text" name = "email" /><br /> <img src = "images/phone.gif" alt = "Phone" /> <input type = "text" name = "phone" /><br /> <span style = "font-size: 10pt"> Must be in the form (555)555-5555</span> <br /><br /> <img src = "images/downloads.gif" alt = "Publications" /><br /> <span style = "color: blue"> Which book would you like information about? </span><br />

63

Outline
form.html (2 of 4)

A unique name (e.g., email) is assigned to eac of the forms input fields. When Register is clicked, each fields name and value are sent the Web server.

2004 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

<!-- create drop-down list containing book names --> <select name = "book"> <option>Internet and WWW How to Program 3e</option> <option>C++ How to Program 4e</option> <option>Java How to Program 5e</option> <option>XML How to Program 1e</option> </select> <br /><br /> <img src = "images/os.gif" alt = "Operating System" /> <br /><span style = "color: blue"> Which operating system are you currently using? <br /></span> <!-- create five radio buttons --> <input type = "radio" name = "os" value = "Windows XP" checked = "checked" /> Windows XP <input type = "radio" name = "os" value = "Windows 2000" /> Windows 2000 <input type = "radio" name = "os" value = "Windows 98" /> Windows 98<br />

64

Outline
form.html (3 of 4)

2004 Prentice Hall, Inc.


All rights reserved.

74 75 76 77 78 79 80 81 82 83 84 85 </body> 86 </html> <!-- create a submit button --> <input type = "submit" value = "Register" /> </form> <input type = "radio" name = "os" value = "Other" /> Other<br /> <input type = "radio" name = "os" value = "Linux" /> Linux

65

Outline
form.html (4 of 4)

2004 Prentice Hall, Inc.


All rights reserved.

66

26.5 Form Processing and Business Logic


Fig. 26.13 XHTML form for gathering user input.

2004 Prentice Hall, Inc. All rights reserved.

67

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
2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.14: form.php -->

68

Outline
form.php (1 of 4)

<!-- Read information sent from form.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Form Validation</title> </head> <body style = "font-family: arial,sans-serif"> <?php extract( $_POST ); // determine whether phone number is valid and print // an error message if not if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ){

We access the phone fields value from form.html by using variable $phone.

2004 Prentice Hall, Inc.


All rights reserved.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <p>Hi ?> }

print( "<p><span style = \"color: red; font-size: 2em\"> INVALID PHONE NUMBER</span><br /> A valid phone number must be in the form <strong>(555)555-5555</strong><br /> <span style = \"color: blue\"> Click the Back button, enter a valid phone number and resubmit.<br /><br /> Thank You.</span></p></body></html>" ); die(); // terminate script execution

69

Outline
form.php (2 of 4)

Function die terminates script execution

<span style = "color: blue"> <strong> <?php print( "$fname" ); ?> </strong> </span>. Thank you for completing the survey.<br />

2004 Prentice Hall, Inc.


All rights reserved.

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

You have been added to the <span style = "color: blue"> <strong> <?php print( "$book " ); ?> </strong> </span> mailing list. </p> <strong>The following information has been saved in our database:</strong><br /> <table border = "0" cellpadding = "0" cellspacing = "10"> <tr> <td bgcolor = "#ffffaa">Name </td> <td bgcolor = "#ffffbb">Email</td> <td bgcolor = "#ffffcc">Phone</td> <td bgcolor = "#ffffdd">OS</td> </tr> <tr> <?php

70

Outline
form.php (3 of 4)

2004 Prentice Hall, Inc.


All rights reserved.

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 ?> </tr> </table>

// print each form fields value print( "<td>$fname $lname</td> <td>$email</td> <td>$phone</td> <td>$os</td>" );

71

Outline
form.php (4 of 4)

<br /><br /><br /> <div style = "font-size: 10pt; text-align: center"> This is only a sample form. You have not been added to a mailing list. </div> </body>

81 </html>

2004 Prentice Hall, Inc.


All rights reserved.

72

26.5 Form Processing and Business Logic


Fig. 26.14 Obtaining user input through forms.

2004 Prentice Hall, Inc. All rights reserved.

73

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

2004 Prentice Hall, Inc. All rights reserved.

74

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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.15: password.html -->

75

Outline
password.html (1 of 4)

<!-- XHTML form sent to password.php for verification --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Verifying a username and a password.</title> <style type = "text/css"> td { background-color: #DDDDDD } </style> </head> <body style = "font-family: arial"> <p style = "font-size: 13pt"> Type in your username and password below. <br /> <span style = "color: #0000FF; font-size: 10pt; font-weight: bold"> Note that password will be sent as plain text </span> </p>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

<!-- post form data to password.php --> <form action = "password.php" method = "post"> <br />

76

Outline
password.html (2 of 4)

Form data is posted to password.php.

<table border = "0" cellspacing = "0" style = "height: 90px; width: 123px; font-size: 10pt" cellpadding = "0"> <tr> <td colspan = "3"> <strong>Username:</strong> </td> </tr> <tr> <td colspan = "3"> <input size = "40" name = "USERNAME" style = "height: 22px; width: 115px" /> </td> </tr>

2004 Prentice Hall, Inc.


All rights reserved.

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

<tr> <td colspan = "3"> <strong>Password:</strong> </td> </tr> <tr> <td colspan = "3"> <input size = "40" name = "PASSWORD" style = "height: 22px; width: 115px" type = "password" /> <br/></td> </tr> <tr> <td colspan = "1"> <input type = "submit" name = "Enter" value = "Enter" style = "height: 23px; width: 47px" /> </td> <td colspan = "2"> <input type = "submit" name = "NewUser" value = "New User" style = "height: 23px" /> </td>

77

Outline
password.html (3 of 4)

2004 Prentice Hall, Inc.


All rights reserved.

72 73 74 75

</tr> </table> </form> </body>

78

Outline
password.html (4 of 4)

76 </html>

2004 Prentice Hall, Inc.


All rights reserved.

79

26.6 Verifying a Username and Password


Fig. 26.15 XHTML form for obtaining a username and password.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.16: password.php -->

80

Outline
password.php (1 of 7)

<!-- Searching a database for usernames and passwords. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <?php extract( $_POST ); // check if user has left USERNAME or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); } // check if the New User button was clicked if ( isset( $NewUser ) ) { // open password.txt for writing using append mode if ( !( $file = fopen( "password.txt", "a" ) ) ) {

2004 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 } } }

// print error message and terminate script // execution if file cannot be opened print( "<title>Error</title></head><body> Could not open password file </body></html>" ); die();

81

Outline
password.php (2 of 7)

// write username and password to file and // call function userAdded fputs( $file, "$USERNAME,$PASSWORD\n" ); userAdded( $USERNAME ); else { // if a new user is not being added, open file // for reading if ( !( $file = fopen( "password.txt", "r" ) ) ) { print( "<title>Error</title></head> <body>Could not open password file </body></html>" ); die();

2004 Prentice Hall, Inc.


All rights reserved.

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

$userVerified = 0;

82

Outline
// read each line in file and check username // and password while ( !feof( $file ) && !$userVerified ) { // read line from file $line = fgets( $file, 255 ); // remove newline character from end of line $line = chop( $line ); // split username and password $field = split( ",", $line, 2 ); // verify username if ( $USERNAME == $field[ 0 ] ) { $userVerified = 1; // call function checkPassword to verify // users password if ( checkPassword( $PASSWORD, $field ) == true ) accessGranted( $USERNAME ); else wrongPassword();

password.php (3 of 7)

Function checkPassword is called to verify the users password. Variable $PASSWORD and array $field are passed to the function. 2004 Prentice Hall, Inc.
All rights reserved.

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 } } }

83

Outline
password.php (4 of 7)

// close text file fclose( $file ); // call function accessDenied if username has // not been verified if ( !$userVerified ) accessDenied();

// verify user password and return a boolean function checkPassword( $userpassword, $filedata ) { if ( $userpassword == $filedata[ 1 ] ) return true; else return false;

2004 Prentice Hall, Inc.


All rights reserved.

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

// print a message indicating the user has been added function userAdded( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>You have been added to the user list, $name. <br />Enjoy the site.</strong>" ); } // print a message indicating permission // has been granted function accessGranted( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>Permission has been granted, $name. <br /> Enjoy the site.</strong>" ); }

84

Outline
password.php (5 of 7)

2004 Prentice Hall, Inc.


All rights reserved.

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

// print a message indicating password is invalid function wrongPassword() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong>You entered an invalid password.<br />Access has been denied.</strong>" ); } // print a message indicating access has been denied function accessDenied() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> You were denied access to this server. <br /></strong>" ); }

85

Outline
password.php (6 of 7)

2004 Prentice Hall, Inc.


All rights reserved.

142 143 144 145 146 147 148 149 150 151 152 153 154 ?>

// print a message indicating that fields // have been left blank function fieldsBlank() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> Please fill in all form fields. <br /></strong>" ); } </body>

86

Outline
password.php (7 of 7)

155 </html>

2004 Prentice Hall, Inc.


All rights reserved.

87

26.6 Verifying a Username and Password


Fig. 26.16 Verifying a username and password.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9

account1,password1 account2,password2 account3,password3 account4,password4 account5,password5 account6,password6 account7,password7 account8,password8 account9,password9

88

Outline
password.txt (1 of 1)

10 account10,password10

2004 Prentice Hall, Inc.


All rights reserved.

89

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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.18: data.html -->

90

Outline
data.html (1 of 2)

<!-- Querying a MySQL Database --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample Database Query</title> </head> <body style = "background-color: #F0E68C"> <h2 style = "font-family: arial color: blue"> Querying a MySQL database. </h2> <form method = "post" action = "database.php"> <p>Select a field to display: <!-- add a select box containing options --> <!-- for SELECT query -->

2004 Prentice Hall, Inc.


All rights reserved.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 </body>

<select name = "select"> <option selected = "selected">*</option> <option>ID</option> <option>Title</option> <option>Category</option> <option>ISBN</option> </select> </p> <input type = "submit" value = "Send Query" style = "background-color: blue; color: yellow; font-weight: bold" /> </form>

91

Outline
data.html (2 of 2)

36 </html>

2004 Prentice Hall, Inc.


All rights reserved.

92

26.7 Connecting to a Database


Fig. 26.18 Form to query a MySQL database.

2004 Prentice Hall, Inc. All rights reserved.

93

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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.19: database.php <!-- send results to the client. --> -->

94

Outline
database.php (1 of 3)

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

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Search Results</title> </head> <body style = "font-family: arial, sans-serif" style = "background-color: #F0E68C"> <?php extract( $_POST ); // build SELECT query $query = "SELECT " . $select . " // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" );

Function mysql_connect returns a database handle which represents PHPs connection to a database. If this connection is not made, function FROM Books"; die is called to terminate script execution.

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // fetch each record in result set for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ <?php <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Search Results</h3> ?> } // query Products database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() ); // open Products database if ( !mysql_select_db( "Products", $database ) ) die( "Could not open Products database" );

95

Outline
database.php (2 of 3)

Function mysql_fetch_row returns an array containing the elements of each row in the result set of our query ($result).
2004 Prentice Hall, Inc.
All rights reserved.

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 </body> 75 </html> </h5> </table> ?> }

// build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" );

96

Outline
database.php (3 of 3)

mysql_close( $database );

<br />Your search yielded <strong> <?php print( "$counter" ) ?> results.<br /><br /></strong> <h5>Please email comments to <a href = "mailto:deitel@deitel.com"> Deitel and Associates, Inc. </a>

2004 Prentice Hall, Inc.


All rights reserved.

97

26.7 Connecting to a Database


Fig. 26.19 Querying a database and displaying the results.

2004 Prentice Hall, Inc. All rights reserved.

98

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
2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.20: cookies.html --> <!-- Writing a Cookie -->

99

Outline
cookies.html (1 of 2)

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Writing a cookie to the client computer</title> </head> <body style = "font-family: arial, sans-serif; background-color: #99CCFF"> <h2>Click Write Cookie to save your cookie data.</h2>

2004 Prentice Hall, Inc.


All rights reserved.

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

<form method = "post" action = "cookies.php" style = "font-size: 10pt"> <strong>Name:</strong><br /> <input type = "text" name = "NAME" /><br /> <strong>Height:</strong><br /> <input type = "text" name = "HEIGHT" /><br /> <strong>Favorite Color:</strong><br /> <input type = "text" name = "COLOR" /><br /> <input type = "submit" value = "Write Cookie" style = "background-color: #F0E86C; color: navy; font-weight: bold" /></p> </form> </body>

100

Outline
Form data is posted to cookies.php. cookies.html (2 of 2)

33 </html>

2004 Prentice Hall, Inc.


All rights reserved.

101

26.8 Cookies
Fig. 26.20 Gathering data to be written as a cookie.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<?php // Fig. 26.21: cookies.php // Program to write a cookie to a client's machine extract( $_POST ); // write each form fields value to a cookie and set the // cookies expiration date setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );

102

Outline
cookies.php (1 of 2)

11 ?> 12 13 14 15

Function setcookie takes the name of the cookie to be set as the first argument, <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" followed by the value to be stored in the "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> cookie. The optional third argument specifies the expiration date of the cookie.
<head> <title>Cookie Saved</title> </head> <body style = "font-family: arial, sans-serif"> <p>The cookie has been set with the following data:</p>

16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 18 19 20 21 22 23

2004 Prentice Hall, Inc.


All rights reserved.

24 25 26 27 28 29 30 31 32 33 34 35 36 37

<!-- print each form fields value --> <br /><span style = "color: blue">Name:</span> <?php print( $NAME ) ?><br /> <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br /> <span style = "color: blue">Favorite Color:</span> <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?> </span><br /> <p>Click <a href = "readCookies.php">here</a> to read the saved cookie.</p> </body>

103

Outline
cookies.php (2 of 2)

38 </html>

Hyperlink to readCookies.php.

2004 Prentice Hall, Inc.


All rights reserved.

104

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

2004 Prentice Hall, Inc. All rights reserved.

105

26.8 Cookies Reading cookies


$_COOKIE environment variable Array foreach loop to access each element Split into key and value

2004 Prentice Hall, Inc. All rights reserved.

106

26.8 Cookies Cookie storage


Internet Explorer
Stores cookies in Cookies directory Text file

2004 Prentice Hall, Inc. All rights reserved.

107

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

Fig. 26.23 Cookies directory after a cookie is written.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.24: readCookies.php -->

108

Outline
readCookies.php (1 of 2)

<!-- Program to read cookies from the client's computer --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>Read Cookies</title></head> <body style = "font-family: arial, sans-serif"> <p> <strong> The following data is saved in a cookie on your computer. </strong> </p>

2004 Prentice Hall, Inc.


All rights reserved.

19 20 21 22 23 24 25 26 27 28 29 30 31 32

<table border = "5" cellspacing = "0" cellpadding = "10"> <?php // iterate through array $_COOKIE and print // name and value of each cookie foreach ( $_COOKIE as $key => $value ) print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" ); ?> </table> </body>

109

Outline
readCookies.php (2 of 2)

33 </html>

2004 Prentice Hall, Inc.


All rights reserved.

110

26.8 Cookies
Fig. 26.24 Displaying the cookies content.

2004 Prentice Hall, Inc. All rights reserved.

111

26.9 Dynamic Content in PHP Dynamically alter XHTML content


Forms action property set to same page that contains it Perform different actions when page is loaded and form is submitted
isset variable

Check for errors


Write different XHTML when errors encountered $$variable syntax References variable whose name equals the value of $variable

If input is valid, make MySQL database calls

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.25: dynamicForm.php -->

112

Outline
dynamicForm.php (1 of 9)

<!-- Form for use with the form.php program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sample form to take user input in XHTML</title>

10 </head> 11 12 <body> 13 14 15 16 17 18 19 20 21 22 // array of book titles $booklist = array( "Internet and WWW How to Program 3e", "C++ How to Program 4e", "Java How to Program 5e", "XML How to Program 1e" ); <?php extract ( $_POST ); $iserror = false;

Build array of options for the form.

2004 Prentice Hall, Inc.


All rights reserved.

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

// array of possible operating systems $systemlist = array( "Windows XP", "Windows 2000", "Windows 98", "Linux", "Other"); // array of name and alt values for the text input fields $inputlist = array( "fname" => "First Name", "lname" => "Last Name", "email" => "Email", "phone" => "Phone" ); if ( isset ( $submit ) ) { if ( $fname == "" ) { $formerrors[ "fnameerror" ] = true; $iserror = true; } if ( $lname == "" ) { $formerrors[ "lnameerror" ] = true; $iserror = true; }

113

Outline
dynamicForm.php (2 of 9)

2004 Prentice Hall, Inc.


All rights reserved.

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

if ( $email == "" ) { $formerrors[ "emailerror" ] = true; $iserror = true; } if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) { $formerrors[ "phoneerror" ] = true; $iserror = true; } if ( !$iserror ) {

114

Outline
dynamicForm.php (3 of 9)

If there were no errors, query the MySQL database.

// build INSERT query $query = "INSERT INTO contacts " . "( LastName, FirstName, Email, Phone, Book, OS ) " . "VALUES ( '$lname', '$fname', '$email', " . "'" . quotemeta( $phone ) . "', '$book', '$os' )"; // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" ); // open MailingList database if ( !mysql_select_db( "MailingList", $database ) ) die( "Could not open MailingList database" );

2004 Prentice Hall, Inc.


All rights reserved.

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 <table border = '0' cellpadding = '0' cellspacing = '10'> <tr> <td bgcolor = '#ffffaa'>Name</td> <td bgcolor = '#ffffbb'>Email</td> <td bgcolor = '#ffffcc'>Phone</td> You have been added to the <span style = 'color: blue'> <strong>$book</strong></span> mailing list. </p> <strong>The following information has been saved in our database:</strong><br /> print( "<p>Hi <span style = 'color: blue'> <strong>$fname</strong></span>. Thank you for completing the survey.<br /> } // execute query in MailingList database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() );

115

Outline
dynamicForm.php (4 of 9)

2004 Prentice Hall, Inc.


All rights reserved.

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 } }

<td bgcolor = '#ffffdd'>OS</td> </tr> <tr> <!-- print each form fields value --> <td>$fname $lname</td> <td>$email</td> <td>$phone</td> <td>$os</td> </tr></table> <br /><br /><br /> <div style = 'font-size: 10pt; text-align: center'> <div style = 'font-size : 18pt'> <a href = 'formDatabase.php'> Click here to view entire database.</a></div> This is only a sample form. You have not been added to a mailing list. </div></body></html>" ); die();

116

Outline
dynamicForm.php (5 of 9)

Halt the script so the form-generation code does not execute.

print( "<h1>This is a sample registration form.</h1> Please fill in all fields and click Register." );

2004 Prentice Hall, Inc.


All rights reserved.

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 } print( "<br />" ); if ( $formerrors[ ( $inputname )."error" ] == true ) print( "<span style = 'color : red'>*</span>" ); print( "<img src = 'images/$inputname.gif' alt = '$inputalt' /><input type = 'text' name = '$inputname' value = '" . $$inputname . "' />" ); <!-- create four text boxes for user input -->" ); foreach ( $inputlist as $inputname => $inputalt ) { $inputtext = $inputvalues[ $inputname ]; print( "<!-- post form data to form.php --> <form method = 'post' action = 'dynamicform.php'> <img src = 'images/user.gif' alt = 'User' /><br /> <span style = 'color: blue'> Please fill out the fields below.<br /> </span> } if ( $iserror ) { print( "<br /><span style = 'color : red'> Fields with * need to be filled in properly.</span>" );

117

Outline
dynamicForm.php (6 of 9)

2004 Prentice Hall, Inc.


All rights reserved.

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 if ( ( $currbook == $book ) ) print( " selected = 'true'" ); foreach ( $booklist as $currbook ) { print( "<option" ); <!-- create drop-down list containing book names --> <select name = 'book'>" ); <span style = 'color: blue'> Which book would you like information about? </span><br /> <img src = 'images/downloads.gif' alt = 'Publications' /><br /> print( "'>Must be in the form (555)555-5555 </span><br /><br /> if ( $formerrors[ "phoneerror" ] ) print( "; color : red" ); print( "<span style = 'font-size : 10pt" );

118

Outline
dynamicForm.php (7 of 9)

Make sure the correct book is selected in the dropdown box.

2004 Prentice Hall, Inc.


All rights reserved.

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 } }

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

119

Outline
<img src = 'images/os.gif' alt = 'Operating System' /> <br /><span style = 'color: blue'> Which operating system are you currently using? <br /></span> <!-- create five radio buttons -->" );

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

dynamicForm.php (8 of 9)

$counter = 0; foreach ( $systemlist as $currsystem ) { print( "<input type = 'radio' name = 'os' value = '$currsystem'" ); if ( $currsystem == $os ) print( "checked = 'checked'" ); if ( $iserror && $counter == 0 ) print( "checked = 'checked'" ); print( " />$currsystem" ); if ( $counter == 2 ) print( "<br />" ); $counter++;

2004 Prentice Hall, Inc.


All rights reserved.

200 201 202 203 204 ?>

print( "<!-- create a submit button --> <br /> <input type = 'submit' name = 'submit' value = 'Register' /> </form></body></html>" );

120

Outline
dynamicForm.php (9 of 9)

2004 Prentice Hall, Inc.


All rights reserved.

121

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

2004 Prentice Hall, Inc. All rights reserved.

122

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 26.26: formDatabase.php <!-- Program to query a database and --> <!-- send results to the client. --> -->

123

Outline
formDatabase.php (1 of 3)

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Search Results</title> </head> <body style = "font-family: arial, sans-serif" style = "background-color: #F0E68C"> <?php

Build the query string.


extract( $_POST ); // build SELECT query $query = "SELECT * FROM contacts"; // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" );

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <tr> <td>ID</td> <td>Last Name</td> <td>First Name</td> <td>E-mail Address</td> <td>Phone Number</td> <td>Book</td> <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Mailing List Contacts</h3> ?> } // query MailingList database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() ); // open MailingList database if ( !mysql_select_db( "MailingList", $database ) ) die( "Could not open MailingList database" );

124

Outline
formDatabase.php (2 of 3)

2004 Prentice Hall, Inc.


All rights reserved.

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 </body> 75 </html> ?>

<td>Operating System</td> </tr> <?php // fetch each record in result set for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ // build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database );

125

Outline
formDatabase.php (3 of 3)

</table>

2004 Prentice Hall, Inc.


All rights reserved.

126

26.9 Dynamic Content in PHP


Fig. 26.26 Displaying the MailingList database.

2004 Prentice Hall, Inc. All rights reserved.

127

26.10 Operator Precedence


Operator new [] ~ ! ++ -@ * / % + . << >> < > <= >= == != === !== Fig. 26.27 Type
constructor subscript bitwise not not increment decrement unary negative error control multiplication division modulus addition subtraction concatenation bitwise shift left bitwise shift right less than greater than less than or equal greater than or equal equal not equal identical not identical

Associativity
none right to left right to left

left to right

left to right

left to right none

none

PHP operator precedence and associativity.

2004 Prentice Hall, Inc. All rights reserved.

128

26.10 Operator Precedence


Operator & ^ | && || = += -= *= /= &= |= ^= .= <<= >>= and xor or , Fig. 26.27 Type
bitwise AND bitwise XOR bitwise OR logical AND logical OR assignment addition assignment subtraction assignment multiplication assignment division assignment bitwise AND assignment bitwise OR assignment bitwise exclusive OR assignment concatenation assignment bitwise shift left assignment bitwise shift right assignment logical AND exclusive OR logical OR list

Associativity
left to right left to right left to right left to right left to right left to right

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

PHP operator precedence and associativity.

2004 Prentice Hall, Inc. All rights reserved.

S-ar putea să vă placă și