Sie sind auf Seite 1von 118

1

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

2003 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.

2003 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

2003 Prentice Hall, Inc. All rights reserved.

Why is PHP used?


1. Easy to Use
Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode".

<html> <head> <title>Example</title> </head> <body>

<?php echo "Hi, I'm a PHP script!"; ?>


</body> </html>

2003 Prentice Hall, Inc. All rights reserved.

Why is PHP used?


2. Cross Platform
Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases

Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MSSQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm

2003 Prentice Hall, Inc. All rights reserved.

Why is PHP used?


3. Cost Benefits
PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free.

PHP
Software Platform
Development Tools

Free Free (Linux)


Free PHP Coder, jEdit

2003 Prentice Hall, Inc. All rights reserved.

26.2 PHP
How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag
HTML
PHP CODE

HTML

<?php echo Hello World; ?>

Starting tag
<?php <? <script language="php">

Ending tag Notes


?> ?> ?> Preferred method as it allows the use of PHP with XHTML Not recommended. Easier to type, but has to be enabled and may conflict with XML Always available, best if used when FrontPage is the HTML editor Not recommended. ASP tags support was added in 3.0.4

<%

%>

2003 Prentice Hall, Inc. All rights reserved.

26.2 PHP Basic application


Variables preceded by $ symbol
Case-sensitive

End statements with semicolon Comments


// for single line /* */ for multiline

Filenames end with .php by convention

2003 Prentice Hall, Inc. All rights reserved.

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>

2003 Prentice Hall, Inc.


All rights reserved.

10

26.2 PHP
Fig. 26.1 Simple PHP program.

2003 Prentice Hall, Inc. All rights reserved.

11

26.2 PHP Variables


Can have different types at different times Variable names inside strings replaced by their value Type conversions
settype function

Type casting

Concatenation operator . (period)


Combine strings

2003 Prentice Hall, Inc. All rights reserved.

12

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

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

13

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

Assign a string to variable


$testString

// declare a string, double and integer $testString = "3.5 seconds"; $testDouble = 79.2; $testInteger = 12; ?>

Assign a double to variable Assign an integer to variable $testDouble


$testInteger

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

14

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

Call function settype print( "Converting back to a string results in

to convert the data type $testString <br /><br />" ); settype Call function to of variable $testString to a convert the data type of double. $data = "98.6 degrees"; variable $testString to an integer. Convert variable $testString back to a string
2003 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 );

15

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

53 </html>

2003 Prentice Hall, Inc.


All rights reserved.

16

26.2 PHP
Fig. 26.3 Type conversion.

2003 Prentice Hall, Inc. All rights reserved.

17

26.2 PHP Arithmetic operators


Assignment operators
Syntactical shortcuts Before being assigned values, variables have value undef

Constants
Named values define function

2003 Prentice Hall, Inc. All rights reserved.

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

18

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

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

19

Multiply variable $a by two using the multiplication assignment operator *=.

Outline

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

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

Add 40 to variable $a using the addition assignment operator +=.

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

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

20

Outline
operators.php (3 of 3)

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

Add a string to an integer.

65 </html>

2003 Prentice Hall, Inc.


All rights reserved.

21

26.2 PHP
Fig. 26.4 Using PHPs arithmetic operators.

2003 Prentice Hall, Inc. All rights reserved.

22

26.2 PHP Keywords


Reserved for language features
ifelseifelse

Arrays
Group of related data
Elements

Name plus braces and index


Indices start at zero count function

array function

2003 Prentice Hall, Inc. All rights reserved.

23

26.2 PHP Arrays, cont.


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

foreach loops

2003 Prentice Hall, Inc. All rights reserved.

24

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.

2003 Prentice Hall, Inc. All rights reserved.

Array

Untuk menambahkan menggunakan kurung kotak tanpa isi index ( [] ) Tipe element tidak perlu di sebutkan, bisa berisi tipe macammacam

2003 Prentice Hall, Inc. All rights reserved.

Fungsi-fungsi Array

