Internet teknologi 2 (ITNET2): PHP Introduction Internet teknologi 2 (ITNET2)
Agenda: Agenda PHP Introduction
PHP Basic Facts
PHP History
PHP Platform
Basic PHP
Variables, Operators, String Processing
Form Processing & Business Logic
Functions
Databases
Cookies
Sessions
Tools
PHP Basic Facts: PHP Basic Facts PHP: Personal Homepage Tools (original)
PHP/FI: Forms Interpreter
PHP: HypertText Preprocessor (today)
PHP is a programming language (~Perl)
Web Server Side Scripting (primary usage)
Command line scripting (administrators)
Client Side GUI (using PHP GTK)
PHP: Interpreted language / weakly typed
As ASP – opposed to ASP.NET/JSP
PHP is Open Source (= free)
Easily Extensible
PHP History: PHP History Rasmus Lerdorf invented PHP
PHP: June 1995
Collection of simple Perl Script Wrappings
PHP/FI: April 1996
C rewrite of PHP + added features, incl. DB support
PHP 3.0: June 1998
Open Source Project, added features, C extension API
PHP 4.0: May 2000
Zend Engine rewrite – much faster
PHP 5.0: July 2004
More advanced OO support
PHP Platform: PHP Platform OS Support:
Linux, FreeBSD, Solaris, Windows, Mac OS X
Embedded Platforms
Web server support
Apache Web server, Microsoft IIS Web server, Netscape/iPlanet
Standard in Linux http://www.securityspace.com/s_survey/data/index.html#free
First.phpProgram Output: 1
3
4
5
6
7
10
11
12
13 A simple PHP document
14
15
16
17
18
19
20
21 Welcome to PHP, !
22
23
24
25 First.php Program Output
Data.php: Data.php 1
3
4
5
6
7
8
9 PHP data types
10
11
12
13
14
21
22
23 is a string.
24 is a double.
25 is an integer.
26
27
28 Now, converting to other types:
29
Data.php: Data.php 34 settype( $testString, "double" );
35 print( " as a double is $testString " );
36 print( "$testString" );
37 settype( $testString, "integer" );
38 print( " as an integer is $testString " );
39 settype( $testString, "string" );
40 print( "Converting back to a string results in
41 $testString " );
42
43 $value = "98.6 degrees";
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 Call function settype to convert the data type of variable $testString to a double. Call function settype to convert the data type of variable $testString to an integer. Convert variable $testString back to a string Use type casting to cast variable $data to different types
Operators.php: Operators.php 1
3
4
5
6
7
8
9 Using arithmetic operators
10
11
12
13 " );
16
17 // define constant VALUE
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 " );
24
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 " );
32
33 // add 40 to variable $a
34 $a += 40;
35 print( "Variable a after adding 40 is $a " );
Operators.php: Operators.php 36
37 // test if variable $a is 50 or less
38 if ( $a " );
40
41 // test if variable $a is between 50 and 100, inclusive
42 elseif ( $a " );
45 else
46 print( "Variable a is now greater than 100
47 " );
48
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 an integer yields $a
62 " );
63 ?>
64
65 Print an uninitialized variable ($nothing).
Arrays.php: Arrays.php 1
3
4
5
6
7
8
9 Array manipulation
10
11
12
13 Creating the first array
17 " );
18 $first[ 0 ] = "zero";
19 $first[ 1 ] = "one";
20 $first[ 2 ] = "two";
21 $first[] = "three";
22
23 // print each element’s index and value
24 for ( $i = 0; $i " );
26
27 print( "Creating the second array
28 " );
29
30 // call function array to create array second
31 $second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i " );
34 Create the array $first by assigning a value to an array element. Assign a value to the array, omitting the index. Appends a new element to the end of the array. Call function array to create an array that contains the arguments passed to it. Store the array in variable $second. Use a for loop to print out each element’s index and value. Function count returns the total number of elements in the array.
Arrays.php: Arrays.php 35 print( "Creating the third array
36 " );
37
38 // assign values to non-numerical indices
39 $third[ "Harvey" ] = 21;
40 $third[ "Paul" ] = 18;
41 $third[ "Tem" ] = 23;
42
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] " );
48
49 print( "Creating the fourth array
50 " );
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", "June" => "sixth",
58 "July" => "seventh", "August" => "eighth",
59 "September" => "ninth", "October" => "tenth",
60 "November" => "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 " );
66 ?>
67
68 Assign values to non-numerical indices in array $third. Function reset sets the internal pointer to the first element of the array. Function next moves the internal pointer to the next element. Operator => is used in function array to assign each element a string index. The value to the left of the operator is the array index, and the value to the right is the element’s value.
Compare.php: Compare.php 1
3
4
5
6
7
8
9 String Comparison
10
11
12
13 0 )
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 ] " ); Use a for loop to iterate through each array element. Function strcmp compares two strings. If the first string alphabetically precedes the second, then –1 is returned. If the strings are equal, 0 is returned. If the first string alphabetically follows the second, then 1 is returned. Use relational operators to compare each array element to string “apple”.
Compare.phpProgram Output: Compare.php Program Output 35 elseif ( $fruits[ $i ] > "apple" )
36 print( "and greater than apple! " );
37 elseif ( $fruits[ $i ] == "apple" )
38 print( "and equal to apple! " );
39
40 }
41 ?>
42
43
Form Handling: Form Handling Form Handling occurs almost the same as in JSP/ASP/ASP.NET
FORM element
INPUT elements (e.g. name )
action = “some.php”
method = “post” || ”get”
Some.php handles the request using
$POST[‘name’] or $GET[‘name’] or $name Not all PHP hosts allows the $name approach
form.html: form.html 1
3
4
5
6
7
8
9 Sample form to take user input in XHTML
10
11
12
13
14 This is a sample registration form.
15 Please fill in all fields and click Register.
16
17
18
19
20
21 Please fill out the fields below.
22
23
24
25
26
27
28
29
30
31
32
33
34
35 The action attribute of the form element indicates that when the user clicks Register, the form data will be posted to form.php.
form.html: form.html 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
48
49
50 Internet and WWW How to Program 2e
51 C++ How to Program 3e
52 Java How to Program 4e
53 XML How to Program 1e
54
55
56
57
58
59 Which operating system are you currently using?
60
61
62
63
65 Windows NT
66
67
69 Windows 2000
70
form.html: form.html 71
73 Windows 98
74
75
76 Linux
77
78
79 Other
80
81
82
83
84
85
86
Form.php: Form.php 1
3
4
5
6
7
8
9 Form Validation
10
11
12
13
14
23 INVALID PHONE NUMBER
24 A valid phone number must be in the form
25 (555)555-5555
26
27 Click the Back button, enter a valid phone
28 number and resubmit.
29 Thank You." );
30
31 die(); // terminate script execution
32 }
33 ?>
34 Function ereg is called to determine whether the phone number entered by the user is valid. The expression \( matches the opening parentheses of a phone number. We access the phone field’s value from form.html by using variable $phone. We should use
$POST[‘phone’] eller $GET[‘phone’] Function die terminates script execution The parentheses in the expression must be followed by three digits ([0-9]{3}), a closing parenthesis, three digits, a literal hyphen and four additional digits.
Form.php: Form.php 35 Hi
36
37
38
39
40 .
41 Thank you for completing the survey.
42
43 You have been added to the
44
45
46
47
48
49 mailing list.
50
51 The following information has been saved
52 in our database:
53
54
55
56 Name
57 Email
58 Phone
59 OS
60
61
62
63 $fname $lname
67 $email
68 $phone
69 $os" );
Form.phpProgram Output: Form.php Program Output 70 ?>
71
72
73
74
75
76 This is only a sample form.
77 You have not been added to a mailing list.
78
79
80
Functions: Functions Used for structure
Weakly typed
no return values
no input parameters
May reside in separate files (.php or .inc)
Scope: normal scoping rules
Example: password protection
Password.html: Password.html 1
3
4
5
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
26
27
28
29
30
33 Form data is posted to password.php.
Password.html: Password.html 34
35
36 Username:
37
38
39
40
41
42
44
45
46
47
48
49 Password:
50
51
52
53
54
55
58
59
60
61
62
63
66
67
68
Password.htmlProgram Output: Password.html Program Output 69 value = "New User"
70 style = "height: 23px" />
71
72
73
74
75
76
Password.php: Password.php 1
3
4
5
6
7
8
9 Error
28 Could not open password file
29 " );
30 die();
31 }
32 Function isset tests whether the user has pressed the New User button, indicating that a new user must be added. To add a new user, we open the file password.txt in append mode and assign the file handle that is returned to variable $file. Print an error message and terminate script execution if the file cannot be opened.
Password.php: Password.php 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
42 if ( !( $file = fopen( "password.txt",
43 "read" ) ) ) {
44 print( "Error
45 Could not open password file
46 " );
47 die();
48 }
49
50 $userVerified = 0;
51
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
66 if ( $USERNAME == $field[ 0 ] ) {
67 $userVerified = 1; Function fputs writes the name and password to the text file.. Function userAdded is called to print a message to the user to indicate that the username and password were added to the file. If variable $NewUser has not been set, we assume that the user has pressed the Enter button, and call function fopen to open the file in read mode. Before entering the while loop, variable $userVerified is set to 0. The while loop executes as long as the there are more lines in the file to read and variable $userVerified is still 0 or empty. Function fgets reads a line from the text file. The result is assigned to variable $line. Function chop removes the newline character from the end of the line. 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 $userVerified is set to 1. Function split is called to separate the string at the specified delimiter (in this case, a comma). The resulting array is stored in array $field.
Password.php: Password.php 68
69 // call function checkPassword to verify
70 // user’s password
71 if ( checkPassword( $PASSWORD, $field )
72 == true )
73 accessGranted( $USERNAME );
74 else
75 wrongPassword();
76 }
77 }
78
79 // close text file
80 fclose( $file );
81
82 // call function accessDenied if username has
83 // not been verified
84 if ( !$userVerified )
85 accessDenied();
86 }
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 Function checkPassword is called to verify the user’s password. Variable $PASSWORD and array $field are passed to the function. If variable $userVerified has not been set to a value other than 0, function accessDenied is called to notify the client that access has been denied. Function checkPassword compares the user’s password to the password in the file. If they match, true is returned, whereas false is returned if they do not.
Password.php: Password.php 97 // print a message indicating the user has been added
98 function userAdded( $name )
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 function accessGranted( $name )
111 {
112 print( "Thank You
113
115 Permission has been
116 granted, $name.
117 Enjoy the site." );
118 }
119
120 // print a message indicating password is invalid
121 function wrongPassword()
122 {
123 print( "Access Denied
124
126 You entered an invalid
127 password.Access has
128 been denied." );
129 }
130 Function userAdded prints a message to the client indicating that the user has been added. Function accessGranted prints a message to the client indicating that permission has been granted. Function wrongPassword prints a message to the client indicating that the password is invalid.
Password.php: Password.php 131 // print a message indicating access has been denied
132 function accessDenied()
133 {
134 print( "Access Denied
135
137
138 You were denied access to this server.
139 " );
140 }
141
142 // print a message indicating that fields
143 // have been left blank
144 function fieldsBlank()
145 {
146 print( "Access Denied
147
149
150 Please fill in all form fields.
151 " );
152 }
153 ?>
154
155 Function accessDenied prints a message to the client indicating that access has been denied. Function fieldsBlank prints a message to the client indicating that all form fields have not been completed.
Password.txt: Password.txt 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 Fig. 29.17 Database password.txt containing usernames and passwords. File-demo
Databases: Databases Many databases supported
Direct DB support
ODBC support
MySQL example of direct support
Works much like JSP/JDBC
Data.html: Data.html 1
3
4
5
6
7
8
9 Sample Database Query
10
11
12
13
14 Querying a MySQL database.
15
16
17
18 Select a field to display:
19
20
21
22
23 *
24 ID
25 Title
26 Category
27 ISBN
28
29
30 Select box containing options for a SELECT query.
Data.htmlProgram Output: Data.html Program Output 31
34
35
36
Database.php: Database.php 1
3
4
5
6
7
8
9
10 Search Results
11
12
13
15 " );
32 die( mysql_error() );
33 }
34 ?>
35 Build the select query and assign the string to variable $query. Function mysql_connect returns a database handle which represents PHP’s connection to a database. If this connection is not made, function die is called to terminate script execution. Function mysql_select_db is called to specify the database to be queried. Function mysql_query returns an object containing the result set of the query, which we assign to variable $result.
Database.php: Database.php 36
37 Search Results
38
39
41
42 " );
51
52 foreach ( $row as $key => $value )
53 print( "$value" );
54
55 print( "" );
56 }
57
58 mysql_close( $database );
59 ?>
60
61
62
63 Your search yielded
64 results.
65
66 Please email comments to
67
68 Deitel and Associates, Inc.
69
70 The for loop iterates through each record in the result set while constructing an XHTML table from the results. Variable $counter is incremented by one for each row retrieved. The foreach loop iterates through the array containing the elements of each row and prints out each element in an individual table cell. The total number of results are printed to the client.
Database.phpProgram Output: Database.php Program Output 71
72
73
dblookup.php: dblookup.php DB-demo Apache Triad also provides MySQL + admin
Cookies.html: Cookies.html 1
3
4
5
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
17
19 Name:
20
21
22 Height:
23
24
25 Favorite Color:
26
27
28
31
32
33
Cookies.php: Cookies.php 1
11
12
14
15
16
17 Cookie Saved
18
19
20
21 The cookie has been set with the following data:
22
23
24 Name:
25
26
27 Height:
28
29
30 Favorite Color:
31 Function setcookie takes the name of the cookie to be set as the first argument, followed by the value to be stored in the cookie. The optional third argument specifies the expiration date of the cookie. Each form field’s value is printed to confirm the data that has been set as a cookie with the user.
Cookies.phpProgram Output: Cookies.php Program Output 32 $COLOR" ) ?>
33
34 Click here
35 to read the saved cookie.
36
37
PHP Sessions: PHP Sessions Provide a way to keep state information
Store values in session variables
Contents of session variables stored on server
Session ID is stored on client
"cryptographically random" number
Stored in URL
or
Stored in cookie
PHP Sessions: PHP Sessions Default for storing session ID is cookie
If cookie won't work, session ID is added to the URL
Can configure PHP to always use URL
Using sessions in PHP: Using sessions in PHP Start a session
Register session variables
Use session variables
Deregister variables and destroy session
Start a session: Start a session session_start();
Checks to see if a session already exists
YES: load registered session variables
NO: creates a session and provides access to $_SESSION superglobal
Call at beginning of all scripts that use sessions
Register session variables: Register session variables $_SESSION['myvar'] = 5;
As of PHP 4.1, can register using $_SESSION
Prior to 4.1, used session_register() function (now deprecated)
Use session variables: Use session variables Access variables by using variable name to index into $_SESSION
$_SESSION['myvar'] = 5;
Unset variables and destroy the session : Unset variables and destroy the session unset($_SESSION['myvar']);
Do not unset the whole $_SESSION array
To unset all session variables at once:
$_SESSION = array();
When finished with a session:
session_destroy();
Include & Require: Include & Require main.php database_functions.inc user_validator.inc messages.inc require – will include an external script (fails if it is not there)
include – will do the same – but NOT fail if it is not there
MyFunctions.inc: MyFunctions.inc \n”;
}
// Print ’bye’.
function PrintBye()
{
print ”Bye, bye\n;
}
// Parameter passed as reference.
function AddHalloRef( &$name )
{
$name = ”Hallo ”.$name;
$name .= ”, nice to see you!”;
}
// Function returns value
function AddHalloReturn( $name )
{
$name = ”Hallo ”.$name;
$name .= ”, nice to see you!”;
return $name;
}
?>
UseInclude.php: UseInclude.php
PHP Setup and Authoring Tools: PHP Setup and Authoring Tools PHP Setup and Authoring Tools
List of installation kits An extensive list of installation kits setting up servers and PHP for you in minutes.
Use ApacheTriad f.i. to avoid manual setup of Apache,, SSL, PHP, MySQL, etc.
PHP Editors List A comprehensive list of editors you can use to edit PHP programs