8/10/2019 Synapseindia Php Development Chaptr-2
1/107
1
Chapter 26 - PHP
Outline26.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 Password26.7 Connecting to a Database
26.8 Cookies
26.9 Dynamic Content in PHP
26.10 Operator Precedence
26.11 Web Resources
8/10/2019 Synapseindia Php Development Chaptr-2
2/107
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.
8/10/2019 Synapseindia Php Development Chaptr-2
3/107
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
8/10/2019 Synapseindia Php Development Chaptr-2
4/107
4
26.2 PHP
Basic application Scripting delimiters
Must enclose all script code
Variables preceded by $symbol Case-sensitive
End statements with semicolon
Comments
//for single line
/* */for multiline
Filenames end with .phpby convention
8/10/2019 Synapseindia Php Development Chaptr-2
5/107
5
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4 < -- Fig. 26.1: first.php -->
5 < -- Our first PHP script -->
6
7
10
11
12
13 A simple PHP document
14
15
16
17
18
19
20 < --print variable names value -->
21Welcome to PHP,
22
23
24
25
first.php
(1 of 1)
Declare variable $name
Scripting delimiters
Single-line comment
Function printoutputs the value of variable$name
8/10/2019 Synapseindia Php Development Chaptr-2
6/107
8/10/2019 Synapseindia Php Development Chaptr-2
7/107
7
26.2 PHP
Variables Can have different types at different times
Variable names inside strings replaced by their
value
Type conversionssettypefunction
Type casting
Concatenation operator
.(period)
Combine strings
8/10/2019 Synapseindia Php Development Chaptr-2
8/107
8
26.2 PHP
Datatype Descriptionint, integer Wholenumbers (i.e., numbers without adecimal point).float, doubl Real numbers (i.e., numbers containingadecimal point).string Text enclosedineither single('') or double("") quotes.bool, Boolea Trueor false.array Groupof elements of thesametype.object
Groupof associateddataandmethods.Resource Anexternal datasource.NULL Novalue.
Fig. 26.2PHPdatatypes.
1
8/10/2019 Synapseindia Php Development Chaptr-2
9/107
9
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.3: data.php -->
5< -- Demonstration of PHP data types -->
6
7
8
9PHP data types
10
11
12
13
14
21
data.php
(1 of 3)
Assign a string to variable$testString
Assign a double to variable$testDoubleAssign an integer to variable$testInteger
22
8/10/2019 Synapseindia Php Development Chaptr-2
10/107
10
22 < --print each variables value -->
23 is a string.
24 is a double.
25 is an integer.
26
27
28 Now, converting to other types:
29
8/10/2019 Synapseindia Php Development Chaptr-2
11/107
11
44
45 // use type casting to cast variables to a
46 // different type
47 print(Now using type casting instead:
48 As a string - . (string) $data .
49
As a double - . (double) $data .
50
As an integer - . (integer) $data );
51 ?>
52
53
data.php
(3 of 3)
Use type casting to cast variable
$datato different types
8/10/2019 Synapseindia Php Development Chaptr-2
12/107
12
26.2 PHPFig. 26.3 Type conversion.
8/10/2019 Synapseindia Php Development Chaptr-2
13/107
13
26.2 PHP
Arithmetic operators Assignment operators
Syntactical shortcuts
Before being assigned values, variables have valueundef
Constants
Named values
definefunction
1
8/10/2019 Synapseindia Php Development Chaptr-2
14/107
14
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.4: operators.php -->
5 < -- Demonstration of operators -->
6
7
8
9 Using arithmetic operators
10
11
12
13
8/10/2019 Synapseindia Php Development Chaptr-2
15/107
15
25 // multiply variable $a by 2
26 $a *= 2;
27 print( "Multiplying variable a by 2 yields $a
");
28
29 // test if variable $a is less than 50
30 if( $a < 50)
31 print( "Variable a is less than 50
");
32
33 // add 40 to variable $a
34 $a += 40;
35 print( "Variable a after adding 40 is $a
");
36
37 // test if variable $a is 50 or less
38 if( $a < 51)
39 print( "Variable a is still 50 or less
");
40
41 // test if variable $a is between 50 and 100, inclusive
42 elseif( $a < 101)
43 print( "Variable a is now between 50 and 100,
44 inclusive
");
45 else
46 print( "Variable a is now greater than 100
47
");
48
operators.php
(2 of 3)
Multiply variable $aby two using the
multiplication assignment operator *=.
Test whether variable $ais less than 50
Add 40to variable $ausing the addition assignmentoperator +=.
Print if variable $ais less than 50.
49
8/10/2019 Synapseindia Php Development Chaptr-2
16/107
16
49// print an uninitialized variable
50 print( "Using a variable before initializing:
51 $nothing
");
52
53 // add constant VALUE to an uninitialized variable
54 $test = $num + VALUE;
55 print( "An uninitialized variable plus constant
56 VALUE yields $test
");
57
58 // add a string to an integer
59 $str = "3 dollars";
60 $a += $str;
61 print( "Adding a string to variable a yields $a
62
");
63 ?>
64
65
operators.php
(3 of 3)
Add constant VALUEto an uninitialized
variable.
Add a string to an integer.
Print an uninitialized variable ($nothing).
8/10/2019 Synapseindia Php Development Chaptr-2
17/107
17
26.2 PHPFig. 26.4 Using PHPs arithmetic operators.
8/10/2019 Synapseindia Php Development Chaptr-2
18/107
18
26.2 PHP
Keywords Reserved for language features
ifelseifelse
Arrays
Group of related data
Elements
Name plus braces and index
Indices start at zero
countfunction
arrayfunction
8/10/2019 Synapseindia Php Development Chaptr-2
19/107
19
26.2 PHP
Arrays, cont. Built-in iterators
Maintain pointer to element currently referenced
reset
key
next
foreachloops
8/10/2019 Synapseindia Php Development Chaptr-2
20/107
20
26.2 PHP
PHPkeywords andbreakcaseclasscontinuedefault
doelseelseifextendfalse
forforeachfunctioglobalif
includlistnewnotor
requirreturnstaticswitchthis
truevarvirtualxorwhile
Fig. 26.5PHPkeywords.
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
8/10/2019 Synapseindia Php Development Chaptr-2
21/107
21
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4< -- Fig. 26.6: arrays.php -->
5< -- Array manipulation -->
6
7
8
9Array manipulation
10
11
12
13
8/10/2019 Synapseindia Php Development Chaptr-2
22/107
8/10/2019 Synapseindia Php Development Chaptr-2
23/107
8/10/2019 Synapseindia Php Development Chaptr-2
24/107
24
26.2 PHPFig. 26.6 Array manipulation.
8/10/2019 Synapseindia Php Development Chaptr-2
25/107
25
26.3 String Processing and Regular
Expressions
String processing Equality and comparison two important operations
strcmpfunction
Returns1 if string 1 < string 2
Returns 0 if string 1 = string 2 Returns 1 if string 1 > string 2
Relational operators
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
8/10/2019 Synapseindia Php Development Chaptr-2
26/107
26
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.7: compare.php -->
5 < -- String Comparison -->
6
7
8
9 String Comparison
10
11
12
13
8/10/2019 Synapseindia Php Development Chaptr-2
27/107
27
26 print( $fruits[ $i ].
27 " is greater than banana ");
28 else
29 print( $fruits[ $i ]." is equal to banana ");
30
31 // use relational operators to compare each element
32 // to string "apple"
33 if( $fruits[ $i ] < "apple")
34 print( "and less than apple
");
35 elseif( $fruits[ $i ] > "apple")
36 print( "and greater than apple
");
37 elseif( $fruits[ $i ] == "apple")
38print( "and equal to apple
");
39
40 }
41 ?>
42
43
compare.php
(2 of 2)
Use relational operators to compare each arrayelement to string apple.
26 3 St i P i d R l
8/10/2019 Synapseindia Php Development Chaptr-2
28/107
28
26.3 String Processing and Regular
ExpressionsFig. 26.7 Using the string comparison operators.
26 3 St i P i d R l
8/10/2019 Synapseindia Php Development Chaptr-2
29/107
29
26.3 String Processing and Regular
Expressions
Regular expressions Pattern matching templates
eregfunction
POSIX
preg_matchfunction Perl
ereg_replacefunction
Building regular expressions
Metacharacters
$, ., ^
Brackets [ ]
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
8/10/2019 Synapseindia Php Development Chaptr-2
30/107
30
2"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.8: expression.php -->
5< -- Using regular expressions -->
6
7
8
9Regular expressions
10
11
12
13
8/10/2019 Synapseindia Php Development Chaptr-2
31/107
31
23 // the string
24 if( ereg( "^Now", $search ) )
25 print( "String 'Now' found at beginning
26 of the line.
");
27
28 // search for pattern 'Now' at the end of the string
29 if( ereg( "Now$", $search ) )
30 print( "String 'Now' was found at the end
31 of the line.
");
32
33 // search for any word ending in 'ow'
34 if( ereg( "[[::]]", $search,
35$match ) )
36 print( "Word found ending in 'ow': ".
37 $match[ 1] . "
");
38
39 // search for any words beginning with 't'
40 print( "Words beginning with 't' found: ");
41
42 while( eregi( "[[::]]",
43 $search, $match ) ) {
44 print( $match[ 1] . " ");
45
expression.php
(2 of 3)
The dollar sign special character ($) search for the
pattern Nowat 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 0or more times.
The special bracket expressions [[::]]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 whileloop is used to find each occurrence of a
word in the string beginning with t.
The pattern used in this example,
[[::]], matches any
word beginning with the character tfollowed by one or
more characters. Character class [[:alpha:]]
recognizes any alphabetic character.
Function eregiis used to specify case insensitive
pattern matches.
The caret special character (^) matches the
beginning of a string. Function eregsearches the
beginning of the string for pattern Now.
8/10/2019 Synapseindia Php Development Chaptr-2
32/107
26 3 St i P i d R l
8/10/2019 Synapseindia Php Development Chaptr-2
33/107
33
26.3 String Processing and Regular
ExpressionsFig. 26.8 Regular expressions in PHP.
26 3 St i P i d R l
8/10/2019 Synapseindia Php Development Chaptr-2
34/107
34
26.3 String Processing and Regular
Expressions
Quantifier Matches{n} Exactlyntimes.{m,n} Betweenmandntimes inclusive.{n,} nor moretimes.+ Oneor moretimes (sameas{1,}).
* Zeroor moretimes (sameas{0,}).? Zeroor onetime(sameas{0,1}).
Fig. 26.9 SomePHPquantifiers.
26 3 St i P i d R l
8/10/2019 Synapseindia Php Development Chaptr-2
35/107
35
26.3 String Processing and Regular
Expressions
Character class Descriptionalnum Alphanumericcharacters(i.e., letters[a-zA-Z] or digits[0-9]).alpha Wordcharacters(i.e., letters[a-zA-Z]).digit Digits.space Whitespace.
lower Lowercaseletters.upper Uppercaseletters.
Fig. 26.10 SomePHPcharacter classes.
26 4 Vie ing Client/Ser er
8/10/2019 Synapseindia Php Development Chaptr-2
36/107
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
26 4 Viewing Client/Server
8/10/2019 Synapseindia Php Development Chaptr-2
37/107
37
26.4 Viewing Client/Server
Environment Variables
Variablename Description
$_SERVER Dataabout thecurrentlyrunningserver.$_ENV Dataabout theclientsenvironment.$_GET Datapostedtotheserver bythegetmethod.$_POST Datapostedtotheserver bythepostmethod.$_COOKIE Datacontainedincookiesontheclientscomputer.$GLOBALS Arraycontainingall global variables.
Fig. 26.11 Someuseful global arrays.
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
8/10/2019 Synapseindia Php Development Chaptr-2
38/107
38
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.11: env.php -->
5 < -- Program to display environment variables -->
6
7
8
9 Environment Variables
10
11
12
13
15
24
25
26
env.php
(1 of 1)
The foreachloop is used to print out the keys andvalues for each element in the $_ENVarray.PHP stores environment variables and their values in
the $_ENVarray.
26 4 Viewing Client/Server
8/10/2019 Synapseindia Php Development Chaptr-2
39/107
39
26.4 Viewing Client/Server
Environment VariablesFig. 26.12 Displaying environment variables.
26 5 Form Processing and Business
8/10/2019 Synapseindia Php Development Chaptr-2
40/107
40
26.5 Form Processing and Business
Logic
Form processingactionproperty
Where to send form data
methodproperty
post Each element has unique name
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
8/10/2019 Synapseindia Php Development Chaptr-2
41/107
41
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 < -- Fig. 26.13: form.html -->
5 < -- Form for use with the form.php program -->
6
7
8
9 Sample form to take user input in XHTML
10
11
12
13
14This is a sample registration form.
15 Please fill in all fields and click Register.
16
17 < -- post form data to form.php -->
18
19
20
21Please fill out the fields below.
22
23
form.html
(1 of 4)
The actionattribute of the formelement
indicates that when the user clicks Register, theform data will be posted to form.php.
24 < -- create four text boxes for user input -->
25
A i ( il) i i d t h
8/10/2019 Synapseindia Php Development Chaptr-2
42/107
42
25
26
27
28
29
30
31
32
33
34
35
36
37
38 Must be in the form (555)555-5555
39
40
41
43
44
45 Which book would you like information about?
46
47
form.html
(2 of 4)
A unique name(e.g., email) is assigned to each
of the forms inputfields. When Registeris
clicked, each fields nameand valueare sent to
the Web server.
48 < -- create drop-down list containing book names -->
49
8/10/2019 Synapseindia Php Development Chaptr-2
43/107
43
49
50 Internet and WWW How to Program 3e
51 C++ How to Program 4e
52 Java How to Program 5e
53 XML How to Program 1e
54
55
56
57
58
59 Which operating system are you currently using?
60
61
62 < -- create five radio buttons -->
63
65 Windows XP
66
67
69 Windows 2000
70
71
73 Windows 98
form.html
(3 of 4)
74
75
8/10/2019 Synapseindia Php Development Chaptr-2
44/107
44
form.html
(4 of 4)
75
76 Linux
77
78
79 Other
80
81 < -- create a submit button -->
82
83
84
85
86
26 5 Form Processing and Business
8/10/2019 Synapseindia Php Development Chaptr-2
45/107
45
26.5 Form Processing and Business
LogicFig. 26.13 XHTML form for gathering user input.
26 5 Form Processing and Business
8/10/2019 Synapseindia Php Development Chaptr-2
46/107
46
26.5 Form Processing and Business
Logic
Business logic Confirm that valid information was entered
extractfunction
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
diefunction
Remember to close all HTML tags
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
8/10/2019 Synapseindia Php Development Chaptr-2
47/107
47
3
4< -- Fig. 26.14: form.php -->
5< -- Read information sent from form.html -->
6
7
8
9 Form Validation
10
11
12
13
14
8/10/2019 Synapseindia Php Development Chaptr-2
48/107
48
24 INVALID PHONE NUMBER
25 A valid phone number must be in the form
26 (555)555-5555
27
28 Click the Back button, enter a valid phone
29 number and resubmit.
30 Thank You.
");31
32 die(); // terminate script execution
33 }
34 ?>
35
36
Hi
37
38
39
40
41 .
42Thank you for completing the survey.
43
form.php
(2 of 4)
Function dieterminates script execution
8/10/2019 Synapseindia Php Development Chaptr-2
49/107
66 print each form fields value
67 print("$fname $lname
8/10/2019 Synapseindia Php Development Chaptr-2
50/107
50
form.php
(4 of 4)
68 $email
69 $phone
70 $os");
71 ?>
72
73
74
75
76
77 This is only a sample form.
78 You have not been added to a mailing list.
79
80
81
26 5 Form Processing and Business
8/10/2019 Synapseindia Php Development Chaptr-2
51/107
51
26.5 Form Processing and Business
LogicFig. 26.14 Obtaining user input through forms.
26 6 Verifying a Username and
8/10/2019 Synapseindia Php Development Chaptr-2
52/107
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
fopenfunction
Read, write, append modes
Store data using fputs
\nnewline character
Close files when done
fclosefunction
26 6 Verifying a Username and
8/10/2019 Synapseindia Php Development Chaptr-2
53/107
53
26.6 Verifying a Username and
Password
Implementing password checking, cont.
Trim newline character
chopfunction
Split string into substrings given a certain delimiter
splitfunction If username/password match list, allow access
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
8/10/2019 Synapseindia Php Development Chaptr-2
54/107
54
3
4 < -- Fig. 26.15: password.html -->
5 < -- XHTML form sent to password.php for verification -->
6
7
8
9 Verifying a username and a password.
10
11
12 td { background-color: #DDDDDD }
13
14
15
16
17
18 Type in your username and password below.
19
20
22 Note that password will be sent as plain text
23
24
25
password.html
(1 of 4)
26 < -- post form data to password.php -->
27
8/10/2019 Synapseindia Php Development Chaptr-2
55/107
55
28
29
30
33
34
35
36 Username:
37
38
39
40
41
42
44
45
46
password.html
(2 of 4)
Form data is posted to password.php.
47
48
8/10/2019 Synapseindia Php Development Chaptr-2
56/107
56
49Password:
50
51
52
53
54
55
58
59
60
61
62
63
66
67
68
71
password.html
(3 of 4)
72
73
8/10/2019 Synapseindia Php Development Chaptr-2
57/107
57
74
75
76 password.html
(4 of 4)
26.6 Verifying a Username and
8/10/2019 Synapseindia Php Development Chaptr-2
58/107
58
26.6 Verifying a Username and
PasswordFig. 26.15 XHTML form for obtaining a username and password.
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
8/10/2019 Synapseindia Php Development Chaptr-2
59/107
59
3
4 < -- Fig. 26.16: password.php -->
5 < -- Searching a database for usernames and passwords. -->
6
7
8
9
8/10/2019 Synapseindia Php Development Chaptr-2
60/107
60
27print( "Error
28 Could not open password file
29 ");
30die();
31}
32
33// write username and password to file and
34// call function userAdded
35 fputs( $file, "$USERNAME,$PASSWORD\n");
36 userAdded( $USERNAME );
37 }
38 else{
39
40// if a new user is not being added, open file
41// for reading
42if( ( $file = fopen( "password.txt",
43"r") ) ) {
44 print( "Error
45Could not open password file
46");
47 die();
48 }
49
password.php
(2 of 7)Print an error message and terminate script execution
if the file cannot be opened.
Function fputswrites the name and password to thetext file..
Function userAddedis called to print a message to the
user to indicate that the username and password wereadded to the file.
50$userVerified = 0;
51
8/10/2019 Synapseindia Php Development Chaptr-2
61/107
61
52 // read each line in file and check username
53 // and password
54 while ( feof( $file ) && $userVerified ) {
55
56// read line from file
57$line = fgets( $file, 255);
58
59 // remove newline character from end of line
60 $line = chop( $line );
61
62 // split username and password
63 $field = split( ",", $line, 2);
64
65// verify username
66if( $USERNAME == $field[ 0] ) {
67$userVerified = 1;
68
69// call function checkPassword to verify
70users password
71if( checkPassword( $PASSWORD, $field )
72== true)
73 accessGranted( $USERNAME );
74 else
75 wrongPassword();
password.php
(3 of 7)
Before entering the whileloop, variable
$userVerifiedis set to 0.
The whileloop executes as long as the there are morelines in the file to read and variable $userVerifiedis
still 0or empty.
Function fgetsreads a line from the text file.
The result is assigned to variable $line.
Function chopremoves the newline characterfrom the end of the line.
Function splitis called to separate the string at the
specified delimiter (in this case, a comma). The
resulting array is stored in array $field.The username entered by the user is tested
against the one returned in the text file (stored
in the first element of the array). If they match,
variable $userVerifiedis set to 1.
Function checkPasswordis called to verify the
users password. Variable $PASSWORDand array
$fieldare passed to the function.
If function checkPasswordreturns true, function
accessGrantedis called to notify the client thatpermission has been granted. Otherwise, function
wrongPasswordis called.
76 }
77 }
78
If variable $userVerified has not been set to a
8/10/2019 Synapseindia Php Development Chaptr-2
62/107
62
78
79 // close text file
80 fclose( $file );
81
82// call function accessDenied if username has
83 // not been verified
84 if( $userVerified )
85accessDenied();
86 }
87
88 // verify user password and return a boolean
89 functioncheckPassword( $userpassword, $filedata )
90{
91 if( $userpassword == $filedata[ 1] )
92returntrue;
93 else
94 returnfalse;
95 }
96
password.php
(4 of 7)
After the whileloop has executed, function
fcloseis called to close the file.
If variable $userVerifiedhas not been set to a
value other than 0, function accessDeniedis
called to notify the client that access has been
denied.
Function checkPasswordcompares the users
password to the password in the file. If they match,
trueis returned, whereas falseis returned if they
do not.
97 // print a message indicating the user has been added
98 functionuserAdded( $name )
99
8/10/2019 Synapseindia Php Development Chaptr-2
63/107
63
99 {
100 print( "Thank You
101
103 You have been added
104 to the user list, $name.
105
Enjoy the site.");
106 }
107
108 // print a message indicating permission
109 // has been granted
110 functionaccessGranted( $name )
111 {
112 print( "Thank You
113
115 Permission has been
116 granted, $name.
117 Enjoy the site.");
118 }
119
password.php
(5 of 7)Function userAddedprints a message to the
client indicating that the user has been added.
Function accessGrantedprints amessage to the client indicating that
permission has been granted.
120// print a message indicating password is invalid
121 functionwrongPassword()
122
8/10/2019 Synapseindia Php Development Chaptr-2
64/107
64
122 {
123print( "Access Denied
124
126 You entered an invalid
127password.
Access has
128 been denied.");
129 }
130
131 // print a message indicating access has been denied
132 functionaccessDenied()
133 {
134print( "Access Denied
135
137
138 You were denied access to this server.
139
" );
140}
141
password.php
(6 of 7)
Function wrongPasswordprints a message to the
client indicating that the password is invalid.
Function accessDeniedprints a message to the
client indicating that access has been denied.
142// print a message indicating that fields
143// have been left blank
144
Function fieldsBlankprints a message to the
8/10/2019 Synapseindia Php Development Chaptr-2
65/107
65
144 functionfieldsBlank()
145{
146 print("Access Denied
147
149
150 Please fill in all form fields.
151
");
152 }
153 ?>
154
155
password.php
(7 of 7)
client indicating that all form fields have not been
completed.
26.6 Verifying a Username and
8/10/2019 Synapseindia Php Development Chaptr-2
66/107
66
y g
PasswordFig. 26.16 Verifying a username and password.
1account1,password12account2,password2
3
8/10/2019 Synapseindia Php Development Chaptr-2
67/107
67
password.txt
(1 of 1)
3account3,password3
4account4,password4
5account5,password5
6account6,password6
7account7,password7
8account8,password8
9account9,password9
10account10,password10
26 7 Connecting to a Database
8/10/2019 Synapseindia Php Development Chaptr-2
68/107
68
26.7 Connecting to a Database
Databases
Store and maintain data
MySQL is a free database product
PHP supports many database operations
Access databases from Web pages
8/10/2019 Synapseindia Php Development Chaptr-2
69/107
22
23 *
24
8/10/2019 Synapseindia Php Development Chaptr-2
70/107
70
24 ID
25 Title
26 Category
27 ISBN
28
29
30
31
34
35
36
data.html
(2 of 2)
Select box containing options for a SELECT
query.
26 7 Connecting to a Database
8/10/2019 Synapseindia Php Development Chaptr-2
71/107
71
26.7 Connecting to a Database
Fig. 26.18 Form to query a MySQL database.
26 7 Connecting to a Database
8/10/2019 Synapseindia Php Development Chaptr-2
72/107
72
26.7 Connecting to a Database
Interacting with databases
SQL
Structured Query Language
Used to manipulate databases
Several useful functionsmysql_connect
mysql_select_db
mysql_query
mysql_error
mysql_fetch_rowmysql_close
1< DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
8/10/2019 Synapseindia Php Development Chaptr-2
73/107
73
3
4< -- Fig. 26.19: database.php -->
5 < -- Program to query a database and -->
6< -- send results to the client. -->
7
8
9
10Search Results
11
12
13
15
8/10/2019 Synapseindia Php Development Chaptr-2
74/107
74
29 die( "Could not open Products database");
30
31 // query Products database
32 if( ( $result = mysql_query( $query, $database ) ) ) {
33print( "Could not execute query
");
34 die( mysql_error() );
35 }
36?>
37
38
39 Search Results
40
41
43
44
8/10/2019 Synapseindia Php Development Chaptr-2
75/107
75
54 foreach( $row as$key => $value )
55 print( "$value");
56
57 print( "");
58}
59
60mysql_close( $database );
61 ?>
62
63
64
65
Your search yielded
66 results.
67
68 Please email comments to
69
70 Deitel and Associates, Inc.
71
72
73
74
75
database.php
(3 of 3)
The foreachloop iterates through the
array containing the elements of each rowand prints out each element in an
individual table cell.The total number of results are printed to the
client.
26 7 Connecting to a Database
8/10/2019 Synapseindia Php Development Chaptr-2
76/107
76
26.7 Connecting to a Database
Fig. 26.19 Querying a database and displaying the results.
26 8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
77/107
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 creditcard numbers, in a cookie
Security risk
Cookies and PHP
setcookiefunction
Name
Value
Expiration date
1< DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
8/10/2019 Synapseindia Php Development Chaptr-2
78/107
78
4 < -- Fig. 26.20: cookies.html -->
5 < -- Writing a Cookie -->
6
7
8
9 Writing a cookie to the client computer
10
11
12
14
15 Click Write Cookie to save your cookie data.
16
cookies.html
(1 of 2)
17
19 Name:
Form data is posted to cookies.php.
8/10/2019 Synapseindia Php Development Chaptr-2
79/107
79
20
21
22 Height:
23
24
25 Favorite Color:
26
27
28
31
32
33
cookies.html
(2 of 2)
p p p
26 8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
80/107
80
26.8 Cookies
Fig. 26.20 Gathering data to be written as a cookie.
1
8/10/2019 Synapseindia Php Development Chaptr-2
81/107
81
4
5 extract( $_POST );
6 write each form fields value to a cookie and set the
7 cookies expiration date
8 setcookie( "Name", $NAME, time() + 60* 60* 24* 5);
9 setcookie( "Height", $HEIGHT, time() + 60* 60* 24* 5);
10 setcookie( "Color", $COLOR, time() + 60* 60* 24* 5);
11 ?>
12
13 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15
16
17
18 Cookie Saved
19
20
21
22
The cookie has been set with the following data:
23
cookies.php
(1 of 2)
Function setcookietakes 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.
24 < --print each form fields value-->
25
Name:
26
Each form fields valueis printed to
confirm the data that has been set as a
8/10/2019 Synapseindia Php Development Chaptr-2
82/107
82
27
28 Height:
29
30
31 Favorite Color:
32
33
8/10/2019 Synapseindia Php Development Chaptr-2
83/107
83
26.8 Cookies
Fig. 26.21 Writing a cookie to the client.
26 8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
84/107
84
26.8 Cookies
Reading cookies
$_COOKIEenvironment variable
Array
foreachloop to access each element
Split into key and value
26 8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
85/107
85
26.8 Cookies
Cookie storage
Internet Explorer
Stores cookies in Cookiesdirectory
Text file
26 8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
86/107
86
26.8 Cookies
Fig. 26.22 Cookiesdirectory before a cookie is written.
Fig. 26.23 Cookiesdirectory after a cookie is written.
1 < DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
8/10/2019 Synapseindia Php Development Chaptr-2
87/107
87
4 < -- Fig. 26.24: readCookies.php -->
5 < -- Program to read cookies from the client's computer -->
6
7
8Read Cookies
9
10
11
12
13
14 The following data is saved in a cookie on your
15 computer.
16
17
18
readCookies.php
(1 of 2)
8/10/2019 Synapseindia Php Development Chaptr-2
88/107
26.8 Cookies
8/10/2019 Synapseindia Php Development Chaptr-2
89/107
89
26.8 Cookies
Fig. 26.24 Displaying the cookies content.
26.9 Dynamic Content in PHP
8/10/2019 Synapseindia Php Development Chaptr-2
90/107
90
26.9 Dynamic Content in PHP
Dynamically alter XHTML content
Forms actionproperty set to same page that
contains it
Perform different actions when page is loaded and
form is submitted
issetvariable
Check for errors
Write different XHTML when errors encountered
$$variablesyntax References variable whose name equals the value of
$variable
If input is valid, make MySQL database calls
1 < DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4
8/10/2019 Synapseindia Php Development Chaptr-2
91/107
91
4 < -- Fig. 26.25: dynamicForm.php -->
5 < -- Form for use with the form.php program -->
6
7
8
9 Sample form to take user input in XHTML
10
11
12
13
8/10/2019 Synapseindia Php Development Chaptr-2
92/107
92
26 "Windows 98",
27 "Linux",
28 "Other");
29
30 // array of name and alt values for the text input fields
31 $inputlist = array( "fname"=> "First Name",
32 "lname"=> "Last Name",
33 "email"=> "Email",
34 "phone"=> "Phone");
35
36 if( isset ( $submit ) ) {
37 if( $fname == "") {
38 $formerrors[ "fnameerror"] = true;
39 $iserror = true;
40 }
41
42 if( $lname == "") {
43 $formerrors[ "lnameerror"] = true;
44 $iserror = true;
45 }
46
dynamicForm.php
(2 of 9)
Check for errors or omissions in form field
input.
If the page is being loaded as a result of a form
submission, do error checking and then retrieve
information from the database.
47 if( $email == "") {
48 $formerrors[ "emailerror"] = true;
49 $iserror = true;
50
8/10/2019 Synapseindia Php Development Chaptr-2
93/107
93
50 }
51
52if( ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) {
53$formerrors[ "phoneerror"] = true;
54$iserror = true;
55 }
56
57 if( $iserror ) {
58
59 // build INSERT query
60 $query = "INSERT INTO contacts ".
61"( LastName, FirstName, Email, Phone, Book, OS ) ".
62"VALUES ( '$lname', '$fname', '$email', ".
63"'". quotemeta( $phone ) . "', '$book', '$os' )";
64
65// Connect to MySQL
66if( ( $database = mysql_connect( "localhost",
67"httpd", "") ) )
68die( "Could not connect to database" );
69
70 // open MailingList database
71 if( mysql_select_db( "MailingList", $database ) )
72 die( "Could not open MailingList database");
dynamicForm.php
(3 of 9)
If there were no errors, query the MySQL
database.
73
74// execute query in MailingList database
75if( ( $result = mysql_query( $query, $database ) ) ) {
76
8/10/2019 Synapseindia Php Development Chaptr-2
94/107
94
76print( "Could not execute query
");
77die( mysql_error() );
78 }
79
80print( "
Hi
81
82$fname.
83Thank you for completing the survey.
84
85You have been added to the
86
87$book
88mailing list.
89
90The following information has been saved
91in our database:
92
93
94
95Name
96Email
97Phone
dynamicForm.php
(4 of 9)
98OS
99
100
101
8/10/2019 Synapseindia Php Development Chaptr-2
95/107
95
101
102 < --print each form fields value -->
103$fname $lname
104$email
105$phone
106$os
107
108
109
110
111
112
113Click here to view entire database.
114This is only a sample form.
115You have not been added to a mailing list.
116");
117 die();
118}
119}
120
121 print( "This is a sample registration form.
122Please fill in all fields and click Register.");
dynamicForm.php
(5 of 9)
Halt the script so the form-generation code
does not execute.
123
124 if( $iserror ) {
125 print( "
126
8/10/2019 Synapseindia Php Development Chaptr-2
96/107
96
126 Fields with * need to be filled in properly.");
127 }
128
129print( "< -- post form data to form.php -->
130
131
132
133 Please fill out the fields below.
134
135
136 < -- create four text boxes for user input -->");
137foreach( $inputlist as$inputname => $inputalt ) {
138$inputtext = $inputvalues[ $inputname ];
139
140print( "");
143
144if( $formerrors[ ( $inputname )."error"] == true)
145print( "*");
146
147 print( "
");
148 }
dynamicForm.php
(6 of 9)
If the form input contained errors, place a red
asterisk (*) next to the text field.
Fill in the forms using$$variable
syntax.
149
150print( "
8/10/2019 Synapseindia Php Development Chaptr-2
97/107
97
152if( $formerrors[ "phoneerror"] )
153print( "; color : red");
154
155 print( "'>Must be in the form (555)555-5555
156
157
158
160
161
162Which book would you like information about?
163
164
165< -- create drop-down list containing book names -->
166");
167
168foreach( $booklist as$currbook ) {
169print( "$currbook");
175 }
176
177
8/10/2019 Synapseindia Php Development Chaptr-2
98/107
98
177 print( "
178
179
180Which operating system are you currently using?
181
182
183 < -- create five radio buttons -->");
184
185 $counter = 0;
186
187 foreach( $systemlist as$currsystem ) {
188print( "$currsystem");
195
196if( $counter == 2) print( "
");
197 $counter++;
198 }
199
dynamicForm.php
(8 of 9)
Make sure the correct OS is checked in thecheckbox.
200 print("< -- create a submit button -->
201
202
203
8/10/2019 Synapseindia Php Development Chaptr-2
99/107
99
203 ");
204 ?> dynamicForm.php
(9 of 9)
26.9 Dynamic Content in PHP
8/10/2019 Synapseindia Php Development Chaptr-2
100/107
100
y
Fig. 26.25 Dynamic form using PHP.
26.9 Dynamic Content in PHP
8/10/2019 Synapseindia Php Development Chaptr-2
101/107
101
y
Fig. 26.25 Dynamic form using PHP.
1< DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4
8/10/2019 Synapseindia Php Development Chaptr-2
102/107
102
4< -- Fig. 26.26: formDatabase.php -->
5< -- Program to query a database and -->
6< -- send results to the client. -->
7
8
9
10Search Results
11
12
13
15
8/10/2019 Synapseindia Php Development Chaptr-2
103/107
103
30
31// query MailingList database
32if( ( $result = mysql_query( $query, $database ) ) ) {
33print( "Could not execute query
");
34die( mysql_error() );
35}
36 ?>
37
38
39 Mailing List Contacts
40
41
43
44
45 ID
46Last Name
47First Name
48 E-mail Address
49 Phone Number
50Book
formDatabase.php
(2 of 3)
51Operating System
52
53
8/10/2019 Synapseindia Php Development Chaptr-2
104/107
104
55 // fetch each record in result set
56for( $counter = 0;
57$row = mysql_fetch_row( $result );
58$counter++ ){
59
60 // build table to display results
61 print( "");
62
63 foreach( $row as$key => $value )
64 print( "$value");
65
66print( "");
67 }
68
69mysql_close( $database );
70 ?>
71
72
73
74
75
formDatabase.php
(3 of 3)
Dynamically create a table
containing each mailing list
member.
member record from the
database.
26.9 Dynamic Content in PHP
8/10/2019 Synapseindia Php Development Chaptr-2
105/107
105
Fig. 26.26 Displaying the MailingListdatabase.
26.10 Operator Precedence
8/10/2019 Synapseindia Php Development Chaptr-2
106/107
106
Operator Type Associativitynew constructor none
[] subscript right to left
~!++---@
bitwise notnot
increment
decrement
unary negative
error control
right to left
*/%
multiplication
division
modulus
left to right
+-.
addition
subtraction
concatenation
left to right
>
bitwise shift left
bitwise shift right
left to right
=
less than
greater than
less than or equal
greater than or equal
none
==!====!==
equal
not equal
identical
not identical
none
Fig. 26.27 PHP operator precedence and associativity.
26.10 Operator Precedence
8/10/2019 Synapseindia Php Development Chaptr-2
107/107
Operator Type Associativity& bitwise AND left to right
^ bitwise XOR left to right
| bitwise OR left to right&& logical AND left to right
|| logical OR left to right
=+=-=*=/=
&=|=^=.==
assignment
addition assignment
subtraction assignment
multiplication assignment
division assignment
bitwise AND assignment
bitwise OR assignment
bitwise exclusive OR assignment
concatenation assignment
bitwise shift left assignment
bitwise shift right assignment
left to right
and logical AND left to right
xor exclusive OR left to rightor logical OR left to right
, list left to right
Fig. 26.27 PHP operator precedence and associativity.
Top Related