2003 Prentice Hall, Inc. All rights reserved.

Contoh Array

2003 Prentice Hall, Inc. All rights reserved.

Loop for ( Seperti di C )

2003 Prentice Hall, Inc. All rights reserved.

Statement if / else

Elseif adalah keyword yang sering dipakai, walaupun else if juga support

2003 Prentice Hall, Inc. All rights reserved.

Loop while

Keyword break dan continue bisa digunakan dan mirip seperti di Java dan C

2003 Prentice Hall, Inc. All rights reserved.

Loop foreach

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

32

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 ] = Assign "one";

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

a value to the array, omitting the index. for loop print each elements index and value. $first[ 2 ] = Appends "two"; a Use newaelement to to the end out of the array. Function count returns the total number of elements in the $first[] = "three"; array.
// print each elements index and value for ( $i = 0; $i < count( $first ); $i++ ) print( "Element $i is $first[$i] <br />" );

2003 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[ "GalAnt" ] = $third[ "LunaTic" ] = 18; print( "<br /><strong>Creating the third array </strong><br />" ); // call function $second = array( print( "<br /><strong>Creating the second array </strong><br />" );

33

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

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

Assign values to non-numerical indices in array $third. 23; 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.
2003 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",

34

Outline
arrays.php (3 of 3)

"September" =>

Operator =>=> is used in function array to assign each "fifth", "June" "sixth", element a string index. The value to the left of the "seventh", "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>

2003 Prentice Hall, Inc.


All rights reserved.

35

26.2 PHP
Fig. 26.6 Array manipulation.

2003 Prentice Hall, Inc. All rights reserved.

36

26.3 String Processing and Regular Expressions String processing


Equality and comparison two important operations strcmp function
Returns 1 if string 1 < string 2 Returns 0 if string 1 = string 2 Returns 1 if string 1 > string 2

Relational operators

2003 Prentice Hall, Inc. All rights reserved.

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

