dr. qusai abuein1 internet & www how to program chap.(26) php (personal home page)

30
Dr. Qusai Abuein 1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Post on 21-Dec-2015

216 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 1

Internet & WWWHow to program

Chap.(26)

PHP (Personal Home Page)

Page 2: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 2

(26.1) Introduction• PHP is platform independent; implementations exist for all

major UNIX, Linux and Windows operating systems.

• PHP also support a large number of databases, including MySQL.

• We study:

– basics of the scripting languages

– viewing environment variables

– form processing and business logic – implementing a private Web site through username and password

verifications

– application that queries a MySQL database

– use cookies to store information

– form-processing

Page 3: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 3

(26.2) PHP• PHP was written specifically for interacting with the Web:

– not only serving content to users, but also responding to requests from users

– generating Web pages with dynamic content • PHP code is embedded directly into XHTML documents. This

allows the document author to write XHTML in a clear, concise manner, without having to use multiple print statements, as is necessary with other CGI-based languages.

• PHP script file names usually end with .php, although a server can be configured to handle other file extensions.

• To run a PHP script, PHP must first installed on your system. • For this chapter’s examples to run correctly, you might need to

copy it to: (C:\Program Files\Apache Group\Apache2\htdocs) for those who are using Apache .

Page 4: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 4

(26.2) PHP• Figure 26.1 presents a simple PHP program that displays a welcome message.• In PHP, code is inserted between the scripting delimiters <?php and ?>. • PHP code can be placed anywhere in XHTML markup, as long as the code is

enclosed in these scripting delimiters. • All variables are preceded by $ and are case sensitive:

– $name != $Name

