0% found this document useful (0 votes)
17 views

PHP Scripting

Uploaded by

Sari Roma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

PHP Scripting

Uploaded by

Sari Roma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

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

11/1/2024 © Reem Al-Attas 1


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
11/1/2024 © Reem Al-Attas 2
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 Scripting delimiters
7 <?php
8 $name = "LunaTic"; // declaration
9 ?> Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12 <head>
13 <title>A simple PHP document</title>Single-line comment
14 </head>
15
16 <body style = "font-size: 2em">
17 <p>
18 <strong>
19
20 <!-- print variable name’s value -->
21 Welcome to PHP, <?php print( "$name" ); ?>!
22 </strong>
23 </p>
24 </body>
Function print outputs the value of variable
$name
25 </html>
PHP

11/1/2024 © Reem Al-Attas 4


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
11/1/2024 © Reem Al-Attas 5
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.

11/1/2024 © Reem Al-Attas 6


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 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>PHP data types</title>
10 </head>
11
12 <body>
13
14 <?php Assign a string to variable
15
$testString
16 // declare a string, double and integer
17 $testString = "3.5 seconds";
18 $testDouble = 79.2;
Assign a double to variable
$testDouble
Assign an integer to variable
19 $testInteger = 12;
$testInteger
20 ?>
21
22 <!-- print each variable’s value -->
23 <?php print( $testString ); ?> is a string.<br />
24 <?php print( $testDouble ); ?> is a double.<br />
25 <?php print( $testInteger ); ?> is an integer.<br />
26
27 <br /> Print each variable’s value
28 Now, converting to other types:<br />
29 <?php
30
31 // call function settype to convert variable
32 // testString to different data types
33 print( "$testString" );
34 settype( $testString, "double" );
35 print( " as a double is $testString <br />" );
36 print( "$testString" );
37 settype( $testString, "integer" );
38 print( " as an integer is $testString <br />" );
39 settype( $testString, "string" );
40 print( "Converting back toCall function
a string settype
results in to
41 $testString <br /><br convert
/>" the data type
); settype
Call function to of
42 convert the data$testString
variable type of to a
43 $data = "98.6 degrees"; double.
variable $testString to an
integer.
Convert variable $testString
back to a string
44
45 // use type casting to cast variables to a
46 // different type
47 print( "Now using type casting instead: <br />
48 As a string - " . (string) $data .
49 "<br />As a double - " . (double) $data .
50 "<br />As an integer - " . (integer) $data );
51 ?>
Use type casting to cast variable
52 </body>
$data to different types
53 </html>
PHP

11/1/2024 © Reem Al-Attas 10


PHP

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

⚫Constants
Named values
define function