37

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 for ( $i = 0; $i <

Function strcmp compares two strings. If the first string alphabetically precedes the second, then 1 is returned. If each array element the strings are equal, 0 is returned. If the first string count( $fruits ); $i++ ) { alphabetically follows the second, then 1 is returned.

// call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " );

2003 Prentice Hall, Inc.


All rights reserved.

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

38

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>

2003 Prentice Hall, Inc.


All rights reserved.

39

26.3 String Processing and Regular Expressions


Fig. 26.7 Using the string comparison operators.

2003 Prentice Hall, Inc. All rights reserved.

40

26.3 String Processing and Regular Expressions Regular expressions


Pattern matching templates ereg function
POSIX preg_match function Perl ereg_replace function

Building regular expressions


Metacharacters
$, ., ^

Brackets [ ]

2003 Prentice Hall, Inc. All rights reserved.

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 $search = "Now is

41

Outline
expression.php (1 of 3)

Function ereg searches for the literal Now inside variable $search. the characters 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 />" );

2003 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

42

Outline

//

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

if ( ereg( "Now$", $search ) ) 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

while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", $search, $match ) ) { print( $match[ 1 ] . " " );

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

The pattern used in this example,

[[:<:]](t[[:alpha:]]+)[[:>:]], matches any The while word loop is used to find each occurrence of a beginning with the character t followed by one or Function eregi is used to specify case insensitive word in themore string beginningCharacter with t. class [[:alpha:]] characters. pattern matches.
All rights reserved.

recognizes any alphabetic character. 2003 Prentice Hall, Inc.

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

43

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.

2003 Prentice Hall, Inc.


All rights reserved.

44

26.3 String Processing and Regular Expressions


Fig. 26.8 Regular expressions in PHP.

2003 Prentice Hall, Inc. All rights reserved.

45

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.

2003 Prentice Hall, Inc. All rights reserved.

46

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.

2003 Prentice Hall, Inc. All rights reserved.

47

26.4 Viewing Client/Server Environment Variables Environment variables


Provide information about execution environment
Type of Web browser Type of server Details of HTTP connection

Stored as array in PHP


$_ENV

2003 Prentice Hall, Inc. All rights reserved.

48

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.

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

49

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> The foreach loop ?> </table> </body>

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

26 </html>

2003 Prentice Hall, Inc.


All rights reserved.

50

26.4 Viewing Client/Server Environment Variables


Fig. 26.12 Displaying environment variables.

2003 Prentice Hall, Inc. All rights reserved.

51

26.5 Form Processing and Business Logic Form processing


action property Where to send form data method property
post

Each element has unique name

2003 Prentice Hall, Inc. All rights reserved.

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

52

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 Please fill

The action attribute of the form element indicates that when the user clicks Register, the a sample registration form.</h1> in all fields and click Register. form data will be posted to form.php.

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

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

53

A unique name (e.g., email) is assigned to each Outline of the forms input fields. When Register is clicked, each fields name and value are sent to form.html <img src = "images/lname.gif" alt = "Last Name" /> the Web server. (2 of 4) <input type = "text" name = "lname" /><br />
<input type = "text" name = "fname" /><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 />

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

2003 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 />

54

Outline
form.html (3 of 4)

2003 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

55

Outline
form.html (4 of 4)

2003 Prentice Hall, Inc.


All rights reserved.

56

26.5 Form Processing and Business Logic


Fig. 26.13 XHTML form for gathering user input.

2003 Prentice Hall, Inc. All rights reserved.

57

26.5 Form Processing and Business Logic Business logic


Confirm that valid information was entered extract function
Creates variables corresponding to each key-value pair in array Easily retrieve all values sent to PHP page

Regular expressions very helpful Do checks on client side where possible


JavaScript Conserves server resources

Ending a script
die function Remember to close all HTML tags
2003 Prentice Hall, Inc. All rights reserved.

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

58

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

Function ereg is called to determine whether the The parentheses in the expression must be phone number entered by the user is valid. followed by The three digits ([0-9]{3} ), a closing expression \( matches the opening ); parenthesis, parentheses three digits, of a literal hyphen and a phone number. four additional digits.

// 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.

2003 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

59

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

2003 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

60

Outline
form.php (3 of 4)

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

61

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>

2003 Prentice Hall, Inc.


All rights reserved.

62

26.5 Form Processing and Business Logic


Fig. 26.14 Obtaining user input through forms.

2003 Prentice Hall, Inc. All rights reserved.

63

26.6 Verifying a Username and Password Private website


Only accessible to certain individuals Encrypt username and password data when sending, storing and retrieving for increased security

Implementing password checking


Login information stored in file
fopen function

Read, write, append modes

Store data using fputs


\n newline character

Close files when done


fclose function

2003 Prentice Hall, Inc. All rights reserved.

64

26.6 Verifying a Username and Password Implementing password checking, cont.


Trim newline character
chop function

Split string into substrings given a certain delimiter


split function

If username/password match list, allow access

2003 Prentice Hall, Inc. All rights reserved.

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

65

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>

2003 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 />

66

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>

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

67

Outline
password.html (3 of 4)

2003 Prentice Hall, Inc.


All rights reserved.

72 73 74 75

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

68

Outline
password.html (4 of 4)

76 </html>

2003 Prentice Hall, Inc.


All rights reserved.

69

26.6 Verifying a Username and Password


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

2003 Prentice Hall, Inc. All rights reserved.

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

70

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

Variable names, when preceded by the logical negation operator (!), return true if they are empty or set to 0. This checks if a user has submitted a form without specifying a username or password. Function fieldsBlank is called if the user has submitted an incomplete formthe to notify the user Function isset tests whether user has that all form fields must be completed. pressed the New User button, indicating that a new user must be added.

// check if user has left USERNAME or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); }

// check if the New User button was clicked To add a if ( isset( $NewUser ) ) {

new user, we open the file password.txt in append mode and assign the file handle that is returned to variable $file.

// open password.txt for writing using append mode if ( !( $file = fopen( "password.txt", "a" ) ) ) {

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

71

Outline

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

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

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

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

72

Outline
// read each line in file and check username Before entering the while // and password while ( !feof(

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

password.php (3 of 7)

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

// read line from file

If function // call function checkPassword to verify


// users password == true ) accessGranted( $USERNAME ); else wrongPassword();

checkPassword returns true, function accessGranted is called to notify the client that

if ( checkPassword( $PASSWORD, $field ) permission

has been granted. Otherwise, function wrongPassword is called.

Function checkPassword is called to verify the users password. Variable $PASSWORD and array $field are passed to the function. 2003 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 } } }