• PHP statements are terminated with a semicolon ( ; ). • one-line comment (//, #). See line 8.• Multiline comments begin with delimiter /* and end with delimiter */

• Line 21 outputs the value of variable $name by calling function print.

• When a variable is encountered inside a double-quoted (“”) string, PHP interpolates the variable.

• PHP variables are “multitype,” meaning that they can contain different types of data (e.g., integers, doubles or strings) at different times. Figure 26.2 introduces theses data types.

Page 5: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 5

(26.2) PHP• Boolean variables:

– $a = true; // do not use quotes , $b = 1; is evaluated to true

– $c = false; // d = 0; is evaluated to false

Page 6: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 6

(26.2) Converting Between PHP Data Types

• Conversion between different data type may be necessary when performing arithmetic operations with variables. In PHP data-type conversion can be performed by passing the data type as an argument to function settype. See Figure 26.3.

• Function settype tack two arguments:

– the variable whose data is to be changed and

– the variable’s new data type.

• Another option for conversion between types is casting (or type casting). Unlike settype, casting doesn’t change a variable’s content. Rather, type casting creates a temporary copy of a variables value in memory.

• The concatenation operator (.) concatenates strings. Line 47 – 50.

Page 7: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 7

(26.2) Arithmetic operators• Fig.26.4 demonstrates a variety of arithmetic operators in PHP.• Line 18 calls function define to create a named constant. • A constant is a value that cannot be modified once it is declared. • Function define tacks two arguments:

– the name (without $) and – the value of the constant.

• An optional third argument accepts a Boolean value that specifies whether the constant is case insensitive—constants are case sensitive by default.

• In PHP, uninitialized variables have the value undef, which evaluates to different values, depending on its context. For example:– when undef is used in a numeric context (e.g., $num in line 54), it

evaluates to 0. – when undef is interpreted in a string context (e.g., $nothing in line 51), it

evaluates to an empty string (“”). • Strings are converted to integers when they are used in arithmetic

operation (lines 59-60).

Page 8: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 8

(26.2) Arithmetic operators• //Addition: $a + b = 6

• //Subtraction: $a - $b = 2

• //Multiplication: $a * $b = 8

• //Division :$a / $b = 2

• //Modulus (remainder of $a / $b): $a % $b = 0

• //Increment: $a++ (would equal 5 since $a = 4)

• Comparison Operators :– $a == $b test if two values are equal

– $a != $b test if two values are not equal

– $a < $ b test if the first value is less than the second

– $a > $b test if the first value is greater than the second

– $a <= $b test if the first value is less than or equal to the second

– $a >= $b test if the first value is greater than or equal to the second

Page 9: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 9

Switch Statements$a = "100"; switch($a) {

case(10): print ( "The value is 10“) ; break;

case (100): print( "The value is 100<br/>“);break;

case (1000): print( "The value is 1000“); break;

default: print( "<p>Are you sure you entered a number?“); }

Page 10: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 10

While and Do WhileLoopsWhile (condition) { statement(s);

} ----------------$i = 0; do { print $i; } while ($i>0);

Page 11: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 11

(26.2) Initializing and manipulating Arrays• See Fig 26.5 for PHP reserved words (keywords).• Arrays are divided into elements that behave as individual

variables. Array names, like other variables, begin with the $ symbol. See Fig.26.6.

• Individual array elements are accessed by following the array-variable name with an index (starting at 0) enclosed in braces ([]).

• If a value is assigned to an array that doesn’t exist, then the array is created (lines 18,19,20).

• assigning a value to an element where the index is omitted appends a new element to the end of the array (line 21).

• Function count (used in the for loop) returns the total number of elements in the array.

• Line 31 demonstrates a second method of initializing arrays. Function array returns an array that contains the arguments passed to it.

Page 12: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 12

(26.2) Initializing and manipulating Arrays• In addition to integer indices, arrays can have nonnumeric

indices (lines 39-41). • For example, indices ArtTic, LunaTic and GalAnt are

assigned the values 21, 18, 23, respectively. • PHP provides function for iterating through the elements of an

array (lines 45-46). • Each array has a built-in internal pointer, which points to the

array element currently begin referenced. • Function reset sets the internal pointer to the first element of the

array. • Function key returns the index of the element currently

referenced by the internal pointer:– $i = key(third); $third($i);

• Function next moves the internal pointer to the next element.• The for loop continues to execute as long as function key

returns an index. Function next returns false when there are no additional elements in the array.

Page 13: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 13

(26.2) Initializing and manipulating Arrays

• Function array can also be used to initialize arrays with string indices. In order to override the automatic numeric indexing performed by function array, use operator (=>), as demonstrated in lines 54-61.

• The value to the left of the operator is the array index, and the value to the right is the element’s value. An array with string indices also is called an associative array.

• The foreach loop (lines 64-65) is a control statement that is specially designed for iterating through arrays.

• The syntax for a foreach loop:– starts with the array to iterate through, – followed by the keyword as, – followed by the variables to receive the index and the value

for each element.

Page 14: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 14

(26.3) String Processing and Regular Expressions • Text manipulation in PHP is usually done with regular

expressions.

• regular expressions are a series of characters that serve as pattern-matching templates (or search criteria) in strings, text files and databases.

• Comparing Strings:• Line 23 and 25 of Fig.26.7 call function strcmp to compare two

strings:– If the first string alphabetically precedes the second string, then -1 is

returned.

– If the strings are equal, then 0 is returned.

– If the first string alphabetically follows the second string, then 1 is returned

Page 15: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 15

(26.3) String Processing and Regular Expressions

• Relational operators (= =,! =, <, <=, >, >=) can also be used to compare strings. These operators are also used for numerical comparison with integers and doubles.

• Using Regular Expressions • PHP provides function ereg, which uses regular expressions to

search a string for a specified pattern

• Figure 26.8 demonstrates some of PHP’s regular expressions capabilities.

• Line 14 assigns the string “Now is the time” to variable $search • Line 19 calls function ereg to search for the literal characters

“Now” inside variable $search. If(ereg(“Now”, $search))

• If the pattern is found, ereg returns true.

• Function ereg tacks two arguments-a regular expression pattern to search for (Now) and the string to search. And an optional third one as an array to hold the results.

Page 16: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 16

(26.3) String Processing and Regular Expressions• Function ereg is a case sensitive and searches only for the first

occurrence.• PHP provides function eregi for specifying case-insensitive

pattern matches. • In addition to literal characters, regular expressions can include

special characters called (metacharacters ) that specify patterns. For example:

– The caret (^) special character matches the beginning of a string. Line 24

– A dollar sign ($) search for the specified pattern at the end of the string (line 29) – The period (.), which matches any single characters

• If the third argument of preg is mentioned , then the first match of the string is stored in the second element of the array and the second match is stored in the third element and so on. The first element (index 0) contains the whole matched string. Line 34.

Page 17: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 17

(26.3) String Processing and Regular Expressions

• Searching for multiple instances of a pattern in a string is slightly more complicated, because the ereg function matches only the first instance of the pattern.

• To find multiple instances of a given pattern, we must remove any matched instances before calling ereg again.

• Lines 42-49 use a while loop and the ereg_replace function to find all the words in the string that begins with t.

• Function ereg_replace tacks three arguments:– the pattern to match,

– a string to replace the matched string and

– the string to search.

• The modified string is returned , so line 48 uses $search to store the returned string allowing us to search for another match. The new $search string now does not contain the first matched string.

Page 18: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 18

(26.4) Viewing Client/Server Environment Variables

• Environment variables contain information about a script’s environment, such as the client’s Web browser, the HTTP host and the HTTP connection.

• Figure 26.11 lists some global arrays. • Figure 26.12 generates an XHTML document that displays the

values of the client’s environment variables in the table. • PHP stores the environment variables and there values in the

$_ENV array. Iterating through this array allows us to view all the client’s environment variables.

• In lines 19-22, we use a foreach loop to print out the $key and $value of each element in the $_ENV array.

Page 19: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 19

User-Defined Functions

function check_age($age) { if ($age > 21) {

return 1; } else { return 0; } } //usage: if(check_age($age)) { print ("You may enter!“); } else { print( "Access Not Allowed!“); exit; }

Page 20: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 20

(26.5) Form Processing and Business Logic

• XHTML form enables Web pages to collect data from users and send it to a Web server for processing. Interaction of these kinds between users and Web servers is vital to e-commerce applications.

• Figure 26.13 uses an XHTML form to collect information about users for the purpose of adding them to a mailing list.

• The action attribute of the form element (line 18) indicates that when the user clicks the Register (Submit) button, the form data will be posted to form.php (Fig. 26.14) for processing.

• Using method = “post” appends form data to the browser request that contains the protocol (i.e., HTTP) and the requested recourse’s URL.

• Scripts located on the web server’s machine can access the form data sent as part of the request.

Page 21: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 21

(26.5) Form Processing and Business Logic• We assign a unique name (e.g., email) to each of the form’s

input fields. • When Register is clicked, each fields name and value is sent to

the Web server. • Script form.php can then access the value for each specific

field through the superglobal array $_POST. • Superglobal arrays are associative arrays predefined by PHP

that hold variables acquired from the user input, the environment or the Web server and are accessible in variable scope. The $_ENV array used in Fig. 26.12 is another example of superglobal array.

• $_POST contains key-value pairs corresponding to name-value pairs for variables submitted through the form. [Note: The superglobal array $_GET would contain these key-value pairs if the form had been submitted using the HTTP get method].

• Figure 26.14 (form.php) processes the data posted by form.html and sends XHTML back to the client.

Page 22: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 22

(26.5) Form Processing and Business Logic• Function extract (associativeArray) (line 15) creates a variable-value

pair corresponding to each key-value pair in the associativeArray (i.e., $_POST), creating variables whose respective names and values corresponding to the names and variables of each posted form field.

• For example, in line 32 of Fig. 26.13, an XHTML text box is created and given the name email.

• In line 68 of our PHP script (Fig. 26.14), after having called function extract, we access the field’s value by using variable $email.

• Elements in the superglobal array $_POST also can be accessed using standard array notation. For example, we could have accessed the form field email’s value by referring to $_POST[‘email’].

• See portability tip 26.1 page 921.• $_POST[‘email’] is more secure than $email.• Function die() (line 32) terminates script execution. In this case, if

the user did not enter a correct value, we do not want to continue executing the rest of the script, so we call function die().

• See Error_Prevention Tip 26.3 page 922.

Page 23: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 23

(26.6) Verifying a Username and Password• Figure 26.15 presents an XHTML form that queries the user for a username

and password. • Fields USERNAME and PASSWORD are posted to the PHP script

password.php for verification.• Script password.php (Fig. 26.16) verifies the client’s username and

password by querying a database. • The valid user list and each user’s respective password are contained in a

simple text file named password.txt (Fig. 26.17).• Existing users are validated against this text file, and new users are appended

to it.• Fig. 26.16: First, lines 13-16 check whether the user has submitted

a form without specifying a username or password. • Variable names, when preceded by the logical negation

operator (!), return true if they are empty or are set to 0. • Logical operator OR (||) returns true if either of the operands

returns true (i.e., if either of the variables is empty or is set to 0).• If this is the case, function fieldsblank (lines 144-152) is called,

which notifies the client that all form fields must be completed.

Page 24: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 24

(26.6) Verifying a Username and Password

• We determine whether we are adding anew user (line 19 in Fig. 26.16) by calling function isset to test whether variable $NewUser has been set.

• When submitting the XHTML form in password.html, the user clicks either the New User or Enter button.

• After calling function extract, either variable $NewUser or variable $Enter is created, depending on which button the user clicked.

• If variable $NewUser has been set, lines 22-36 execute. • If this variable has not been set, we assume that the user has

pressed the Enter button, and lines 42-75 execute.

Page 25: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 25

(26.6) Verifying a Username and Password• To add a new user, we open the file password.txt by calling function fopen

and assigning the file handle that is returned to variable $file (lines 22-23). • A file handle is a number assigned to the file by the Web server for purpose

of identification. • Function fopen tacks two arguments-the name of the file and the mod in

which to open it. • The possible modes include:

– r (read), – w (write) and – a (append).

• If an error occurs in opening the file, function fopen dose not return a file handle, an error message is presented (lines 27-29) and script execution is terminated by calling function die (line 30).

• If the file opens probably, function fputs (line 35) writes the name and password to the file.

• To specify a new line, we use the newline character (\n). This places each username and password pair on a separate line in the file.

• In line 36, we pass the variable $USERNAME to function userAded (lines 98-106). Function userAded prints a message to the client to indicate that the username and password were added to the file.

Page 26: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 26

(26.6) Verifying a Username and Password• The test condition (line 54) checks to ensure that the end of the file has not

been reached and that the user has not been found in the password file. • Function feof($file) determines whether we have reached the end of the

specified file ($file).• Each line in password.txt consists of a username and password pair that is

separated by a comma and followed by a newline character. • A line from this file is read using function fgets (line 57) and is assigned to

variable $line. • Function fgets tacks two arguments:

– the file handle to read, and – the maximum number of characters to read.

• The function fgets reads until: – a newline character is encountered, – the end of the file is encountered or – the number of character read reach one less than the number specified in the

second argument.

Page 27: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 27

(26.6) Verifying a Username and Password

• For each line read, function chop is called (line 60) to remove the new line character from the end of the line.

• The function split is called to divide the string into substrings at the specified separator, or delimiter (in this case, a comma).

• For example, function split returns an array containing (“account1” and “assword1”) from the first line in password.txt. This array is assigned to variable $field.

• Function fclose ($file) (line 80) closes the file specified in $file.

Page 28: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 28

(26.7) Connecting to a Database

Page 29: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 29

Summery

Page 30: Dr. Qusai Abuein1 Internet & WWW How to program Chap.(26) PHP (Personal Home Page)

Dr. Qusai Abuein 30

End of Chap. (26)

Thank you .