11/1/2024 © Reem Al-Attas 11


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 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using arithmetic operators</title>
10 </head>
11
12 <body>
13 <?php
14 $a = 5; Define constant VALUE.
15 print( "The value of variable a is $a <br />" );
16
17 // define constant VALUE
Add constant VALUE to variable $a.
18 define( "VALUE", 5 );
19
20 // add constant VALUE to variable $a
21 $a = $a + VALUE;
22 print( "Variable a after adding constant VALUE
23 is $a <br />" );
24
25 // multiply variable $a by 2
26 $a *= 2;
Multiply variable $a by two using the
27 print( "Multiplying variable a by 2 yields $a <br />" );
multiplication assignment operator *=.
28
29 // test if variable $a is less than 50
30 if ( $a < 50 )
Print if variable $a isTest than 50.variable $a is less than 50
lesswhether
31 print( "Variable a is less than 50 <br />" );
32
33 // add 40 to variable $a
Add 40 to variable $a using the addition assignment
34 $a += 40;
operator +=.
35 print( "Variable a after adding 40 is $a <br />" );
36
37 // test if variable $a is 50 or less
38 if ( $a < 51 )
39 print( "Variable a is still 50 or less<br />" );
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<br />" );
45 else
46 print( "Variable a is now greater than 100
47 <br />" );
48
49 // print an uninitialized variable
50 print( "Using a variable before initializing:
51 $nothing <br />" );
52
53 // add constant VALUE to an uninitialized variable
54 $test = $num + VALUE;
55 print( "An uninitialized variable plus constant
56 VALUE yields $test <br />" );
57 Print anAdd
uninitialized variable
constant VALUE $nothing
to (an ).
uninitialized
58 // add a string to an integer
variable.
59 $str = "3 dollars";
60 $a += $str;
61 print( "Adding a string to variable a yields $a
62 <br />" );
63 ?>
64 </body>
Add a string to an integer.
65 </html>
PHP

11/1/2024 © Reem Al-Attas 15


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
11/1/2024 © Reem Al-Attas 16
PHP

⚫Arrays, cont.
Built-in iterators
⚫Maintain pointer to element currently referenced
⚫ reset
⚫ key
⚫ next
⚫ foreach loops

11/1/2024 © Reem Al-Attas 17


PHP
PHP keywords
and do for include require true
break else foreach list return var
case elseif function new static virtual
class extends global not switch xor
continue false if or this while
default
Fig. 26.5 PHP keywords.

11/1/2024 © Reem Al-Attas 18


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.6: arrays.php -->
5 <!-- Array manipulation -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Array manipulation</title>
10 </head>
11
12 <body>
13 <?php Create the array $first by assigning a value
14 to an array element.
15 // create array first
16 print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
19 $first[ 1 ] = Assign
"one"; a value to the array, omitting the index.
20 $first[ 2 ] = Appends
"two"; a Use for loop
newaelement to to
theprint
end out each
of the element’s index and value.
array.
21 $first[] = "three"; Function count returns the total number of elements in the
22 array.
23 // print each element’s index and value
24 for ( $i = 0; $i < count( $first ); $i++ )
25 print( "Element $i is $first[$i] <br />" );
26
27 print( "<br /><strong>Creating the second array
28 </strong><br />" ); Call function array to create an array that contains
29 the arguments passed to it. Store the array in variable
30 // call function array to create array$second
second .
31 $second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print( "Element $i is $second[$i] <br />" );
34
35 print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values to non-numerical indices
39 $third[ "ArtTic" ] = 21;
Assign values to non-numerical indices
40 $third[ "LunaTic" ] = 18;
in array $third.
41 $third[ "GalAnt" ] = 23;
Function reset sets the internal pointer to the
42
first element of the array.
43 // iterate through the array elements and print each
44 // element’s name and value
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 print( "$element is $third[$element] <br />" );
48 Function key returns the index of the element which
the internal pointer references.
Function next moves the internal pointer to the next
element.
49 print( "<br /><strong>Creating the fourth array
50 </strong><br />" );
51
52 // call function array to create array fourth using
53 // string indices
54 $fourth = array(
55 "January" => "first", "February" => "second",
56 "March" => "third", "April" => "fourth",
57 "May" => "fifth",
Operator
"June"
=>=>is used in function array to assign each
"sixth",
58 "July" => "seventh",element a string
"August" index. The value to the left of the
=> "eighth",
59 "September" => "ninth", operator is the
"October" => array index, and the value to the right is
"tenth",
60 "November" => the element’s=>value.
"eleventh","December" "twelfth"
61 );
62
63 // print each element’s name and value
64 foreach ( $fourth as $element => $value )
65 print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>
PHP

11/1/2024 © Reem Al-Attas 22


String Processing and Regular
Expressions
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

11/1/2024 © Reem Al-Attas 24


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.7: compare.php -->
5 <!-- String Comparison -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>String Comparison</title>
10 </head>
11
12 <body>
13 <?php
Use a for loop to iterate through each array element.
14
15 // create array fruits
16 $fruits = array( "apple", "orange", "banana" );
Function strcmp compares two strings. If the first string
17
alphabetically precedes the second, then –1 is returned. If
18 // iterate through each array element
the strings are equal, 0 is returned. If the first string
19 for ( $i = 0; $i < count( $fruits ); $i++ ) {
20
alphabetically follows the second, then 1 is returned.
21 // call function strcmp to compare the array element
22 // to string "banana"
23 if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
24 print( $fruits[ $i ]." is less than banana " );
25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
26 print( $fruits[ $i ].
27 " is greater than banana " );
28 else
29 print( $fruits[ $i ]." is Use relational
equal to bananaoperators
" ); to compare each array
30
element to string “apple”.
31 // use relational operators to compare each element
32 // to string "apple"
33 if ( $fruits[ $i ] < "apple" )
34 print( "and less than apple! <br />" );
35 elseif ( $fruits[ $i ] > "apple" )
36 print( "and greater than apple! <br />" );
37 elseif ( $fruits[ $i ] == "apple" )
38 print( "and equal to apple! <br />" );
39
40 }
41 ?>
42 </body>
43 </html>
String Processing and Regular
Expressions

11/1/2024 © Reem Al-Attas 27


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 [ ]
11/1/2024 © Reem Al-Attas 28
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.8: expression.php -->
5 <!-- Using regular expressions -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Regular expressions</title>
10 </head>
11
12 <body>
13 <?php Function ereg searches for the literal
14 $search = "Now is the characters
time"; Now inside variable $search.
15 print( "Test string is: '$search'<br /><br />" );
16
17 // call function ereg to search for pattern 'Now'
18 // in variable search
19 if ( ereg( "Now", $search ) )
20 print( "String 'Now' was found.<br />" );
21
22 // search for pattern 'Now' in the beginning of
23 // the string
24 if ( ereg( "^Now", $search ) )
The dollar sign special character ($) search for the
25 print( "String 'Now' found at beginning
pattern
The caret special Now at
character (^)the end of the
matches the string.
26 of the line.<br />" );
27 beginning of a string. Function ereg searches the
28 // search for beginning
pattern 'Now' atofthe
theend
string string Now .
for pattern
of the
29 if ( ereg( "Now$", $search ) )
30 print( "String 'Now' was found at the end
31 of the line.<br />" );
32
33 // search for any word ending in 'ow'
34 if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search,
35 $match ) )
36 print( "Word found ending in 'ow': " .
37 $match[ 1 ] . "<br />" );
38
The expression
The specialinside the expressions
bracket [a-zA-Z]*ow
parentheses,[[:<:]] and ,
39 // search for any words beginning with 't'
matches
Placingany
[[:>:]] word
a patternending
in the
match in ow. The
parentheses
beginning quantifier
stores
and the of
end a*
matched
40 print( "Words beginning with 't' found: ");
matches
string thethe
in
word, preceding
array that
respectively.pattern 0 or more
is specified times.
in the third argument
41
42
to function ereg.
while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
43 $search, $match ) ) {
44 print( $match[ 1 ] . " " );
The pattern used in this example,
45
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any
The while word
loop is used to find
witheach occurrence of a
Function eregi beginning
is used to specify case insensitivet followed by one or
the character
word in themore
stringcharacters. with t. class [[:alpha:]]
beginningCharacter
pattern matches.
recognizes any alphabetic character.
46 // remove the first occurrence of a word beginning
47 // with 't' to find other instances in the string
48 $search = ereg_replace( $match[ 1 ], "", $search );
49 }
50 After printing a match of a word beginning with t, function
51 print( "<br />" ); ereg_replace is called to remove the word from the string.
52 ?> This is necessary be because to find multiple instances of a
53 </body> given pattern, the first matched instance must first be removed.
54 </html>
Function ereg_replace takes three arguments: the pattern to
match, a string to replace the matched string and the string to
search.
String Processing and Regular
Expressions

11/1/2024 © Reem Al-Attas 32


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.

11/1/2024 © Reem Al-Attas 33


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.

11/1/2024 © Reem Al-Attas 34


Viewing Client/Server
Environment Variables
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

11/1/2024 © Reem Al-Attas 36


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.

11/1/2024 © Reem Al-Attas 37


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.11: env.php -->
5 <!-- Program to display environment variables -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Environment Variables</title>
10 </head>
11
12 <body>
13 <table border = "0" cellpadding = "2" cellspacing = "0"
14 width = "100%">
15 <?php
16
17 // print the key and value for each element
18 // in the $_ENV array
19 foreach ( $_ENV as $key => $value )
20 print( "<tr><td bgcolor = \"#11bbff\">
21 The foreach loop
<strong>$key</strong></td> is used to print out the keys and
22 <td>$value</td></tr>" ); element in the $_ENV array.
values for each
23 ?> PHP stores environment variables and their values in
24 </table> the $_ENV array.
25 </body>
26 </html>
Viewing Client/Server Environment
Variables

11/1/2024 © Reem Al-Attas 39


Form Processing and
Business Logic
Form Processing and Business
Logic
⚫Form processing
action property
⚫Where to send form data
method property
⚫ post
Each element has unique name

11/1/2024 © Reem Al-Attas 41


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.13: form.html -->
5 <!-- Form for use with the form.php program -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample form to take user input in XHTML</title>
10 </head>
11
12 <body>
13 The action attribute of the form element
14 <h1>This is indicates
a sample registration that when the user clicks Register, the
form.</h1>
15 Please fill form
in all fields and data
click will be posted to form.php.
Register.
16
17 <!-- post form data to form.php -->
18 <form method = "post" action = "form.php">
19 <img src = "images/user.gif" alt = "User" /><br />
20 <span style = "color: blue">
21 Please fill out the fields below.<br />
22 </span>
23
24 <!-- create four text boxes for user input -->
25 <img src = "images/fname.gif" alt = "First Name" />
A unique name (e.g., email) is assigned to each
26 <input type = "text" name = "fname" /><br />
of the form’s input fields. When Register is
27
clicked, each field’s name and value are sent to
28 <img src = "images/lname.gif" alt = "Last Name" />
the Web server.
29 <input type = "text" name = "lname" /><br />
30
31 <img src = "images/email.gif" alt = "Email" />
32 <input type = "text" name = "email" /><br />
33
34 <img src = "images/phone.gif" alt = "Phone" />
35 <input type = "text" name = "phone" /><br />
36
37 <span style = "font-size: 10pt">
38 Must be in the form (555)555-5555</span>
39 <br /><br />
40
41 <img src = "images/downloads.gif"
42 alt = "Publications" /><br />
43
44 <span style = "color: blue">
45 Which book would you like information about?
46 </span><br />
47
48 <!-- create drop-down list containing book names -->
49 <select name = "book">
50 <option>Internet and WWW How to Program 3e</option>
51 <option>C++ How to Program 4e</option>
52 <option>Java How to Program 5e</option>
53 <option>XML How to Program 1e</option>
54 </select>
55 <br /><br />
56
57 <img src = "images/os.gif" alt = "Operating System" />
58 <br /><span style = "color: blue">
59 Which operating system are you currently using?
60 <br /></span>
61
62 <!-- create five radio buttons -->
63 <input type = "radio" name = "os" value = "Windows XP"
64 checked = "checked" />
65 Windows XP
66
67 <input type = "radio" name = "os" value =
68 "Windows 2000" />
69 Windows 2000
70
71 <input type = "radio" name = "os" value =
72 "Windows 98" />
73 Windows 98<br />
74
75 <input type = "radio" name = "os" value = "Linux" />
76 Linux
77
78 <input type = "radio" name = "os" value = "Other" />
79 Other<br />
80
81 <!-- create a submit button -->
82
83
84
</form> form.html
<input type = "submit" value = "Register" />

85 </body>
86 </html> (4 of 4)
Form Processing and Business
Logic

11/1/2024 © Reem Al-Attas 46


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
11/1/2024 © Reem Al-Attas 47
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.14: form.php -->
5 <!-- Read information sent from form.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Form Validation</title>
10 </head>
11
12 <body style = "font-family: arial,sans-serif">
Function ereg is called to determine whether the
13 The parentheses in the expression must be
<?php phone number entered by the user is valid.
14 followed by The digits ([0-9]{3}
threeexpression ), a closing
\( matches the opening
15 extract( $_POST );
parenthesis, parentheses
three digits, of
a literal hyphen and
a phone number.
16 four additional digits.
17 // determine whether phone number is valid and print
18 // an error message if not
19 if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$",
20 $phone ) ){
21
We access the phone field’s value from
form.html by using variable $phone.
22 print( "<p><span style = \"color: red;
23 font-size: 2em\">
24 INVALID PHONE NUMBER</span><br />
25 A valid phone number must be in the form
26 <strong>(555)555-5555</strong><br />
27 <span style = \"color: blue\">
28 Click the Back button, enter a valid phone
Function die terminates script execution
29 number and resubmit.<br /><br />
30 Thank You.</span></p></body></html>" );
31
32 die(); // terminate script execution
33 }
34 ?>
35
36 <p>Hi
37 <span style = "color: blue">
38 <strong>
39 <?php print( "$fname" ); ?>
40 </strong>
41 </span>.
42 Thank you for completing the survey.<br />
43
44 You have been added to the
45 <span style = "color: blue">
46 <strong>
47 <?php print( "$book " ); ?>
48 </strong>
49 </span>
50 mailing list.
51 </p>
52 <strong>The following information has been saved
53 in our database:</strong><br />
54
55 <table border = "0" cellpadding = "0" cellspacing = "10">
56 <tr>
57 <td bgcolor = "#ffffaa">Name </td>
58 <td bgcolor = "#ffffbb">Email</td>
59 <td bgcolor = "#ffffcc">Phone</td>
60 <td bgcolor = "#ffffdd">OS</td>
61 </tr>
62
63 <tr>
64 <?php
65
66 // print each form field’s value
67 print( "<td>$fname $lname</td>
68 <td>$email</td>
69 <td>$phone</td>
70 <td>$os</td>" );
71 ?>
72 </tr>
73 </table>
74
75
76
<br /><br /><br /> form.php
<div style = "font-size: 10pt; text-align: center">
77
78
79
This is only a sample form.
(4 of 4)
You have not been added to a mailing list.
</div>
80 </body>
81 </html>
Form Processing and Business
Logic

11/1/2024 © Reem Al-Attas 52


Verifying a Username and
Password
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
11/1/2024 © Reem Al-Attas 54
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

11/1/2024 © Reem Al-Attas 55


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.15: password.html -->
5 <!-- XHTML form sent to password.php for verification -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Verifying a username and a password.</title>
10
11 <style type = "text/css">
12 td { background-color: #DDDDDD }
13 </style>
14 </head>
15
16 <body style = "font-family: arial">
17 <p style = "font-size: 13pt">
18 Type in your username and password below.
19 <br />
20 <span style = "color: #0000FF; font-size: 10pt;
21 font-weight: bold">
22 Note that password will be sent as plain text
23 </span>
24 </p>
25
26 <!-- post form data to password.php -->
27 <form action = "password.php" method = "post">
28 <br />
29
Form data is posted to password.php.
30 <table border = "0" cellspacing = "0"
31 style = "height: 90px; width: 123px;
32 font-size: 10pt" cellpadding = "0">
33
34 <tr>
35 <td colspan = "3">
36 <strong>Username:</strong>
37 </td>
38 </tr>
39
40 <tr>
41 <td colspan = "3">
42 <input size = "40" name = "USERNAME"
43 style = "height: 22px; width: 115px" />
44 </td>
45 </tr>
46
47 <tr>
48 <td colspan = "3">
49 <strong>Password:</strong>
50 </td>
51 </tr>
52
53 <tr>
54 <td colspan = "3">
55 <input size = "40" name = "PASSWORD"
56 style = "height: 22px; width: 115px"
57 type = "password" />
58 <br/></td>
59 </tr>
60
61 <tr>
62 <td colspan = "1">
63 <input type = "submit" name = "Enter"
64 value = "Enter" style = "height: 23px;
65 width: 47px" />
66 </td>
67 <td colspan = "2">
68 <input type = "submit" name = "NewUser"
69 value = "New User"
70 style = "height: 23px" />
71 </td>
72 </tr>
73 </table>
74 </form>
75 </body>
76 </html>
Verifying a Username and
Password

11/1/2024 © Reem Al-Attas 60


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.16: password.php -->
5 <!-- Searching a database for usernames and passwords. -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head> Variable names, when preceded by the logical
9 <?php negation operator (!), return true if they are empty
10 extract( $_POST ); or set to 0. This checks if a user has submitted a form
11 without specifying a username or password.
12 // check if user has left USERNAME or PASSWORD field blank
13 if ( !$USERNAME || !$PASSWORD ) { Function fieldsBlank is called if the user has
14 fieldsBlank(); submittedisset
an incomplete formthe
to notify the user
Function tests whether user has
15 die(); that all form fields must be completed.
pressed the New User button, indicating that a
16 }
new user must be added.
17
18 // check if the New User button wasTo add a
clicked new user, we open the file
19 if ( isset( $NewUser ) ) { password.txt in append mode and assign the
20 file handle that is returned to variable $file.
21 // open password.txt for writing using append mode
22 if ( !( $file = fopen( "password.txt",
23 "a" ) ) ) {
24
25 // print error message and terminate script
26 // execution if file cannot be opened
27 print( "<title>Error</title></head><body>
28 Could not open password file
29 </body></html>" );
30 die(); Print an error message and terminate script execution
31 } if the file cannot be opened.
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 { Function userAdded is called to print a message to the
Function fputs writes the name and password to the
39 user to indicate that the username and password were
text file..
40 // if a new user isadded to theadded,
not being file. open file
41 // for reading
42 if ( !( $file = fopen( "password.txt",
43 "r" ) ) ) {
44 print( "<title>Error</title></head>
45 <body>Could not open password file
46 </body></html>" );
47 die();
48 }
49
50 $userVerified = 0;
51
52 // read each line in file and check
Before username
entering the while loop, variable
53 // and password fgets reads a line
Function$userVerified from
is set to 0the
. text file.
54 while ( !feof( $file ) && !$userVerified
The result ) {
is assigned to variable $line.
55
56 // read line from file
57
The while loop$file,
executes
$line = fgets(Function
as
chop
255
long as the there are more
); removes the newline character
58
lines in the filefrom
to read and of
the end variable $userVerified is
the line.
Function
still split is called to separate the string at the
0 or empty.
59 // remove newline character from end of line
specified delimiter (in this case, a comma). The
60 $line = chop( $line );
The username
resulting array is stored inentered by the user
array $field . is tested
61
against the one returned in the text file (stored
62 // split username and password
in the first element of the array). If they match,
63 $field = split( ",", $line, 2 );
variable $userVerified is set to 1.
64
65 // verify username
66 if ( $USERNAME == $field[ 0 ] ) {
67 $userVerified = 1;
68
69 If function
// call function checkPassword to verify checkPassword returns true, function
70 // user’s password accessGranted is called to notify the client that
71 permission
if ( checkPassword( $PASSWORD, $field ) has been granted. Otherwise, function
72 == true ) wrongPassword is called.
73 accessGranted( $USERNAME );
74 else
Function checkPassword is called to verify the
75 wrongPassword();
user’s password. Variable $PASSWORD and array
$field are passed to the function.
76 }
77 }
78 If variable $userVerified has not been set to a
value otherAfter
than 0the while loop
, function has executed,
accessDenied is function
79 // close text file
80 fclose( $file
fclose is called to close the file.
);called to notify the client that access has been
81 denied.
82 // call function accessDenied if username has
83 // not been verified
Function checkPassword compares the user’s
84 if ( !$userVerified )
password to the password in the file. If they match,
85 accessDenied();
true is returned, whereas false is returned if they
86 }
do not.
87
88 // verify user password and return a boolean
89 function checkPassword( $userpassword, $filedata )
90 {
91 if ( $userpassword == $filedata[ 1 ] )
92 return true;
93 else
94 return false;
95 }
96
97 // print a message indicating the user has been added
98 function userAdded( $name )
99 {
100 print( "<title>Thank You</title></head>
101 Function userAdded
<body style = \"font-family: arial; prints a message to the
102 font-size: 1em; client
color: indicating that the user has been added.
blue\">
103 <strong>You have been added
104 to the user list, $name. Function accessGranted prints a
105 <br />Enjoy the site.</strong>"message
); to the client indicating that
106 } permission has been granted.
107
108 // print a message indicating permission
109 // has been granted
110 function accessGranted( $name )
111 {
112 print( "<title>Thank You</title></head>
113 <body style = \"font-family: arial;
114 font-size: 1em; color: blue\">
115 <strong>Permission has been
116 granted, $name. <br />
117 Enjoy the site.</strong>" );
118 }
119
120 // print a message indicating password is invalid
121 function wrongPassword()
122 {
Function wrongPassword prints a message to the
123 print( "<title>Access Denied</title></head>
client indicating that the password is invalid.
124 <body style = \"font-family: arial;
125 font-size: 1em; color: red\">
126 <strong>You entered an invalid
127 password.<br />Access has
128 been denied.</strong>" );
129 }
130
131 // print a message indicating access has been denied
132 function accessDenied()
133 {
134 print( "<title>Access Denied</title></head>
135 <body style = \"font-family: arial;
136 font-size: 1em; color: red\">
137 <strong>
138 You were denied access to this server.
139 <br /></strong>" ); Function accessDenied prints a message to the
140 } client indicating that access has been denied.
141
142 // print a message indicating that fields
143 // have been left blank
Function fieldsBlank prints a message to the
144 function fieldsBlank()
client indicating that all form fields have not been
145 {
completed.
146 print( "<title>Access Denied</title></head>
147 <body style = \"font-family: arial;
148 font-size: 1em; color: red\">
149 <strong>
150 Please fill in all form fields.
151 <br /></strong>" );
152 }
153 ?>
154 </body>
155 </html>
Verifying a Username and
Password

11/1/2024 © Reem Al-Attas 68


1 account1,password1
2 account2,password2
3 account3,password3
4 account4,password4
5 account5,password5
6 account6,password6
7 account7,password7
8 account8,password8
9 account9,password9
10 account10,password10

password.txt
Connecting to a Database
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

11/1/2024 © Reem Al-Attas 71


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.18: data.html -->
5 <!-- Querying a MySQL Database -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample Database Query</title>
10 </head>
11
12 <body style = "background-color: #F0E68C">
13 <h2 style = "font-family: arial color: blue">
14 Querying a MySQL database.
15 </h2>
16
17 <form method = "post" action = "database.php">
18 <p>Select a field to display:
19
20 <!-- add a select box containing options -->
21 <!-- for SELECT query -->
22 <select name = "select">
23 <option selected = "selected">*</option>
24 <option>ID</option>
25 <option>Title</option> Select box containing options for a SELECT
26 <option>Category</option> query.
27 <option>ISBN</option>
28 </select>
29 </p>
30
31 <input type = "submit" value = "Send Query"
32 style = "background-color: blue;
33 color: yellow; font-weight: bold" />
34 </form>
35 </body>
36 </html>
Connecting to a Database

11/1/2024 © Reem Al-Attas 74


Connecting to a Database
⚫Interacting with databases
SQL
⚫Structured Query Language
⚫Used to manipulate databases
Several useful functions
⚫ mysql_connect
⚫ mysql_select_db
⚫ mysql_query
⚫ mysql_error
⚫ mysql_fetch_row
⚫ mysql_close
11/1/2024 © Reem Al-Attas 75
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.19: database.php -->
5 <!-- Program to query a database and -->
6 <!-- send results to the client. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search Results</title>
11 </head>
12
13 <body style = "font-family: arial, sans-serif"
14 style = "background-color: #F0E68C">
15 <?php Build the select query and assign the
16 string to variable $query.
17 extract( $_POST ); Function mysql_connect returns a database
18 handle which represents PHP’s connection to a
19 // build SELECT query database. If this connection is not made, function
20 $query = "SELECT " . $select . " FROM
dieBooks";
is called to terminate script execution.
21
22 // Connect to MySQL
23 if ( !( $database = mysql_connect( "localhost",
24 "httpd", "" ) ) )
25 die( "Could not connect to database" );
26
27 // open Products database
28 Function) mysql_query
if ( !mysql_select_db( "Products", $database ) returns an object
29 die( "Could not open Products containing
database" ); the result set of the query, which
30 we assign to variable $result.
31 // query Products database
32 if ( !( $result = mysql_query( $query, $database ) ) ) {
Function mysql_select_db is called to specify the
33 print( "Could not execute query! <br />" );
database to be queried.
34 die( mysql_error() );
35 }
36 ?>
37
38 <h3 style = "color: blue">
39 Search Results</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 style = "background-color: #ADD8E6">
43
44 <?php The for loop iterates through each
45 record in the result set while
46 // fetch each record in result set constructing an XHTML table from
47 for ( $counter = 0; the results. Variable $counter is
48 $row = mysql_fetch_row( $result incremented
); by one for each row
49 $counter++ ){ retrieved. Function mysql_fetch_row returns an
50 array containing the elements of each
row in the result set of our query
($result).
51 // build table to display results
52 print( "<tr>" );
53
54 foreach ( $row as $key => $value )
55 print( "<td>$value</td>" );
56
57 print( "</tr>" ); The foreach loop iterates through the
58 }
array containing the elements of each row
59
and prints out each element in an
60 mysql_close( $databaseThe
); total number of results are printed to the
individual table cell.
61 ?> client.
62
63 </table>
64
65 <br />Your search yielded <strong>
66 <?php print( "$counter" ) ?> results.<br /><br /></strong>
67
68 <h5>Please email comments to
69 <a href = "mailto:[email protected]">
70 Deitel and Associates, Inc.
71 </a>
72 </h5>
73
74 </body>
75 </html>
Connecting to a Database

11/1/2024 © Reem Al-Attas 79


Cookies
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
11/1/2024
⚫Expiration date © Reem Al-Attas 81
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.20: cookies.html -->
5 <!-- Writing a Cookie -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Writing a cookie to the client computer</title>
10 </head>
11
12 <body style = "font-family: arial, sans-serif;
13 background-color: #99CCFF">
14
15 <h2>Click Write Cookie to save your cookie data.</h2>
16
17 <form method = "post" action = "cookies.php"
18 style = "font-size: 10pt">
19 <strong>Name:</strong><br /> Form data is posted to cookies.php.
20 <input type = "text" name = "NAME" /><br />
21
22 <strong>Height:</strong><br />
23 <input type = "text" name = "HEIGHT" /><br />
24
25 <strong>Favorite Color:</strong><br />
26 <input type = "text" name = "COLOR" /><br />
27
28 <input type = "submit" value = "Write Cookie"
29 style = "background-color: #F0E86C; color: navy;
30 font-weight: bold" /></p>
31 </form>
32 </body>
33 </html>
Cookies

11/1/2024 © Reem Al-Attas 84


1 <?php
2 // Fig. 26.21: cookies.php
3 // Program to write a cookie to a client's machine
4
5 extract( $_POST );
6 // write each form field’s value to a cookie and set the
7 // cookie’s expiration date
8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?> Function setcookie takes the name of the
12 cookie to be set as the first argument,
13 followed by the value to be stored in the
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
14 cookie. The optional third argument specifies
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15 the expiration date of the cookie.
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17 <head>
18 <title>Cookie Saved</title>
19 </head>
20
21 <body style = "font-family: arial, sans-serif">
22 <p>The cookie has been set with the following data:</p>
23
24 <!-- print each form field’s value -->
25 <br /><span style = "color: blue">Name:</span>
Each form field’s value is printed to
26 <?php print( $NAME ) ?><br /> confirm the data that has been set as a
27 cookie with the user.
28 <span style = "color: blue">Height:</span>
29 <?php print( $HEIGHT ) ?><br />
30
31 <span style = "color: blue">Favorite Color:</span>
32
33 <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?>
34 </span><br />
35 <p>Click <a href = "readCookies.php">here</a>
36 to read the saved cookie.</p>
37 </body>
38 </html>
Hyperlink to readCookies.php.
Cookies

11/1/2024 © Reem Al-Attas 87


Cookies

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

11/1/2024 © Reem Al-Attas 88


Cookies

⚫Cookie storage
Internet Explorer
⚫Stores cookies in Cookies directory
⚫Text file

11/1/2024 © Reem Al-Attas 89


Cookies
Cookies directory before a cookie is written.

Cookies directory after a cookie is written.

11/1/2024 © Reem Al-Attas 90


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.24: readCookies.php -->
5 <!-- Program to read cookies from the client's computer -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head><title>Read Cookies</title></head>
9
10 <body style = "font-family: arial, sans-serif">
11
12 <p>
13 <strong>
14 The following data is saved in a cookie on your
15 computer.
16 </strong>
17 </p>
18
19 <table border = "5" cellspacing = "0" cellpadding = "10">
20 <?php
The foreachPHPloop iterates
creates through
array the $_COOKIE
$_COOKIE which contains
21
array and prints the name
all cookie andindexed
values value ofbyeach
theircookie
names.
22 // iterate through array $_COOKIE and print
in an XHTML table.
23 // name and value of each cookie
24 foreach ( $_COOKIE as $key => $value )
25 print( "<tr>
26 <td bgcolor=\"#F0E68C\">$key</td>
27 <td bgcolor=\"#FFA500\">$value</td>
28 </tr>" );
29 ?>
30
31 </table>
32 </body>
33 </html>
Cookies

11/1/2024 © Reem Al-Attas 93


Dynamic Content in PHP
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
11/1/2024 © Reem Al-Attas 95
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.25: dynamicForm.php -->
5 <!-- Form for use with the form.php program -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample form to take user input in XHTML</title>
10 </head>
11
12 <body>
13 <?php
14 extract ( $_POST );
Build array of options for the form.
15 $iserror = false;
16
17 // array of book titles
18 $booklist = array( "Internet and WWW How to Program 3e",
19 "C++ How to Program 4e",
20 "Java How to Program 5e",
21 "XML How to Program 1e" );
22
23 // array of possible operating systems
24 $systemlist = array( "Windows XP",
25 "Windows 2000",
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",
If the page is being loaded as a result of a form
33 "email" => "Email",
submission, do error
Check for errors checking and
or omissions then field
in form retrieve
34 "phone" => "Phone" );
information
input. from the database.
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
47 if ( $email == "" ) {
48 $formerrors[ "emailerror" ] = true;
49 $iserror = true;
50 }
51
52 if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) {
53 $formerrors[ "phoneerror" ] = true;
54 $iserror = true;
55 }
56
If there were no errors, query the MySQL
57 if ( !$iserror ) {
database.
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
66 if ( !( $database = mysql_connect( "localhost",
67 "httpd", "" ) ) )
68 die( "Could not connect to database" );
69
70 // open MailingList database
71 if ( !mysql_select_db( "MailingList", $database ) )
72 die( "Could not open MailingList database" );
73
74 // execute query in MailingList database
75 if ( !( $result = mysql_query( $query, $database ) ) ) {
76 print( "Could not execute query! <br />" );
77 die( mysql_error() );
78 }
79
80 print( "<p>Hi
81 <span style = 'color: blue'>
82 <strong>$fname</strong></span>.
83 Thank you for completing the survey.<br />
84
85 You have been added to the
86 <span style = 'color: blue'>
87 <strong>$book</strong></span>
88 mailing list.
89 </p>
90 <strong>The following information has been saved
91 in our database:</strong><br />
92
93 <table border = '0' cellpadding = '0' cellspacing = '10'>
94 <tr>
95 <td bgcolor = '#ffffaa'>Name</td>
96 <td bgcolor = '#ffffbb'>Email</td>
97 <td bgcolor = '#ffffcc'>Phone</td>
98 <td bgcolor = '#ffffdd'>OS</td>
99 </tr>
100 <tr>
101
102 <!-- print each form field’s value -->
103 <td>$fname $lname</td>
104 <td>$email</td>
105 <td>$phone</td>
106 <td>$os</td>
107 </tr></table>
108
109 <br /><br /><br />
110 <div style = 'font-size: 10pt; text-align: center'>
111 <div style = 'font-size : 18pt'>
112 <a href = 'formDatabase.php'>
113 Click here to view entire database.</a></div>
Halt the script so the form-generation code
114 This is only a sample form.
does not execute.
115 You have not been added to a mailing list.
116 </div></body></html>" );
117 die();
118 }
119 }
120
121 print( "<h1>This is a sample registration form.</h1>
122 Please fill in all fields and click Register." );
123
124 if ( $iserror ) {
125 print( "<br /><span style = 'color : red'>
126 Fields with * need to be filled in properly.</span>" );
127 }
128
129 print( "<!-- post form data to form.php -->
130 <form method = 'post' action = 'dynamicform.php'>
131 <img src = 'images/user.gif' alt = 'User' /><br />
132 <span style = 'color: blue'>
133 Please fill out the fields below.<br />
134 </span>
135
136 <!-- create four text boxes for user input -->" );
Fill in the forms using $$variable syntax.
137 foreach ( $inputlist as $inputname => $inputalt ) {
138 $inputtext = $inputvalues[ $inputname ];
139
140 print( "<img src = 'images/$inputname.gif'
If the form input contained errors, place a red
141 alt = '$inputalt' /><input type = 'text'
asterisk (*) next to the text field.
142 name = '$inputname' value = '" . $$inputname . "' />" );
143
144 if ( $formerrors[ ( $inputname )."error" ] == true )
145 print( "<span style = 'color : red'>*</span>" );
146
147 print( "<br />" );
148 }
149
150 print( "<span style = 'font-size : 10pt" );
151
152 if ( $formerrors[ "phoneerror" ] )
153 print( "; color : red" );
154
155 print( "'>Must be in the form (555)555-5555
156 </span><br /><br />
157
158 <img src = 'images/downloads.gif'
159 alt = 'Publications' /><br />
160
161 <span style = 'color: blue'>
162 Which book would you like information about?
163 </span><br />
164
165 <!-- create drop-down list containing book names -->
166 <select name = 'book'>" );
167
Make sure the correct book is selected in the
168 foreach ( $booklist as $currbook ) {
dropdown box.
169 print( "<option" );
170
171 if ( ( $currbook == $book ) )
172 print( " selected = 'true'" );
173
174 print( ">$currbook</option>" );
175 }
176
177 print( "</select><br /><br />
178 <img src = 'images/os.gif' alt = 'Operating System' />
179 <br /><span style = 'color: blue'>
180 Which operating system are you currently using?
181 <br /></span>
182
183 <!-- create five radio buttons -->" );
184
185 $counter = 0;
186
187 foreach ( $systemlist as $currsystem ) {
188
Make sure the correct OS is checked in the
print( "<input type = 'radio' name = 'os'
189 value =
checkbox.
'$currsystem'" );
190
191 if ( $currsystem == $os ) print( "checked = 'checked'" );
192 if ( $iserror && $counter == 0 ) print( "checked = 'checked'" );
193
194 print( " />$currsystem" );
195
196 if ( $counter == 2 ) print( "<br />" );
197 $counter++;
198 }
199
200 print( "<!-- create a submit button -->
201 <br />
202 <input type = 'submit' name = 'submit' value = 'Register' />
203 </form></body></html>" );
204 ?>
Dynamic Content in PHP

11/1/2024 © Reem Al-Attas 105


Dynamic Content in PHP

11/1/2024 © Reem Al-Attas 106


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.26: formDatabase.php -->
5 <!-- Program to query a database and -->
6 <!-- send results to the client. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search Results</title>
11 </head>
12
13 <body style = "font-family: arial, sans-serif"
14 style = "background-color: #F0E68C">
15 <?php
16 Build the query string.
17 extract( $_POST );
18
19 // build SELECT query
20 $query = "SELECT * FROM contacts";
21
22 // Connect to MySQL
23 if ( !( $database = mysql_connect( "localhost",
24 "httpd", "" ) ) )
25 die( "Could not connect to database" );
26
27 // open MailingList database
28 if ( !mysql_select_db( "MailingList", $database ) )
29 die( "Could not open MailingList database" );
30
31 // query MailingList database
32 if ( !( $result = mysql_query( $query, $database ) ) ) {
33 print( "Could not execute query! <br />" );
34 die( mysql_error() );
35 }
36 ?>
37
38 <h3 style = "color: blue">
39 Mailing List Contacts</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 style = "background-color: #ADD8E6">
43
44 <tr>
45 <td>ID</td>
46 <td>Last Name</td>
47 <td>First Name</td>
48 <td>E-mail Address</td>
49 <td>Phone Number</td>
50 <td>Book</td>
51 <td>Operating System</td>
52 </tr>
53 <?php Retrieve each mailing list
54 member record from the
55 // fetch each record in result database.
set
56 for ( $counter = 0;
57 $row = mysql_fetch_row( $result );
58 $counter++ ){
59 Dynamically create a table
60 // build table to display results
containing each mailing list
61 print( "<tr>" );
member.
62
63 foreach ( $row as $key => $value )
64 print( "<td>$value</td>" );
65
66 print( "</tr>" );
67 }
68
69 mysql_close( $database );
70 ?>
71
72 </table>
73
74 </body>
75 </html>
Dynamic Content in PHP

11/1/2024 © Reem Al-Attas 110


Operator Precedence
Operator Precedence
Operator Type Associativity
new constructor none
[] subscript right to left
~ bitwise not right to left
! not
++ increment
-- decrement
- unary negative
@ error control
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
. concatenation
<< bitwise shift left left to right
>> bitwise shift right
< less than none
> greater than
<= less than or equal
>= greater than or equal
== equal none
!= not equal
=== identical
!== not identical
Fig. 26.27 PHP operator precedence and associativity.
11/1/2024 © Reem Al-Attas 112
Operator Precedence
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 left to right
+= 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
and logical AND left to right
xor exclusive OR left to right
or logical OR left to right
, list left to right
Fig. 26.27 PHP operator precedence and associativity.

11/1/2024 © Reem Al-Attas 113

You might also like