73

// close text fclose( $file

If variable $userVerified has not been set to a the while loop has executed, value otherAfter than 0 , function accessDenied is function file fclose is called to close the called to notify the client that access has file. been password.php ); denied. (4 of 7) Function checkPassword compares the users password to the password in the file. If they match, true is returned, whereas false is returned if they do not.

Outline

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

2003 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; Function userAdded font-size: 1em; <strong>You have been added to the user list, $name. <br />Enjoy the }

74

Outline
password.php (5 of 7)

prints a message to the color: blue\"> client indicating that the user has been added.

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

// 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>" ); }

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

75

Outline

Function wrongPassword prints a message to the client indicating that the password is invalid. password.php <body style = \"font-family: arial; (6 of 7) font-size: 1em; color: red\">
<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>" ); }

Function accessDenied prints a message to the client indicating that access has been denied.

2003 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() {

76

Function fieldsBlank prints a message to Outline the client indicating that all form fields have not been completed. print( "<title>Access Denied</title></head> password.php <body style = \"font-family: arial; (7 of 7)
font-size: 1em; color: red\"> <strong> Please fill in all form fields. <br /></strong>" );

} </body>

155 </html>

2003 Prentice Hall, Inc.


All rights reserved.

77

26.6 Verifying a Username and Password


Fig. 26.16 Verifying a username and password.

2003 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

78

Outline
password.txt (1 of 1)

10 account10,password10

2003 Prentice Hall, Inc.


All rights reserved.

79

26.7 Connecting to a Database Databases


Store and maintain data MySQL is a free database product PHP supports many database operations
Access databases from Web pages

2003 Prentice Hall, Inc. All rights reserved.

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

80

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

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

81

Outline

Select box containing options for a SELECT data.html query. (2 of 2)

36 </html>

2003 Prentice Hall, Inc.


All rights reserved.

82

26.7 Connecting to a Database


Fig. 26.18 Form to query a MySQL database.

2003 Prentice Hall, Inc. All rights reserved.

83

26.7 Connecting to a Database Interacting with databases


SQL
Structured Query Language Used to manipulate databases

Several useful functions


mysql_connect mysql_select_db mysql_query mysql_error mysql_fetch_row mysql_close

2003 Prentice Hall, Inc. All rights reserved.

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

84

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

Build the select query and assign the string to variable $query. 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.

extract( $_POST ); // build SELECT query $query = "SELECT " . $select . " // Connect to MySQL

if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" );

2003 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 <?php <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <h3 style = "color: blue"> Search Results</h3> ?> } // if // open Products database

85

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

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

Outline

The for loop iterates through each record in the result set while // fetch each record in result set constructing an XHTML table from for ( $counter = 0; the results. Variable $counter is $row = mysql_fetch_row( $result incremented ); by one for each row $counter++ ){ Function mysql_fetch_row returns an retrieved. array containing the elements of each row in the result set of our query ($result).
2003 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 )

86

Outline

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

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

2003 Prentice Hall, Inc.


All rights reserved.

87

26.7 Connecting to a Database


Fig. 26.19 Querying a database and displaying the results.

2003 Prentice Hall, Inc. All rights reserved.

88

26.8 Cookies Cookies


Store information on client computer Track preferences and other information Stored as text files on hard drive Never store sensitive information, such as credit card numbers, in a cookie
Security risk

Cookies and PHP


