2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 26 - PHP Outline 26.1 Introduction 26.2 PHP 26.3 String Processing and Regular Expressions 26.4 Viewing Client/Server Environment Variables 26.5 Form Processing and Business Logic 26.6 Verifying a Username and Password 26.7 Connecting to a Database 26.8 Cookies 26.9 Dynamic Content in PHP 26.10 Operator Precedence 26.11 Web Resources
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 26 - PHP
Outline26.1 Introduction
26.2 PHP
26.3 String Processing and Regular Expressions
26.4 Viewing Client/Server Environment Variables26.5 Form Processing and Business Logic
26.6 Verifying a Username and Password
26.7 Connecting to a Database
26.8 Cookies26.9 Dynamic Content in PHP
26.10 Operator Precedence
26.11 Web Resources
2003 Prentice Hall, Inc. All rights reserved.
2
Objectives
In this chapter, you will learn:– To understand PHP data types, operators, arrays and control
structures.
– To understand string processing and regular expressions in
PHP.
– To construct programs that process form data.
– To be able to read and write client data using cookies.
– To construct programs that interact with MySQL databases.
2003 Prentice Hall, Inc. All rights reserved.
3
26.1 Introduction
• PHP– PHP: Hypertext Preprocessor
– Originally called “Personal Home Page Tools”
– Popular server-side scripting technology
– Open-source
• Anyone may view, modify and redistribute source code
• Supported freely by community
– Platform independent
2003 Prentice Hall, Inc. All rights reserved.
4
26.2 PHP
• Basic application– Scripting delimiters
• <? php ?>
• Must enclose all script code
– Variables preceded by $ symbol
• Case-sensitive
– End statements with semicolon
– Comments
• // for single line
• /* */ for multiline
– Filenames end with .php by convention
2003 Prentice Hall, Inc.
All rights reserved.
Outline51 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"
16 <body styl <body styl <body styl <body style = e = e = e = "font"font"font"font----size: 2em"size: 2em"size: 2em"size: 2em">>>>
17 <p> <p> <p> <p>
18 <strong><strong><strong><strong>
19
20 <! <! <! <!-------- print variable name’s value print variable name’s value print variable name’s value print variable name’s value -------->>>>
21 Welcome to PHP, Welcome to PHP, Welcome to PHP, Welcome to PHP, <?php<?php<?php<?php print print print print( ( ( ( "$name""$name""$name""$name" ); ); ); ); ?>?>?>?>!!!!
22 </strong> </strong> </strong> </strong>
23 </p> </p> </p> </p>
24 </body> </body> </body> </body>
25 </htm</htm</htm</html>l>l>l>
first.php
(1 of 1)
Declare variable $name
Scripting delimiters
Single-line comment
Function print outputs the value of variable $name
2003 Prentice Hall, Inc. All rights reserved.
6
26.2 PHPFig. 26.1 Simple PHP program.
2003 Prentice Hall, Inc. All rights reserved.
7
26.2 PHP
• Variables– Can have different types at different times
– Variable names inside strings replaced by their value
– Type conversions
• settype function
• Type casting
– Concatenation operator
• . (period)
• Combine strings
2003 Prentice Hall, Inc. All rights reserved.
8
26.2 PHP
Data type Description int, integer Whole numbers (i.e., numbers without a decimal point). float, double Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single ('') or double ("") quotes. bool, Boolean True or false. array Group of elements of the same type. object Group of associated data and methods. Resource An external data source. NULL No value.
Fig. 26.2 PHP data types.
2003 Prentice Hall, Inc.
All rights reserved.
Outline91 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Demonstration of PHP data types Demonstration of PHP data types Demonstration of PHP data types Demonstration of PHP data types -------->>>>
9 <title><title><title><title>PHP data typesPHP data typesPHP data typesPHP data types</title></title></title></title>
10 </head></head></head></head>
11
12 <body><body><body><body>
13
14 <?php<?php<?php<?php
15
16 // declare a string, double and integer// declare a string, double and integer// declare a string, double and integer// declare a string, double and integer
Assign a double to variable $testDoubleAssign an integer to variable $testInteger
2003 Prentice Hall, Inc.
All rights reserved.
Outline10
22 <!<!<!<!-------- print each variable’s value print each variable’s value print each variable’s value print each variable’s value -------->>>>
23 <?php<?php<?php<?php printprintprintprint( $testString ); ( $testString ); ( $testString ); ( $testString ); ?>?>?>?> is a string. is a string. is a string. is a string.<br /><br /><br /><br />
24 <?php<?php<?php<?php printprintprintprint( $testDouble ); ( $testDouble ); ( $testDouble ); ( $testDouble ); ?> ?> ?> ?> is a double.is a double.is a double.is a double.<br /><br /><br /><br />
25 <?php<?php<?php<?php printprintprintprint( $testInteger ); ( $testInteger ); ( $testInteger ); ( $testInteger ); ?> ?> ?> ?> is an integer.is an integer.is an integer.is an integer.<br /><br /><br /><br />
26
27 <br /><br /><br /><br />
28 Now, converting to other types: Now, converting to other types: Now, converting to other types: Now, converting to other types:<br /><br /><br /><br />
29 <?php<?php<?php<?php
30
31 // call function settype to convert variable // call function settype to convert variable // call function settype to convert variable // call function settype to convert variable
32 // testString to different data types // testString to different data types // testString to different data types // testString to different data types
35 printprintprintprint( ( ( ( " as a double is $testString <br />"" as a double is $testString <br />"" as a double is $testString <br />"" as a double is $testString <br />" ); ); ); );
38 printprintprintprint( ( ( ( " as an integer is $testString <br />"" as an integer is $testString <br />"" as an integer is $testString <br />"" as an integer is $testString <br />" ); ); ); );
40 printprintprintprint( ( ( ( "Converting back to a string results in"Converting back to a string results in"Converting back to a string results in"Converting back to a string results in
45 // use type casting to cast variables to a// use type casting to cast variables to a// use type casting to cast variables to a// use type casting to cast variables to a
46 // different type // different type // different type // different type
47 printprintprintprint( ( ( ( "Now using type casting instead: <br />"Now using type casting instead: <br />"Now using type casting instead: <br />"Now using type casting instead: <br />
48 As a string As a string As a string As a string ---- " " " " . ( . ( . ( . (stringstringstringstring) $data .) $data .) $data .) $data .
49 "<br />As a double "<br />As a double "<br />As a double "<br />As a double ---- " " " " . ( . ( . ( . (doubledoubledoubledouble) $data .) $data .) $data .) $data .
50 "<br />As an integer "<br />As an integer "<br />As an integer "<br />As an integer ---- " " " " . ( . ( . ( . (integerintegerintegerinteger) $data );) $data );) $data );) $data );
51 ?>?>?>?>
52 </body> </body> </body> </body>
53 </html></html></html></html>
data.php
(3 of 3)
Use type casting to cast variable
$data to different types
2003 Prentice Hall, Inc. All rights reserved.
12
26.2 PHPFig. 26.3 Type conversion.
2003 Prentice Hall, Inc. All rights reserved.
13
26.2 PHP
• Arithmetic operators– Assignment operators
• Syntactical shortcuts
• Before being assigned values, variables have value undef
• Constants– Named values
– define function
2003 Prentice Hall, Inc.
All rights reserved.
Outline141 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
15 printprintprintprint( ( ( ( "The value of variable a is $a <br />""The value of variable a is $a <br />""The value of variable a is $a <br />""The value of variable a is $a <br />" ); ); ); );
22 printprintprintprint( ( ( ( "Variable a after adding constant VALUE "Variable a after adding constant VALUE "Variable a after adding constant VALUE "Variable a after adding constant VALUE
25 // multiply variable $a by 2// multiply variable $a by 2// multiply variable $a by 2// multiply variable $a by 2
26 $a *= $a *= $a *= $a *= 2222;;;;
27 printprintprintprint( ( ( ( "Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />" ); ); ); );
28
29 // test if variable $a is less than 50// test if variable $a is less than 50// test if variable $a is less than 50// test if variable $a is less than 50
30 if if if if ( $a < ( $a < ( $a < ( $a < 50505050 ) ) ) )
31 prprprprintintintint( ( ( ( "Variable a is less than 50 <br />""Variable a is less than 50 <br />""Variable a is less than 50 <br />""Variable a is less than 50 <br />" ); ); ); );
32
33 // add 40 to variable $a // add 40 to variable $a // add 40 to variable $a // add 40 to variable $a
34 $a += $a += $a += $a += 40404040;;;;
35 printprintprintprint( ( ( ( "Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />" ); ); ); );
36
37 // test if variable $a is 50 or less// test if variable $a is 50 or less// test if variable $a is 50 or less// test if variable $a is 50 or less
39 printprintprintprint( ( ( ( "Variable a is still 50 or less<br />""Variable a is still 50 or less<br />""Variable a is still 50 or less<br />""Variable a is still 50 or less<br />" ); ); ); );
40
41 // test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive
43 printprintprintprint( ( ( ( "Variable a is now between 50 "Variable a is now between 50 "Variable a is now between 50 "Variable a is now between 50 and 100, and 100, and 100, and 100,
46 printprintprintprint( ( ( ( "Variable a is now greater than 100"Variable a is now greater than 100"Variable a is now greater than 100"Variable a is now greater than 100
47 <br />"<br />"<br />"<br />" ); ); ); );
48
operators.php
(2 of 3)
Multiply variable $a by two using the
multiplication assignment operator *=.
Test whether variable $a is less than 50
Add 40 to variable $a using the addition assignment operator +=.
Print if variable $a is less than 50.
2003 Prentice Hall, Inc.
All rights reserved.
Outline16
49 // print an uninitialized variable // print an uninitialized variable // print an uninitialized variable // print an uninitialized variable
50 printprintprintprint( ( ( ( "Using a variable before initializing:"Using a variable before initializing:"Using a variable before initializing:"Using a variable before initializing:
53 // add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable
61 prin prin prin printttt( ( ( ( "Adding a string to "Adding a string to "Adding a string to "Adding a string to variable avariable avariable avariable a yields $a yields $a yields $a yields $a
62 <br />"<br />"<br />"<br />" ); ); ); );
63 ?>?>?>?>
64 </body> </body> </body> </body>
65 </html></html></html></html>
operators.php
(3 of 3)
Add constant VALUE to an uninitialized
variable.
Add a string to an integer.
Print an uninitialized variable ($nothing).
2003 Prentice Hall, Inc. All rights reserved.
17
26.2 PHPFig. 26.4 Using PHP’s arithmetic operators.
2003 Prentice Hall, Inc. All rights reserved.
18
26.2 PHP
• Keywords– Reserved for language features
– if…elseif…else
• Arrays– Group of related data
• Elements
– Name plus braces and index
• Indices start at zero
– count function
– array function
2003 Prentice Hall, Inc. All rights reserved.
19
26.2 PHP
• Arrays, cont.– Built-in iterators
• Maintain pointer to element currently referenced
• reset
• key
• next
• foreach loops
2003 Prentice Hall, Inc. All rights reserved.
20
26.2 PHP
PHP keywords
and break case class continue default
do else elseif extends false
for foreach function global if
include list new not or
require return static switch this
true var virtual xor while
Fig. 26.5 PHP keywords.
2003 Prentice Hall, Inc.
All rights reserved.
Outline211 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
16 printprintprintprint( ( ( ( "<strong>Creating the first array</strong>"<strong>Creating the first array</strong>"<strong>Creating the first array</strong>"<strong>Creating the first array</strong>
23 // print each element’s index and value // print each element’s index and value // print each element’s index and value // print each element’s index and value
25 printprintprintprint( ( ( ( "Element $i is $first[$i] <br />""Element $i is $first[$i] <br />""Element $i is $first[$i] <br />""Element $i is $first[$i] <br />" ); ); ); );
arrays.php
(1 of 3)
Create the array $first by assigning a value
to an array element.
Assign a value to the array, omitting the index.
Appends a new element to the end of the array.Use a for loop to print out each element’s index and value.
Function count returns the total number of elements in the
array.
2003 Prentice Hall, Inc.
All rights reserved.
Outline22
26
27 printprintprintprint( ( ( ( "<br /><strong>Creating the second array"<br /><strong>Creating the second array"<br /><strong>Creating the second array"<br /><strong>Creating the second array
30 // call function array to create array second // call function array to create array second // call function array to create array second // call function array to create array second
33 printprintprintprint( ( ( ( "Element $i is $second[$i] <br />""Element $i is $second[$i] <br />""Element $i is $second[$i] <br />""Element $i is $second[$i] <br />" ); ); ); );
34
35 printprintprintprint( ( ( ( "<br /><strong>Creating the third array"<br /><strong>Creating the third array"<br /><strong>Creating the third array"<br /><strong>Creating the third array
38 // assign val// assign val// assign val// assign values to nonues to nonues to nonues to non----numerical indices numerical indices numerical indices numerical indices
43 // iterate through the array elements and print each // iterate through the array elements and print each // iterate through the array elements and print each // iterate through the array elements and print each
44 // element’s n // element’s n // element’s n // element’s name and valueame and valueame and valueame and value
45 for for for for ( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );
52 // call function array to create array fourth using // call function array to create array fourth using // call function array to create array fourth using // call function array to create array fourth using
53 // string indices // string indices // string indices // string indices
63 // print each element’s name and value // print each element’s name and value // print each element’s name and value // print each element’s name and value
64 foreach foreach foreach foreach ( $fourth as $el( $fourth as $el( $fourth as $el( $fourth as $element => $value )ement => $value )ement => $value )ement => $value )
65 printprintprintprint( ( ( ( "$element is the $value month <br />""$element is the $value month <br />""$element is the $value month <br />""$element is the $value month <br />" ); ); ); );
66 ?>?>?>?>
67 </body> </body> </body> </body>
68 </html></html></html></html>
arrays.php
(3 of 3)
Operator => is used in function array to assign each
element a string index. The value to the left of the
operator is the array index, and the value to the right is
the element’s value.
2003 Prentice Hall, Inc. All rights reserved.
24
26.2 PHPFig. 26.6 Array manipulation.
2003 Prentice Hall, Inc. All rights reserved.
25
26.3 String Processing and Regular
Expressions
• String processing– Equality and comparison two important operations
– strcmp function
• Returns –1 if string 1 < string 2
• Returns 0 if string 1 = string 2
• Returns 1 if string 1 > string 2
– Relational operators
2003 Prentice Hall, Inc.
All rights reserved.
Outline261 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
18 // iterate through each array element// iterate through each array element// iterate through each array element// iterate through each array element
21 // call function strcmp to compare the array element // call function strcmp to compare the array element // call function strcmp to compare the array element // call function strcmp to compare the array element
22 // to string "banana" // to string "banana" // to string "banana" // to string "banana"
24 printprintprintprint( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ]." is less than banana "" is less than banana "" is less than banana "" is less than banana " ); ); ); );
compare.php
(1 of 2)
Use a for loop to iterate through each array element.
Function strcmp compares two strings. If the first string
alphabetically precedes the second, then –1 is returned. If
the strings are equal, 0 is returned. If the first string
alphabetically follows the second, then 1 is returned.
27 " is greater than banana "" is greater than banana "" is greater than banana "" is greater than banana " ); ); ); );
28 elseelseelseelse
29 printprintprintprint( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ]." is equal to banana "" is equal to banana "" is equal to banana "" is equal to banana " ); ); ); );
30
31 // use relational operators to compare each element // use relational operators to compare each element // use relational operators to compare each element // use relational operators to compare each element
32 // to string "apple" // to string "apple" // to string "apple" // to string "apple"
34 print print print print( ( ( ( "and less than apple! <br />""and less than apple! <br />""and less than apple! <br />""and less than apple! <br />" ); ); ); );
38 print print print print( ( ( ( "and equal to apple! <br />""and equal to apple! <br />""and equal to apple! <br />""and equal to apple! <br />" ); ); ); );
39
40 }}}}
41 ?>?>?>?>
42 </body> </body> </body> </body>
43 </html></html></html></html>
compare.php
(2 of 2)
Use relational operators to compare each array element to string “apple”.
2003 Prentice Hall, Inc. All rights reserved.
28
26.3 String Processing and Regular
ExpressionsFig. 26.7 Using the string comparison operators.
2003 Prentice Hall, Inc. All rights reserved.
29
26.3 String Processing and Regular
Expressions
• Regular expressions– Pattern matching templates
– ereg function
• POSIX
– preg_match function
• Perl
– ereg_replace function
• Building regular expressions– Metacharacters
• $, ., ^
– Brackets [ ]
2003 Prentice Hall, Inc.
All rights reserved.
Outline301 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
14 $search = $search = $search = $search = "Now is the time""Now is the time""Now is the time""Now is the time";;;;
15 print print print print( ( ( ( "Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />" ) ) ) );;;;
16
17 // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now'
18 // in variable search // in variable search // in variable search // in variable search
19 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "Now""Now""Now""Now", $search ), $search ), $search ), $search ) ) ) ) )
20 print print print print( ( ( ( "String 'Now' was found.<br />""String 'Now' was found.<br />""String 'Now' was found.<br />""String 'Now' was found.<br />" ); ); ); );
21
expression.php
(1 of 3)
Function ereg searches for the literal
characters Now inside variable $search.
2003 Prentice Hall, Inc.
All rights reserved.
Outline31
22 // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of
23 // the string // the string // the string // the string
24 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "^Now""^Now""^Now""^Now", $search ), $search ), $search ), $search ) ) ) ) )
25 print print print print( ( ( ( "String 'Now' found at beginning"String 'Now' found at beginning"String 'Now' found at beginning"String 'Now' found at beginning
26 of the line.<br />"of the line.<br />"of the line.<br />"of the line.<br />" ); ); ); );
27
28 // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string
29 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "Now$""Now$""Now$""Now$", $search ), $search ), $search ), $search ) ) ) ) )
30 print print print print( ( ( ( "String 'Now' was found at the end "String 'Now' was found at the end "String 'Now' was found at the end "String 'Now' was found at the end
31 of the line.<br />"of the line.<br />"of the line.<br />"of the line.<br />" ); ); ); );
32
33 // search for any word ending in 'ow'// search for any word ending in 'ow'// search for any word ending in 'ow'// search for any word ending in 'ow'
36 printprintprintprint( ( ( ( "Word found ending in 'ow': ""Word found ending in 'ow': ""Word found ending in 'ow': ""Word found ending in 'ow': " . . . .
39 // search for any words beginning with 't' // search for any words beginning with 't' // search for any words beginning with 't' // search for any words beginning with 't'
40 print print print print( ( ( ( "Words beginning with 't' found: ""Words beginning with 't' found: ""Words beginning with 't' found: ""Words beginning with 't' found: "););););
The dollar sign special character ($) search for the
pattern Now at the end of the string.
The expression inside the parentheses, [a-zA-Z]*ow,
matches any word ending in ow. The quantifier *
matches the preceding pattern 0 or more times.
The special bracket expressions [[:<:]] and
[[:>:]] match the beginning and end of a
word, respectively.
Placing a pattern in parentheses stores the matched
string in the array that is specified in the third argument
to function ereg.
The while loop is used to find each occurrence of a
word in the string beginning with t.
The pattern used in this example,
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any
word beginning with the character t followed by one or
more characters. Character class [[:alpha:]]
recognizes any alphabetic character.
Function eregi is used to specify case insensitive
pattern matches.
The caret special character (^) matches the
beginning of a string. Function ereg searches the
beginning of the string for pattern Now .
2003 Prentice Hall, Inc.
All rights reserved.
Outline32
expression.php
(3 of 3)
46 // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning
47 // with 't' to find other instances in the string // with 't' to find other instances in the string // with 't' to find other instances in the string // with 't' to find other instances in the string
After printing a match of a word beginning with t, function
ereg_replace is called to remove the word from the string.
This is necessary be because to find multiple instances of a
given pattern, the first matched instance must first be removed.
Function ereg_replace takes three arguments: the pattern to
match, a string to replace the matched string and the string to
search.
2003 Prentice Hall, Inc. All rights reserved.
33
26.3 String Processing and Regular
ExpressionsFig. 26.8 Regular expressions in PHP.
2003 Prentice Hall, Inc. All rights reserved.
34
26.3 String Processing and Regular
Expressions
Quantifier Matches {n} Exactly n times. {m,n} Between m and n times inclusive. {n,} n or more times. + One or more times (same as {1,}). * Zero or more times (same as {0,}). ? Zero or one time (same as {0,1}).
Fig. 26.9 Some PHP quantifiers.
2003 Prentice Hall, Inc. All rights reserved.
35
26.3 String Processing and Regular
Expressions
Character class Description alnum Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]). alpha Word characters (i.e., letters [a-zA-Z]). digit Digits. space Whitespace. lower Lowercase letters. upper Uppercase letters.
Fig. 26.10 Some PHP character classes.
2003 Prentice Hall, Inc. All rights reserved.
36
26.4 Viewing Client/Server Environment
Variables
• Environment variables– Provide information about execution environment
• Type of Web browser
• Type of server
• Details of HTTP connection
– Stored as array in PHP
• $_ENV
2003 Prentice Hall, Inc. All rights reserved.
37
26.4 Viewing Client/Server Environment
Variables
Variable name Description $_SERVER Data about the currently running server.
$_ENV Data about the client’s environment. $_GET Data posted to the server by the get method. $_POST Data posted to the server by the post method. $_COOKIE Data contained in cookies on the client’s computer. $GLOBALS Array containing all global variables.
Fig. 26.11 Some useful global arrays.
2003 Prentice Hall, Inc.
All rights reserved.
Outline381 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Program to display environment variables Program to display environment variables Program to display environment variables Program to display environment variables -------->>>>
17 // print the key and value for each element // print the key and value for each element // print the key and value for each element // print the key and value for each element
18 // in the $_ENV array // in the $_ENV array // in the $_ENV array // in the $_ENV array
Outline411 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program -------->>>>
9 <title> <title> <title> <title>Sample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTML</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13
14 <h1> <h1> <h1> <h1>This is a sample registration form.This is a sample registration form.This is a sample registration form.This is a sample registration form.</h1></h1></h1></h1>
15 Please fill in all fields and click Register.Please fill in all fields and click Register.Please fill in all fields and click Register.Please fill in all fields and click Register.
16
17 <!<!<!<!-------- post form data to form.php post form data to form.php post form data to form.php post form data to form.php -------->>>>
21 Please fill out the fields below. Please fill out the fields below. Please fill out the fields below. Please fill out the fields below.<br /><br /><br /><br />
22 </span> </span> </span> </span>
23
form.html
(1 of 4)
The action attribute of the form element
indicates that when the user clicks Register, the
form data will be posted to form.php.
2003 Prentice Hall, Inc.
All rights reserved.
Outline42
24 <! <! <! <!-------- create four text boxes for user input create four text boxes for user input create four text boxes for user input create four text boxes for user input -------->>>>
25 <img src = <img src = <img src = <img src = "images/fname.gif""images/fname.gif""images/fname.gif""images/fname.gif" alt = alt = alt = alt = "First Name""First Name""First Name""First Name" /> /> /> />
26 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "fname""fname""fname""fname" /><br /> /><br /> /><br /> /><br />
27
28 <img src = <img src = <img src = <img src = "images/lname.gif""images/lname.gif""images/lname.gif""images/lname.gif" alt = alt = alt = alt = "La"La"La"Last Name" st Name" st Name" st Name" />/>/>/>
29 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "lname""lname""lname""lname" /><br /> /><br /> /><br /> /><br />
30
31 <img src = <img src = <img src = <img src = "images/email.gif""images/email.gif""images/email.gif""images/email.gif" alt = alt = alt = alt = "Email" "Email" "Email" "Email" /> /> /> />
32 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "email""email""email""email" /><br /> /><br /> /><br /> /><br />
33
34 <img src = <img src = <img src = <img src = "images/p"images/p"images/p"images/phone.gif"hone.gif"hone.gif"hone.gif" alt = alt = alt = alt = "Phone" "Phone" "Phone" "Phone" /> /> /> />
35 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "phone""phone""phone""phone" /><br /> /><br /> /><br /> /><br />
38 Must be in the form (555)555 Must be in the form (555)555 Must be in the form (555)555 Must be in the form (555)555----5555555555555555</span></span></span></span>
45 Which book would you like information about? Which book would you like information about? Which book would you like information about? Which book would you like information about?
48 <! <! <! <!-------- create drop create drop create drop create drop----down list containing book names down list containing book names down list containing book names down list containing book names -------->>>>
49 <select name = <select name = <select name = <select name = "book""book""book""book">>>>
50 <option><option><option><option>Internet and WWW How to Program 3eInternet and WWW How to Program 3eInternet and WWW How to Program 3eInternet and WWW How to Program 3e</option></option></option></option>
51 <option><option><option><option>C++ How to Program 4eC++ How to Program 4eC++ How to Program 4eC++ How to Program 4e</option></option></option></option>
52 <optio <optio <optio <option>n>n>n>Java How to Program 5eJava How to Program 5eJava How to Program 5eJava How to Program 5e</option></option></option></option>
53 <option> <option> <option> <option>XML How to Program 1eXML How to Program 1eXML How to Program 1eXML How to Program 1e</option></option></option></option>
59 Which operating system are you currently using? Which operating system are you currently using? Which operating system are you currently using? Which operating system are you currently using?
62 <! <! <! <!-------- create five radio buttons create five radio buttons create five radio buttons create five radio buttons -------->>>>
63 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Windows XP""Windows XP""Windows XP""Windows XP"
67 <input type = <input type = <input type = <input type = "radio" "radio" "radio" "radio" name = name = name = name = "os""os""os""os" value = value = value = value =
69 Windows 2000Windows 2000Windows 2000Windows 2000
70
71 <input ty <input ty <input ty <input type = pe = pe = pe = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value =
73 Windows 98Windows 98Windows 98Windows 98<br /><br /><br /><br />
form.html
(3 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline44
form.html
(4 of 4)
74
75 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Linux""Linux""Linux""Linux" /> /> /> />
76 LinuxLinuxLinuxLinux
77
78 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Other""Other""Other""Other" /> /> /> />
79 Other Other Other Other<br /><br /><br /><br />
80
81 <! <! <! <!-------- create a su create a su create a su create a submit button bmit button bmit button bmit button -------->>>>
82 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Register""Register""Register""Register" /> /> /> />
83 </form> </form> </form> </form>
84
85 </body> </body> </body> </body>
86 </html></html></html></html>
2003 Prentice Hall, Inc. All rights reserved.
45
26.5 Form Processing and Business Logic
Fig. 26.13 XHTML form for gathering user input.
2003 Prentice Hall, Inc. All rights reserved.
46
26.5 Form Processing and Business Logic
• Business logic– Confirm that valid information was entered
– extract function
• Creates variables corresponding to each key-value pair in array
• Easily retrieve all values sent to PHP page
– Regular expressions very helpful
– Do checks on client side where possible
• JavaScript
• Conserves server resources
• Ending a script– die function
• Remember to close all HTML tags
2003 Prentice Hall, Inc.
All rights reserved.
Outline471 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Read information sent from form.html Read information sent from form.html Read information sent from form.html Read information sent from form.html -------->>>>
17 // determine whether phone number is valid and print // determine whether phone number is valid and print // determine whether phone number is valid and print // determine whether phone number is valid and print
18 // an error message if not // an error message if not // an error message if not // an error message if not
25 A valid phone number must be in the form A valid phone number must be in the form A valid phone number must be in the form A valid phone number must be in the form
28 Click the Back button, enter a valid phone Click the Back button, enter a valid phone Click the Back button, enter a valid phone Click the Back button, enter a valid phone
29 number and resubmit.<br /><br /> number and resubmit.<br /><br /> number and resubmit.<br /><br /> number and resubmit.<br /><br />
42 Thank you for completing the survey.Thank you for completing the survey.Thank you for completing the survey.Thank you for completing the survey.<br /><br /><br /><br />
43
form.php
(2 of 4)
Function die terminates script execution
2003 Prentice Hall, Inc.
All rights reserved.
Outline49
44 You have been added to the You have been added to the You have been added to the You have been added to the
52 <strong> <strong> <strong> <strong>The following information has been saved The following information has been saved The following information has been saved The following information has been saved
77 This is only a sample form. This is only a sample form. This is only a sample form. This is only a sample form.
78 You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.
79 </di </di </di </div>v>v>v>
80 </body> </body> </body> </body>
81 </html></html></html></html>
2003 Prentice Hall, Inc. All rights reserved.
51
26.5 Form Processing and Business Logic
Fig. 26.14 Obtaining user input through forms.
2003 Prentice Hall, Inc. All rights reserved.
52
26.6 Verifying a Username and Password
• Private website– Only accessible to certain individuals
– Encrypt username and password data when sending, storing
and retrieving for increased security
• Implementing password checking– Login information stored in file
• fopen function
• Read, write, append modes
– Store data using fputs
• \n newline character
– Close files when done
• fclose function
2003 Prentice Hall, Inc. All rights reserved.
53
26.6 Verifying a Username and Password
• Implementing password checking, cont.– Trim newline character
• chop function
– Split string into substrings given a certain delimiter
• split function
– If username/password match list, allow access
2003 Prentice Hall, Inc.
All rights reserved.
Outline541 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- XHTML form sent to password.php for ve XHTML form sent to password.php for ve XHTML form sent to password.php for ve XHTML form sent to password.php for verification rification rification rification -------->>>>
9 <title> <title> <title> <title>Verifying a username and a password.Verifying a username and a password.Verifying a username and a password.Verifying a username and a password.</title></title></title></title>
18 Type in your username and password below. Type in your username and password below. Type in your username and password below. Type in your username and password below.
21 font font font font----weight: bold"weight: bold"weight: bold"weight: bold">>>>
22 Note that password will be sent as plain textNote that password will be sent as plain textNote that password will be sent as plain textNote that password will be sent as plain text
23 </span> </span> </span> </span>
24 </p> </p> </p> </p>
25
password.html
(1 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline55
26 <!<!<!<!-------- post form data to password.php post form data to password.php post form data to password.php post form data to password.php -------->>>>
Fig. 26.15 XHTML form for obtaining a username and password.
2003 Prentice Hall, Inc.
All rights reserved.
Outline591 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Searching a database for usernames an Searching a database for usernames an Searching a database for usernames an Searching a database for usernames and passwords. d passwords. d passwords. d passwords. -------->>>>
12 // check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank
18 // check if the New User button was clicked // check if the New User button was clicked // check if the New User button was clicked // check if the New User button was clicked
19 if if if if ( ( ( ( isset( $NewUser )isset( $NewUser )isset( $NewUser )isset( $NewUser ) ) { ) { ) { ) {
20
21 // open password.txt for writi// open password.txt for writi// open password.txt for writi// open password.txt for writing using append modeng using append modeng using append modeng using append mode
negation operator (!), return true if they are empty
or set to 0. This checks if a user has submitted a form
without specifying a username or password.
Function fieldsBlank is called if the user has
submitted an incomplete form to notify the user
that all form fields must be completed.Function isset tests whether the user has
pressed the New User button, indicating that a
new user must be added.
To add a new user, we open the file
password.txt in append mode and assign the
file handle that is returned to variable $file.
2003 Prentice Hall, Inc.
All rights reserved.
Outline60
25 // print error message and terminate script // print error message and terminate script // print error message and terminate script // print error message and terminate script
26 // execution if file cannot be opened // execution if file cannot be opened // execution if file cannot be opened // execution if file cannot be opened
33 // write username and password to file and // write username and password to file and // write username and password to file and // write username and password to file and
34 // call function userAdded // call function userAdded // call function userAdded // call function userAdded
40 // if a new user is not being added, open file // if a new user is not being added, open file // if a new user is not being added, open file // if a new user is not being added, open file
41 // for reading // for reading // for reading // for reading
52 // read each line in file and check username // read each line in file and check username // read each line in file and check username // read each line in file and check username
53 // and password // and password // and password // and password
54 while while while while ( ( ( ( !feof( $file )!feof( $file )!feof( $file )!feof( $file ) && !$userVerified ) { && !$userVerified ) { && !$userVerified ) { && !$userVerified ) {
55
56 // read line from file// read line from file// read line from file// read line from file
59 // remove newline character from end of line // remove newline character from end of line // remove newline character from end of line // remove newline character from end of line
69 // call function checkPassword to verify // call function checkPassword to verify // call function checkPassword to verify // call function checkPassword to verify
82 // call function accessDenied if username has // call function accessDenied if username has // call function accessDenied if username has // call function accessDenied if username has
83 // not been verified // not been verified // not been verified // not been verified
88 // // // // verify user password and return a booleanverify user password and return a booleanverify user password and return a booleanverify user password and return a boolean
password to the password in the file. If they match,
true is returned, whereas false is returned if they
do not.
2003 Prentice Hall, Inc.
All rights reserved.
Outline63
97 // print a message indicating the user has been added // print a message indicating the user has been added // print a message indicating the user has been added // print a message indicating the user has been added
98 function function function function userAdded( $name ) userAdded( $name ) userAdded( $name ) userAdded( $name )
102 font font font font----size: 1em; color: bluesize: 1em; color: bluesize: 1em; color: bluesize: 1em; color: blue\\\\"> "> "> ">
103 <strong>You have been added <strong>You have been added <strong>You have been added <strong>You have been added
104 to the user list, $name. to the user list, $name. to the user list, $name. to the user list, $name.
105 <br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>" ); ); ); );
106 }}}}
107
108 // print a message in // print a message in // print a message in // print a message indicating permission dicating permission dicating permission dicating permission
109 // has been granted // has been granted // has been granted // has been granted
110 function function function function accessGranted( $name ) accessGranted( $name ) accessGranted( $name ) accessGranted( $name )
117 Enjoy the site.</strong>"Enjoy the site.</strong>"Enjoy the site.</strong>"Enjoy the site.</strong>" ); ); ); );
118 } } } }
119
password.php
(5 of 7)Function userAdded prints a message to the
client indicating that the user has been added.
Function accessGranted prints a
message to the client indicating that
permission has been granted.
2003 Prentice Hall, Inc.
All rights reserved.
Outline64
120 // print a message indicating password is invalid // print a message indicating password is invalid // print a message indicating password is invalid // print a message indicating password is invalid
121 function function function function wrongPassword() wrongPassword() wrongPassword() wrongPassword()
125 font font font font----size: 1em; color: redsize: 1em; color: redsize: 1em; color: redsize: 1em; color: red\\\\">">">">
126 <strong>You entered an invalid <strong>You entered an invalid <strong>You entered an invalid <strong>You entered an invalid
127 password.<br />Access has password.<br />Access has password.<br />Access has password.<br />Access has
128 been denied.</strong>"been denied.</strong>"been denied.</strong>"been denied.</strong>" ); ); ); );
129 }}}}
130
131 // print a message indicating a // print a message indicating a // print a message indicating a // print a message indicating access has been deniedccess has been deniedccess has been deniedccess has been denied
132 function function function function accessDenied() accessDenied() accessDenied() accessDenied()
136 font font font font----size: 1em; color: redsize: 1em; color: redsize: 1em; color: redsize: 1em; color: red\\\\">">">">
137 <strong> <strong> <strong> <strong>
138 You were denied access to this server. You were denied access to this server. You were denied access to this server. You were denied access to this server.
142 // print a message indicating that fields // print a message indicating that fields // print a message indicating that fields // print a message indicating that fields
143 // have been left blank // have been left blank // have been left blank // have been left blank
144 function function function function fieldsBlank() fieldsBlank() fieldsBlank() fieldsBlank()
Outline691 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
31 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Send "Send "Send "Send Query"Query"Query"Query"
Outline731 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Program to query a database and Program to query a database and Program to query a database and Program to query a database and -------->>>>
6 <!<!<!<!-------- send res send res send res send results to the client. ults to the client. ults to the client. ults to the client. -------->>>>
25 diediediedie( ( ( ( "Could not connect to database""Could not connect to database""Could not connect to database""Could not connect to database" ); ); ); );
database.php
(1 of 3)
Build the select query and assign the
string to variable $query.
Function mysql_connect returns a database
handle which represents PHP’s connection to a
database. If this connection is not made, function
die is called to terminate script execution.
2003 Prentice Hall, Inc.
All rights reserved.
Outline74
26
27 // open Products database // open Products database // open Products database // open Products database
28 if if if if ( ( ( ( !!!!mysql_select_dbmysql_select_dbmysql_select_dbmysql_select_db( ( ( ( "Products""Products""Products""Products", $database ), $database ), $database ), $database ) ) ) ) )
29 diediediedie( ( ( ( "Could not open Products database""Could not open Products database""Could not open Products database""Could not open Products database" ); ); ); );
70 Deitel and Associates, Inc.Deitel and Associates, Inc.Deitel and Associates, Inc.Deitel and Associates, Inc.
71 </a> </a> </a> </a>
72 </h5> </h5> </h5> </h5>
73
74 </body> </body> </body> </body>
75 </html></html></html></html>
database.php
(3 of 3)
The foreach loop iterates through the
array containing the elements of each row
and prints out each element in an
individual table cell.The total number of results are printed to the
client.
2003 Prentice Hall, Inc. All rights reserved.
76
26.7 Connecting to a Database
Fig. 26.19 Querying a database and displaying the results.
2003 Prentice Hall, Inc. All rights reserved.
77
26.8 Cookies
• Cookies– Store information on client computer
– Track preferences and other information
– Stored as text files on hard drive
– Never store sensitive information, such as credit card
numbers, in a cookie
• Security risk
• Cookies and PHP– setcookie function
• Name
• Value
• Expiration date
2003 Prentice Hall, Inc.
All rights reserved.
Outline781 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
9 <title><title><title><title>Writing a cookie to the client computerWriting a cookie to the client computerWriting a cookie to the client computerWriting a cookie to the client computer</title></title></title></title>
15 <h2> <h2> <h2> <h2>Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.</h2></h2></h2></h2>
20 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "NAME""NAME""NAME""NAME" /> /> /> /><br /><br /><br /><br />
23 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "HEIGHT""HEIGHT""HEIGHT""HEIGHT" /> /> /> /><br /><br /><br /><br />
26 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "COLOR""COLOR""COLOR""COLOR" /> /> /> /><br /><br /><br /><br />
27
28 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Write C"Write C"Write C"Write Cookie" ookie" ookie" ookie"
3 // Program to write a cookie to a client's machine// Program to write a cookie to a client's machine// Program to write a cookie to a client's machine// Program to write a cookie to a client's machine
6 // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the
7 // cookie’s expiration date // cookie’s expiration date // cookie’s expiration date // cookie’s expiration date
13 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1//W3C//DTD XHTML 1//W3C//DTD XHTML 1//W3C//DTD XHTML 1.0 Transitional//EN".0 Transitional//EN".0 Transitional//EN".0 Transitional//EN"
22 <p> <p> <p> <p>The cookie has been set with the following data:The cookie has been set with the following data:The cookie has been set with the following data:The cookie has been set with the following data:</p></p></p></p>
23
cookies.php
(1 of 2)
Function setcookie takes the name of the
cookie to be set as the first argument,
followed by the value to be stored in the
cookie. The optional third argument specifies
the expiration date of the cookie.
2003 Prentice Hall, Inc.
All rights reserved.
Outline82
24 <!<!<!<!-------- print each form field’s value print each form field’s value print each form field’s value print each form field’s value -------->>>>
36 to read the saved cookie. to read the saved cookie. to read the saved cookie. to read the saved cookie.</p></p></p></p>
37 </body> </body> </body> </body>
38 </html></html></html></html>
cookies.php
(2 of 2)
Each form field’s value is printed to
confirm the data that has been set as a
cookie with the user.
Hyperlink to readCookies.php.
2003 Prentice Hall, Inc. All rights reserved.
83
26.8 Cookies
Fig. 26.21 Writing a cookie to the client.
2003 Prentice Hall, Inc. All rights reserved.
84
26.8 Cookies
• Reading cookies– $_COOKIE environment variable
• Array
– foreach loop to access each element
• Split into key and value
2003 Prentice Hall, Inc. All rights reserved.
85
26.8 Cookies
• Cookie storage– Internet Explorer
• Stores cookies in Cookies directory
• Text file
2003 Prentice Hall, Inc. All rights reserved.
86
26.8 Cookies
Fig. 26.22 Cookies directory before a cookie is written.
Fig. 26.23 Cookies directory after a cookie is written.
2003 Prentice Hall, Inc.
All rights reserved.
Outline871 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Program to read cookies from the cli Program to read cookies from the cli Program to read cookies from the cli Program to read cookies from the client's computer ent's computer ent's computer ent's computer -------->>>>
14 The following data is saved in a cookie on your The following data is saved in a cookie on your The following data is saved in a cookie on your The following data is saved in a cookie on your
22 // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print
23 // name and value of each cookie // name and value of each cookie // name and value of each cookie // name and value of each cookie
array and prints the name and value of each cookie
in an XHTML table.
2003 Prentice Hall, Inc. All rights reserved.
89
26.8 Cookies
Fig. 26.24 Displaying the cookie’s content.
2003 Prentice Hall, Inc. All rights reserved.
90
26.9 Dynamic Content in PHP
• Dynamically alter XHTML content– Form’s action property set to same page that contains it
– Perform different actions when page is loaded and form is
submitted
• isset variable
– Check for errors
• Write different XHTML when errors encountered
– $$variable syntax
• References variable whose name equals the value of $variable
– If input is valid, make MySQL database calls
2003 Prentice Hall, Inc.
All rights reserved.
Outline911 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program -------->>>>
9 <title><title><title><title>Sample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTML</title></title></title></title>
17 // array of book titles// array of book titles// array of book titles// array of book titles
18 $booklist = $booklist = $booklist = $booklist = arrayarrayarrayarray( ( ( ( "Internet and WWW How to Program 3e""Internet and WWW How to Program 3e""Internet and WWW How to Program 3e""Internet and WWW How to Program 3e",,,,
19 "C++ How to Program 4e""C++ How to Program 4e""C++ How to Program 4e""C++ How to Program 4e",,,,
20 "Java How to Program 5e""Java How to Program 5e""Java How to Program 5e""Java How to Program 5e",,,,
21 "XML How to Program 1e""XML How to Program 1e""XML How to Program 1e""XML How to Program 1e" ); ); ); );
22
dynamicForm.php
(1 of 9)
Build array of options for the form.
2003 Prentice Hall, Inc.
All rights reserved.
Outline92
23 // array of possible operating systems// array of possible operating systems// array of possible operating systems// array of possible operating systems
30 // array of name and alt values// array of name and alt values// array of name and alt values// array of name and alt values for the text input fields for the text input fields for the text input fields for the text input fields
68 die( "Could not connect to database" ); die( "Could not connect to database" ); die( "Could not connect to database" ); die( "Could not connect to database" );
69
70 // open MailingList database// open MailingList database// open MailingList database// open MailingList database
72 die( die( die( die( "Could not open MailingList database""Could not open MailingList database""Could not open MailingList database""Could not open MailingList database" ); ); ); );
dynamicForm.php
(3 of 9)
If there were no errors, query the MySQL
database.
2003 Prentice Hall, Inc.
All rights reserved.
Outline94
73
74 // execute query in MailingList database// execute query in MailingList database// execute query in MailingList database// execute query in MailingList database
83 Thank you for completing the survey.<br />Thank you for completing the survey.<br />Thank you for completing the survey.<br />Thank you for completing the survey.<br />
84
85 You have You have You have You have been added to thebeen added to thebeen added to thebeen added to the
90 <strong>The following information has been saved<strong>The following information has been saved<strong>The following information has been saved<strong>The following information has been saved
102 <!<!<!<!-------- print each form field’s value print each form field’s value print each form field’s value print each form field’s value -------->>>>
113 Click here to view entire database.</a></div>Click here to view entire database.</a></div>Click here to view entire database.</a></div>Click here to view entire database.</a></div>
114 This is only a sample form. This is only a sample form. This is only a sample form. This is only a sample form.
115 You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.
121 printprintprintprint( ( ( ( "<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>
122 Please fill in all fields and click Register."Please fill in all fields and click Register."Please fill in all fields and click Register."Please fill in all fields and click Register." ); ); ); );
126 Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>" ); ); ); );
127 } } } }
128
129 printprintprintprint( ( ( ( "<!"<!"<!"<!-------- post form data to form.php post form data to form.php post form data to form.php post form data to form.php -------->>>>
133 Please fill outPlease fill outPlease fill outPlease fill out the fields below.<br /> the fields below.<br /> the fields below.<br /> the fields below.<br />
134 </span></span></span></span>
135
136 <!<!<!<!-------- create four text boxes for user input create four text boxes for user input create four text boxes for user input create four text boxes for user input -------->">">">" ); ); ); );
153 printprintprintprint( ( ( ( "; color : red""; color : red""; color : red""; color : red" ); ); ); );
154
155 printprintprintprint( ( ( ( "'>Must be in the form (555)555"'>Must be in the form (555)555"'>Must be in the form (555)555"'>Must be in the form (555)555----5555555555555555
162 Which book would you like information about?Which book would you like information about?Which book would you like information about?Which book would you like information about?
165 <!<!<!<!-------- create drop create drop create drop create drop----down list containing book names down list containing book names down list containing book names down list containing book names -------->>>>
166 <select name = 'book'>"<select name = 'book'>"<select name = 'book'>"<select name = 'book'>" ); ); ); );
180 Which operating system are you currently using?Which operating system are you currently using?Which operating system are you currently using?Which operating system are you currently using?
183 <!<!<!<!-------- create five radio buttons create five radio buttons create five radio buttons create five radio buttons -------->">">">" ); ); ); );
188 prinprinprinprintttt( ( ( ( "<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'
200 printprintprintprint( ( ( ( "<!"<!"<!"<!-------- create a submit button create a submit button create a submit button create a submit button -------->>>>
201 <br /> <br /> <br /> <br />
202 <input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' />
Outline1021 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
5 <!<!<!<!-------- Program to query a database and Program to query a database and Program to query a database and Program to query a database and -------->>>>
6 <!<!<!<!-------- send send send send results to the client. results to the client. results to the client. results to the client. -------->>>>
25 die( die( die( die( "Could not connect to database""Could not connect to database""Could not connect to database""Could not connect to database" ); ); ); );
formDatabase.php
(1 of 3)
Build the query string.
2003 Prentice Hall, Inc.
All rights reserved.
Outline103
26
27 // open MailingList database// open MailingList database// open MailingList database// open MailingList database
29 die( die( die( die( "Could not open MailingList database""Could not open MailingList database""Could not open MailingList database""Could not open MailingList database" ); ); ); );