1© Copyright 2006-2007 Haim Levkowitz
PHP = Personal Home Page
• Or PHP: Hypertext Preprocessor
2© Copyright 2006-2007 Haim Levkowitz
Origins and Uses
• Origins• Rasmus Lerdorf - 1994• Developed to track visitors to his Web
site• open-source product• PHP = Personal Home Page• Or PHP: Hypertext Preprocessor
• Used for form handling, file processing,database access
3© Copyright 2006-2007 Haim Levkowitz
PHP Overview
• Server-side scripting language• scripts embedded in HTML documents• Similar to JavaScript, but on server side
• Alternative to CGI, ASP.NET, JSP, Allaire’sColdFusion
• PHP processor has two modes:• copy (XHTML)• interpret (PHP)
4© Copyright 2006-2007 Haim Levkowitz
PHP Overview (cont.)
• Syntax similar to JavaScript
• Dynamically typed
• Purely interpreted
5© Copyright 2006-2007 Haim Levkowitz
General SyntacticCharacteristics• PHP code can be specified in XHTML document
• internally or externally:• Internally:
• <?php• ...• ?>
• Externally: include ("myScript.inc")• file can have both PHP and XHTML• If file has PHP, must be in
• <?php .. ?>• even if include already in <?php .. ?>
• Every variable name begin with $
6© Copyright 2006-2007 Haim Levkowitz
General SyntacticCharacteristics (cont.)
• Comments• three different kinds (Java and Perl)• // ...• # ...• /* ... */
• Compound statements• formed with braces• cannot be blocks
7© Copyright 2006-2007 Haim Levkowitz
Primitives, Operations,Expressions
• Variables• no type declarations• unassigned (unbound) variable has valueNULL• unset function sets variable to NULL• IsSet function used to determine
whether variable is NULL
8© Copyright 2006-2007 Haim Levkowitz
Primitives, Operations,Expressions (cont.)
• error_reporting(15);• prevents PHP from using unbound
variables• many predefined variables,• including environment variables of host
OS• can get list of predefined variables by
calling phpinfo() in script
9© Copyright 2006-2007 Haim Levkowitz
Eight primitive types
• Four scalar types• Boolean, integer, double, and string
• Two compound types• array and object
• Two special types:• resource and NULL
• Integer & double• like those of other languages
• Strings• Characters are single bytes• String literals use single or double quotes
10© Copyright 2006-2007 Haim Levkowitz
Primitives, Operations,Expressions (cont.)
• Single-quoted string literals• (as in Perl)• Embedded variables NOT
interpolated• Embedded escape sequences NOT
recognized
11© Copyright 2006-2007 Haim Levkowitz
• Double-quoted string literals (as in Perl)• Embedded variables ARE interpolated• If there is variable name in double-quoted string
• but don’t want it interpolated,• must be backslashed
• Embedded escape sequences ARE recognized• For both single- and double-quoted literal strings,
embedded delimiters must be backslashed• Boolean-values are true and false (case insensitive)
• 0 and "" and "0" are false• others are true
12© Copyright 2006-2007 Haim Levkowitz
Primitives, Operations,Expressions (cont.)• Arithmetic Operators and Expressions• Usual operators
• If result of integer division not integer• double returned
• Any integer operation that results in overflow• produces double
• Modulus operator coerces its operands tointeger, if necessary
• When double is rounded to integer• rounding always towards zero
13© Copyright 2006-2007 Haim Levkowitz
Arithmetic functions
• floor• ceil• round• abs• min• max• rand• etc.
14© Copyright 2006-2007 Haim Levkowitz
String Operations andFunctions
• only operator• period• concatenation
• Indexing• $str{3}= fourth character
15© Copyright 2006-2007 Haim Levkowitz
String Operations andFunctions (cont.)• Functions:
• strlen, strcmp, strpos, substr• as in C
• chop• remove whitespace from right end
• trim• remove whitespace from both ends
• ltrim• remove whitespace from left end
• strtolower, strtoupper
16© Copyright 2006-2007 Haim Levkowitz
Scalar type conversions:String to numeric
• If string• contains e or E• converted to double
• otherwise• to integer
• does not begin with sign or digit• zero is used
17© Copyright 2006-2007 Haim Levkowitz
Scalar type conversions(cont.)
• Explicit conversions – casts• e.g.,• (int)$total• or• settype($total, "integer")
18© Copyright 2006-2007 Haim Levkowitz
Determine type ofvariable
• gettype or is_type• gettype($total)• may return "unknown"
• is_integer($total)• predicate function
19© Copyright 2006-2007 Haim Levkowitz
Output
• HTML
• Sent to browser
• Through standard output
20© Copyright 2006-2007 Haim Levkowitz
Three ways to produceoutput
• echo, print, printf• echo and print
• take string• but will coerce other values to strings
• echo "whatever"; # Only one parameter• echo("first <br />", $sum) # More thanone
• print "Welcome to my site!"; # Only one
21© Copyright 2006-2007 Haim Levkowitz
PHP code place in body ofXHTML doc• <html>
• <head>• <title> Trivial php example </title>• </head>• <body>• <?php• print "Welcome to my Web site!";• ?>• </body>
• </html>• -> SHOW today.php and display
22© Copyright 2006-2007 Haim Levkowitz
Control statements
• Control Expressions• Relational operators• same as JavaScript• including === and !==
• Boolean operators• same as Perl• two sets, && and and, etc.
23© Copyright 2006-2007 Haim Levkowitz
Selection statements
• if, if-else, elseif• switch
• as in C• switch expression type must be integer,
double, or string• while, do-while, for
• just like C• foreach
• later
24© Copyright 2006-2007 Haim Levkowitz
Control statements(cont.)• break
• in any for, foreach, while, do-while, or switch• continue
• in any loop• Alternative compound delimiters
• more readability• if(...):
• ...• endif;
• SHOW powers.php
25© Copyright 2006-2007 Haim Levkowitz
Can intermingle HTML, PHP
<?php $a = 7; $b = 7; if ($a == $b) { $a = 3 * $a; ?> <br /> At this point, $a and $b are equal <br /> So, we change $a to three times $a <?php }
?>
26© Copyright 2006-2007 Haim Levkowitz
Arrays
• Not like arrays of other programming language• generalization• mapping of keys to values• keys can be
• numbers• traditional array
• strings• hash (“associative array”)
27© Copyright 2006-2007 Haim Levkowitz
Array creation
• Use array() construct• takes one or more key => value pairs as parameters• returns array of them• keys
• non-negative integer literals, or• string literals
• values can be anything• e.g.,
• $list = array(0 => "apples", 1 =>"oranges", 2 => "grapes")
• “regular” array of strings
28© Copyright 2006-2007 Haim Levkowitz
Arrays (cont.)
• If key is omitted, and• there have been integer keys• default key will be largest current key + 1
• there have been no integer keys• 0 is default key
• If key appears that has already appeared• new value will overwrite old one
29© Copyright 2006-2007 Haim Levkowitz
Arrays can have mixedkinds of elements• e.g.,• $list = array("make" => "Cessna",• "model" => "C210",• "year" => 1960,• 3 => "sold");
• $list = array(1, 3, 5, 7, 9);
• $list = array(5, 3 => 7, 5 => 10,• "month" => "May");
• $colors = array('red', 'blue', 'green',• 'yellow');
30© Copyright 2006-2007 Haim Levkowitz
Accessing array elements –use brackets• $list[4] = 7;• $list["day"] = "Tuesday";• $list[] = 17;• If element with specified key does not exist
• element is created• If array does not exist
• array is created
31© Copyright 2006-2007 Haim Levkowitz
Extract keys, values fromarray
• $highs = array("Mon" => 74,"Tue" => 70,"Wed" => 67,"Thu" => 62,"Fri" => 65);
• $days = array_keys($highs);• $temps = array_values($highs);
32© Copyright 2006-2007 Haim Levkowitz
Dealing with Arrays
• Array can be deleted with unset• unset($list);• unset($list[4]); # No index4 element now
33© Copyright 2006-2007 Haim Levkowitz
• is_array($list)• returns true if $list is array
• in_array(17, $list)• returns true if 17 is an element of $list
• explode(" ", $str)• creates array with values of words from $str• split on space
• implode(" ", $list)• creates string of elements from $list• separated by space
34© Copyright 2006-2007 Haim Levkowitz
Sequential access to arrayelements
• current and next• $colors = array("Blue", "red", "green",• "yellow");• $color = current($colors);• print("$color <br />");• while ($color = next($colors))• print ("$color <br />");
35© Copyright 2006-2007 Haim Levkowitz
• This does not always work• E.g, when value in array = FALSE
• Alternative: each, instead of next• while ($element = each($colors)) { print ("$element['value'] <br />");
• prev function• moves current backwards
• array_push($list, $element) and• array_pop($list)
36© Copyright 2006-2007 Haim Levkowitz
Implement stacks witharrays
• foreach (array_name as scalar_name) { ... }
• foreach ($colors as $color) {• print• "Is $color your favorite color?<br />";• }
• Is red your favorite color?• Is blue your favorite color?• Is green your favorite color?• Is yellow your favorite color?
37© Copyright 2006-2007 Haim Levkowitz
• foreach can iterate through both keys andvalues:
• foreach ($colors as $key => $color) { … }• Inside compound statement
• both $key and $color are defined• $ages = array("Bob" => 42, "Mary" => 43);• foreach ($ages as $name => $age)• print("$name is $age years old <br/>");
38© Copyright 2006-2007 Haim Levkowitz
sort
• sort values of array• leave keys in their present order• intended for traditional arrays• e.g.,• sort($list);
• sort function does not return anything• Works for both strings and numbers• even mixed strings and numbers
39© Copyright 2006-2007 Haim Levkowitz
• $list = ('h', 100, 'c', 20, 'a');• sort($list);• // Produces ('a', 'c', 'h‘, 20, 100)
• In PHP 4, sort function can take second parameter• specifies particular kind of sort• sort($list, SORT_NUMERIC);
• asort• sort values of array• but keep key/value relationships
• intended for hashes
40© Copyright 2006-2007 Haim Levkowitz
• rsort
• sort values of array into reverse order• ksort
• sort elements of array by keys
• maintain key/value relationships
• e.g., …
41© Copyright 2006-2007 Haim Levkowitz
• $list("Fred" => 17, "Mary" => 21,• "Bob" => 49, "Jill" => 28);• ksort($list);• // $list is now ("Bob" => 49,• // "Fred" => 17, "Jill" => 28, "Mary" => 21)• krsort
• sort elements of array by keys into reverse order• SHOW sorting.php
42© Copyright 2006-2007 Haim Levkowitz
User-Defined Functions
• Syntactic form:• function
function_name(formal_parameters){
…}
43© Copyright 2006-2007 Haim Levkowitz
General Characteristics
• Functions need not be defined beforethey are called
• (in PHP 3, they must)• Function overloading not supported
• If try to redefine function
• error
44© Copyright 2006-2007 Haim Levkowitz
• Functions can have variable number ofparameters
• Default parameter values supported• Function definitions can be nested• Function names NOT case sensitive• return function used to return value• If there is no return• no returned value
45© Copyright 2006-2007 Haim Levkowitz
Parameters
• If caller sends too many actual parameters• subprogram ignores extra ones
• If caller does not send enough parameters• unmatched formal parameters
unbound• default parameter passing method• pass by value• (one-way communication)
46© Copyright 2006-2007 Haim Levkowitz
To specify pass-by-reference
• prepend ampersand to formalparameter
• function addOne(&$param) {$param++;
}
$it = 16;addOne($it); // $it is now 17
47© Copyright 2006-2007 Haim Levkowitz
If function does not specifyparameter to be pass byreference• can prepend ampersand to actual parameter
and still get pass-by-reference semantics
• function subOne($param) { $param--; }$it = 16;subOne(&$it); // $it is now 15
48© Copyright 2006-2007 Haim Levkowitz
Return Values
• Any type may be returned• including objects and arrays• using return
• If function returns reference• name of function must have prepended
ampersand
• function &newArray($x) { … }
49© Copyright 2006-2007 Haim Levkowitz
Scope of Variables
• undeclared variable in function
• has scope of function
• To access a nonlocal variable• it must be declared to be global’
• as in• global $sum;
50© Copyright 2006-2007 Haim Levkowitz
Lifetime of Variables
• Normally
• from first appearance
• to end of function’s execution• static $sum = 0; # $sum isstatic
51© Copyright 2006-2007 Haim Levkowitz
Pattern Matching
• two kinds:
• POSIX
• Perl-compatible• preg_match(regex, str [,array])• optional array
• where to put matches
52© Copyright 2006-2007 Haim Levkowitz
Form Handling
• Simpler with PHP than
• CGI or servlets
• Forms could be handled by samedocument that creates the form
• but that may be confusing
53© Copyright 2006-2007 Haim Levkowitz
PHP particulars:
• It does not matter whether GET or POST methodused to transmit form data
• PHP builds array of the form values• $_GET for GET method and• $_POST for POST method• subscripts are widget names
• SHOW popcorn3.html• SHOW popcorn3.php
54© Copyright 2006-2007 Haim Levkowitz
Files
• PHP can:• Deal with any files on• server• Internet
• using either• http or ftp
• Instead of filehandles• PHP associates variable with file• called file variable
• (for program reference)
55© Copyright 2006-2007 Haim Levkowitz
• file has file pointer (where to read or write)• $fptr = fopen(filename, use_indicator)
• Use indicators:• r read only, from beginning• r+ read and write, from beginning• w write only, from beginning• (also creates file, if necessary)• w+ read and write, from beginning• (also creates file, if necessary)• a write only, at end, if exists• (creates file, if necessary)• a+ read and write, read at beginning, write• at end
• Because fopen could fail, use with die• Use file_exists(filename) to determine whether file exists
before trying to open it• Use fclose(file_var) to close file
56© Copyright 2006-2007 Haim Levkowitz
Reading files
• 1. Read all or part of file into stringvariable
• $str = fread(file_var, #bytes)• To read whole file, use• filesize(file_name)• as second parameter
57© Copyright 2006-2007 Haim Levkowitz
Reading files
• 2. Read lines of file into array• @file_lines = file(file_name)• Need not open or close file
58© Copyright 2006-2007 Haim Levkowitz
Reading files
• 3. Read one line from file• $line = fgets(file_var, #bytes)• Reads characters until• eoln• eof• Or #bytes characters have been
read
59© Copyright 2006-2007 Haim Levkowitz
Reading files
• 4. Read one character at a time• $ch = fgetc(file_var)• Control reading lines or characters with
eof detection using feof• TRUE for eof; FALSE otherwise
• while(!feof($file_var)) {$ch = fgetc($file_var);
}
60© Copyright 2006-2007 Haim Levkowitz
Writing to files
• $bytes_written = fwrite(file_var,string)
• fwrite returns number of bytes it wrote• Files can be locked• avoid interference from concurrent
accesses• with flock• just like Perl
61© Copyright 2006-2007 Haim Levkowitz
Cookies
• Create cookie with setcookie• setcookie(cookie_name,
cookie_value, lifetime)
• e.g.,
62© Copyright 2006-2007 Haim Levkowitz
e.g.,
• setcookie("voted", "true", time() +86400);
• Cookies• must be created before any other
HTML created by script• obtained in script same way form
values gotten• using the $_COOKIES array
63© Copyright 2006-2007 Haim Levkowitz
Session tracking
• PHP creates and maintains session tracking id• Create id with call to
• session_start• with no parameters
• Subsequent calls to session_start• retrieve any session variables• previously registered in session
64© Copyright 2006-2007 Haim Levkowitz
To create session variable
• Use session_register
• only parameter is string literal ofname of session variable• without dollar sign