setcookie function Name Value Expiration date
2003 Prentice Hall, Inc. All rights reserved.

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

89

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>

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

90

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

33 </html>

2003 Prentice Hall, Inc.


All rights reserved.

91

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

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

92

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

2003 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> Each <?php print( $NAME ) ?><br /> <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br />

form fields value is printed to Outline confirm the data that has been set as a cookie with the user. cookies.php (2 of 2)

93

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

38 </html>

Hyperlink to readCookies.php.

2003 Prentice Hall, Inc.


All rights reserved.

94

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

2003 Prentice Hall, Inc. All rights reserved.

95

26.8 Cookies Reading cookies


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

2003 Prentice Hall, Inc. All rights reserved.

96

26.8 Cookies Cookie storage


Internet Explorer
Stores cookies in Cookies directory Text file

2003 Prentice Hall, Inc. All rights reserved.

97

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

Fig. 26.23 Cookies directory after a cookie is written.

2003 Prentice Hall, Inc. All rights reserved.

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

98

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>

2003 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

99

The foreach loop iterates through the $_COOKIE Outline PHP creates array $_COOKIE which contains array and prints the name and value of each cookie all cookie values indexed by their names. // iterate through array $_COOKIE and print in an XHTML table. readCookies.php // name and value of each cookie (2 of 2) foreach ( $_COOKIE as $key => $value )
print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" );

?> </table> </body>

33 </html>

2003 Prentice Hall, Inc.


All rights reserved.

100

26.8 Cookies
Fig. 26.24 Displaying the cookies content.

2003 Prentice Hall, Inc. All rights reserved.

101

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

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

102

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.

2003 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" =>

103

Outline
dynamicForm.php (2 of 9)

If the page is being loaded as a result of a form submission, do error checking and then field retrieve Check for errors or omissions in form "Phone" ); information from the database. input.

if ( isset ( $submit ) ) { if ( $fname == "" ) { $formerrors[ "fnameerror" ] = true; $iserror = true; } if ( $lname == "" ) { $formerrors[ "lnameerror" ] = true; $iserror = true; }

2003 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 ) {

104

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

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

105

Outline
dynamicForm.php (4 of 9)

2003 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. </div></body></html>" ); die(); You have not been added to a mailing list.

106

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

2003 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' <!-- 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>" );

107

Outline
dynamicForm.php (6 of 9)

Fill in the forms using $$variable syntax.

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

If the form input contained errors, place a red asterisk (*) next to the text field.

2003 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'" ); print( "<option" ); <!-- create drop-down list containing book names --> <select name = 'book'>" ); foreach ( $booklist as $currbook ) { <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" );

108

Outline
dynamicForm.php (7 of 9)

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

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

109

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 ) { value =

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

Make sure the correct OS is checked in the checkbox. '$currsystem'" );

if ( $currsystem == $os ) print( "checked = 'checked'" ); if ( $iserror && $counter == 0 ) print( "checked = 'checked'" ); print( " />$currsystem" ); if ( $counter == 2 ) print( "<br />" ); $counter++;

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

110

Outline
dynamicForm.php (9 of 9)

2003 Prentice Hall, Inc.


All rights reserved.

111

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

2003 Prentice Hall, Inc. All rights reserved.

112

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

2003 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. --> -->

113

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

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

114

Outline
formDatabase.php (2 of 3)

2003 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 for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ // build table to print( "<tr>" );

115

Outline
Retrieve each mailing list member record from the resultdatabase. set formDatabase.php (3 of 3)

Dynamically create a table display results containing each mailing list member.

foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } mysql_close( $database );

</table>

2003 Prentice Hall, Inc.


All rights reserved.

116

26.9 Dynamic Content in PHP


Fig. 26.26 Displaying the MailingList database.

2003 Prentice Hall, Inc. All rights reserved.

117

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.

2003 Prentice Hall, Inc. All rights reserved.

118

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.

2003 Prentice Hall, Inc. All rights reserved.

Das könnte Ihnen auch gefallen