7-Server-side web development with
PHP
Origins and Uses of PHP
Origins
Rasmus Lerdorf - 1994
Developed to allow him to track visitors to his Web
site
PHP was originally an acronym for Personal
HomePage, but later it became PHP: Hypertext
Preprocessor
PHP is used for form handling, file processing,
and database access
2
Overview of PHP
PHP is a server-side scripting language whose scripts are embedded in HTML
documents
PHP is an alternative to ASP.NET and JSP
The PHP processor has two modes:
copy (HTML)
interpret (PHP)
When the PHP processor finds markup code (which may include embedded client-side script) in
the input file, it simply copies it to the output file
When the processor encounters PHP script in the input file, it interprets it and sends any output
of the script to the output file.
This implies that the output from a PHP script must be HTML or XHTML, either of which could
include embedded client-side script.
PHP syntax is similar to that of JavaScript
PHP is dynamically typed
PHP is purely interpreted
General
Syntactic
PHP code can be specified in an HTML document internally or
externally:
Characteristics
Internally:
<?php
...
?>
Externally: include ("myScript.inc")
the file can have both PHP and HTML
If the file has PHP, the PHP must be in
<?php .. ?>, even if the include is already in
<?php .. ?>
Every variable name begin with a $
General Syntactic
Characteristics
Comments - three different kinds (Java and C)
// ...
# ...
/* ... */
Compound statements are formed with braces
Compound statements cannot be blocks
Unless used as the body of a function definition, a
compound statement cannot be a block. (It cannot
define locally scoped variables.)
5
The reserved words of PHP
Primitives, Operations, and
Variables
Expressions
There are no type declarations
An unassigned (unbound) variable has the
value, NULL
The unset function sets a variable to NULL
The IsSet function is used to determine whether a
variable is NULL
For example, IsSet($fruit) returns TRUE if $fruit
currently has a non-NULL value, FALSE otherwise.
7
Primitives, Operations, and
Expressions
If you want to be informed when an unbound variable
is referenced, include a call to the
error_reporting(15) function to change the error
reporting level of the PHP interpreter to 15
The default error reporting level is 7, which does not require
the interpreter to report the use of an unbound variable.
PHP has many predefined variables, including the
environment variables of the host operating system
You can get a list of the predefined variables by calling
phpinfo() in a script
Primitives, Operations, and
There are eight primitive types:
Expressions
Four scalar types: Boolean, integer, double, and string
Two compound types: array and object
Two special types: resource and NULL
Integer & double are like those of other languages
Strings
Characters are single bytes, UNICODE is not supported.
String literals use single or double quotes
Strings
Single-quoted string literals
Embedded variables are NOT interpolated
i.e. are not substituted for their Values
Embedded escape sequences are NOT recognized
For example, the value of
The sum is: $sum
is exactly as it is typed.
However, if the current value of $sum is 10.2, then the value of
The sum is: $sum
is
The sum is: 10.2
10
Strings
Double-quoted string literals
Embedded variables ARE interpolated
If there is a variable name in a double-quoted
string but you dont want it interpolated, it must be
backslashed
Embedded escape sequences ARE recognized
For both single- and double-quoted literal
strings, embedded delimiters must be
backslashed
11
Boolean
Boolean - values are true and false (case
insensitive)
If an integer expression is used in a Boolean context, it
evaluates to FALSE if it is zero; otherwise, it is TRUE.
If a string expression is used in a Boolean context, it
evaluates to FALSE if it is either the empty string or
the string 0; otherwise, it is TRUE.
This implies that the string 0.0evaluates to TRUE
i.e. - 0 and "" and "0" are false; others are true
12
Arithmetic Operators and
Usual
operators (+, -, *, /, %, ++, and --)
Expressions
if both operands are integers, the operation is integer and an
integer result is produced.
If either operand is a double, the operation is double and a double
result is produced
If the result of integer division is not an integer, a double is
returned
Any integer operation that results in overflow produces a double
The modulus operator (%) coerces its operands to integer, if
necessary
When a double is rounded to an integer, the rounding is always
towards zero
13
Arithmetic functions
14
String Operations and
The only operator is period (.), for catenation
Functions
Indexing - $str{3} is the fourth character
strlen, strcmp, strpos, substr, as in C
chop remove whitespace from the right end
trim remove whitespace from both ends
ltrim remove whitespace from the left end
strtolower, strtoupper
$str = Apples are good;$sub = substr($str, 7, 1);
The value of $sub is now a.
15
String Operations and Functions
16
Scalar Type Conversions
Implicit (coercions)
String to numeric and vice versa
There are also frequent coercions between
numeric and string types.
Whenever a numeric value appears in a string
context, the numeric value is coerced to a string
Likewise, whenever a string value appears in a numeric
context, the string value is coerced to a numeric value
If the string contains an e or an E, it is converted
to double; otherwise to integer
If the string does not begin with a sign or a digit,
the conversion fails and zero is used.
When a double is converted to an integer, the
fractionalpart is dropped; rounding is not done.
17
Explicit conversions
1.
2.
1.
Casting:three different ways
One can cast an expression to a different type. The
cast is a type name in parentheses preceding the
expression
e.g., (int)$total
Another way to specify explicit type conversion is
to use one of the functions intval, doubleval,
or strval
intval($total)
The third way to specify an explicit type conversion
is with the settype function, which takes two
parameters: a variable and a string that specifies a
type name
18
settype($total, "integer")
1.
2.
Variable type
two different
ways
determination
Using gettype function
which takes a variable as its parameter and returns a string that
has the name of the type of the current value of the variable
gettype($total) - it may return "unknown"
use one or more of the type testing functions, each of which takes a
variable name as a parameter and returns a Boolean value
These functions are is_int, is_integer, and is_long, which
test for integer type; is_double, is_float, and is_real, which
test for double type; is_bool, which tests for Boolean type; and
is_string, which tests for string type.
is_integer($total) a predicate function
19
Assignment Operators
PHP has the same set of assignment
operators as its predecessor language,
C, including the compound assignment
operators such as += and /=.
20
Output
Output from a PHP script is HTML that is sent to the
browser
HTML is sent to the browser through standard output
There are two ways to produce output: print and printf
print takes a string, but will coerce other values to
strings
print "This is too <br /> much fun <br />";
print 72;
printf is exactly as in C and is for formatted output
printf(literal_string, param1, param2, )
21
Output
PHP code is placed in the body of an HTML document
<html>
<head><title> Trivial php example </title>
</head>
<body>
<?php
print "<b>Welcome to my home page <br /> <br />";
print "Today is:</b> ";
print date("l, F jS");
print "<br />";
?>
</body>
</html>
22
Date function
Note that the date information is generated
with the date function, whose first parameter
is a string that specifies the parts of the date
you want to see.
In this example, l requests the day of the
week, F requests the month, j requests the
day of the month, and an S next to the j gets
the correct suffix for the day (e. g., st or nd)
SHOW today.php and display
23
Control Statements
Control Expressions
The usual six (>, <, >=,<=, !=, and ==) have
the usual meanings.
PHP also has ===, which produces TRUE only
if both operands are the same type and have
the same value, and !==, the opposite of ===.
If the types of the operands of the other six
relational operators are not the same, one is
coerced to the type of the other
24
Boolean operators
same as C
There are six Boolean operators: and,
or, xor, !, &&, and ||.
The and and && operators perform the
same operation, as do or and ||.
The difference between them is that the
precedence of and and or is lower than
that of && and ||.
25
Selection statements
if statement
PHPs if statement is like that of C
if, if-else, elseif
26
The switch statement
as in C
The switch expression type must be
integer, double, or string
27
Loop Statements
while - just like C
foreach - discussed later
The following example computes the
factorial of $n:
28
do-while Statement
do-while - just like C
This example computes the sum of the
positive integers up to 100:
29
For Statement
for - just like C
The following example computes the
factorial of $n:
30
The break statement
The break statement can be used to
terminate the execution of a for, for
each, while, or do while construct.
The continue statement is used in loop
constructs to skip the remainder of the
current iteration but continue execution
at the beginning of the next.
31
Example
illustrates the form of an XHTML/PHP
document, as well as some simple
mathematical functions and the
intermingling of XHTML and PHP in a
document.
The sqrt function returns the square root
of its parameter;
the pow function raises its first parameter
to the power of its second parameter
SHOW powers.php
32
Example
HTML can be intermingled with PHP script
<?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
}
?>
33
Arrays
Not like the arrays of any other programming
language
A PHP array is a generalization of the arrays of other
languages
a combination of the arrays of a typical language an
associative arrays, or hashes, found in some other
languages, such as Ruby and Python
A PHP array is really a mapping of keys to values,
where the keys can be numbers (to get a traditional
array) or strings (to get a hash)
34
Array creation
There are two ways to create an array in PHP
1. Assigning a value to a subscripted variable that previously was not an array
creates the array
if no array named $listcurrently exists, the following statement creates one:
$list[0] = 17;
If empty brackets are used in an assignment to an array, a numeric
subscript is implicitly furnished
The furnished subscript is 1 greater than the largest used so far in the
array if the array already has elements with numeric keys
$list[1] = Today is my birthday!;$list[] = 42;
the second elements subscript will be 2
demonstrates that the elements of an array need not be of the same
type.
35
Array creation
2.
The second way to create an array is with the array construct.
$list = array(17, 24, 45, 91);
The parameters of array specify the values to be placed in a
new array and sometimes also the keys.
If the array is like a traditional array, only the values need to be
specified; the PHP interpreter will furnish the numeric keys.
Above statement creates a traditional array of four elements,
with the keys 0, 1, 2, and 3
If you would rather have different keys, you can specify them in
the array construct, as follows:
$list = array(1 => 17, 2 => 24, 3 => 42, 4 => 91);
36
Array creation
String Keyed Array
$ages[Mary] = 29;
the value of the element whose key is Mary in the
$ages array can be set to 29
The list construct
The list construct can be used to assign multiple
elements of an array to scalar variables in one statement
37
Accessing array elements
Use brackets
$list[4] = 7;
$list["day"] = "Tuesday";
$list[] = 17;
If an element with the specified key does
not exist, it is created
If the array does not exist, the array is
created
38
Functions for Dealing with Arrays
The keys or values can be extracted from an array
$highs = array("Mon" => 74, "Tue" => 70,
"Wed" => 67, "Thu" => 62,
"Fri" => 65);
$days = array_keys($highs);
$temps = array_values($highs);
Testing whether an element exists
if (array_key_exists("Wed", $highs))
An array can be deleted with unset
unset($list);
unset($list[4]);
# Deletes index 4 element
39
Functions for Dealing with Arrays
is_array($list) returns true if $list is an array
in_array(17, $list) returns true if 17 is an element of
$list
sizeof(an_array) returns the number of elements
explode(" ", $str) creates an array with the values of the
words from $str, split on a space
implode(" ", $list) creates a string of the elements from
$list, separated by a space
$words = array(Are, you, lonesome, tonight);
$str = implode( , $words);
40
Array internal logical structure
Internally, the elements of an array are stored in a linked list of
cells, where each cell includes both the key and the value of the
element.
The cells themselves are stored in memory through a key
hashing function so that they are randomly distributed in a
reserved block of storage.
Accesses to elements through string keys are implemented
through the hashing function.
However, the elements all have links that connect them in the
order in which they were created, allowing them to be accessed
in that order if the keys are strings and in the order of their keys
if the keys are numbers
41
Array internal logical structure
42
Sequential access to array elements
PHP includes several different ways to access array
elements in sequential order
current pointer
Every array has an internal pointer that references
one element of the array
This pointer is initialized to reference the first
element of the array at the time the array is created.
The element being referenced by the pointer can be
obtained with the current function
$colors = array("Blue", "red", "green", "yellow");
$color = current($colors);
print("$color <br />");
produces the following output: Blue
43
the next function
The current pointer can be moved with the next
function, which both moves the pointer to the next
array element and returns the value of that element.
If the current pointer is already pointing at the last
element of the array, next returns FALSE.
For example, if the current pointer is referencing the
first element of the $colors array, the following code
produces a list of all of the elements of that array:
$colors = array("Blue", "red", "green", "yellow");
$color = current($colors);
print("$color <br />");
while ($color = next($colors))
print ("$color <br />");
44
the each function
the next function does not always work for example,
if one of the values in the array happens to be FALSE
Alternative: each, instead of next function
returns a two element array consisting of the key and
the value of the current element, avoids this problem.
It returns FALSE only if the current pointer has gone
past the last element of the array
while ($element = each($colors)) {
print ("$element['value'] <br />");
}
45
MORE ARRAY FUNCTIONS
The current pointer can be moved backward (i. e., to the
element before the current element) with the prev function.
Like the next function, the Prev function returns the value of the
element referenced by the current pointer after the pointer has
been moved.
The current pointer can be set to the first element with the
reset function, which also returns the value of the first element.
It can be set to the last element of the array with the end
function, which also returns the value of the last element.
The key function, when given the name of an array, returns the
key of the current element of the array.
46
The array_push and array_pop functions
These provide a simple way to implement a stack in an array.
The array_push function takes an array as its first parameter.
After this first parameter, there can be any number of additional
parameters.
The values of all subsequent parameters are placed at the end of
the array.
The array_push function returns the new number of elements in
the array.
The array_pop function takes a single parameter: the name of an
array.
It removes the last element from the array and returns it. The
value NULL is re turned if the array is empty.
47
The foreach statement
is designed to build loops that process all of the elements of
an array.
This statement has two forms:
foreach (array as scalar_variable) loop body
foreach (array as key => value) loop body
In the first form, one of the arrays values is set to the scalar
variable for each iteration of the loop body.
The current pointer is implicitly initialized, as with reset,
before the first iteration.
foreach ($colors as $color) {
print "Is $color your favorite color?<br />";}
Is
Is
Is
Is
red your favorite color?
blue your favorite color?
green your favorite color?
yellow your favorite color?
48
The foreach statement
The second form of foreach provides both the key
and the value of each element of the array:
foreach (array as key => value) loop body
i.e. foreach can iterate through both keys and values:
foreach ($colors as $key => $color) { }
Examples:
$ages = array("Bob" => 42, "Mary" => 43);
foreach ($ages as $name => $age)
print("$name is $age years old <br />");
49
Array Sorting Functions
The sort function
takes an array as a parameter, sorts the values in the array,
replacing the keys with the numeric keys, 0, 1, 2, ....
The array can have both string and numeric values.
The string values migrate to the beginning of the array in
alphabetical order.
The numeric values follow in ascending order.
Regardless of the types of the keys in the original array, the
sorted array has 0, 1,2, and so forth as keys.
This function is obviously meant for sorting traditional arrays
of either strings or numbers.
50
Array Sorting Functions
The assortfunction is used to sort arrays that
correspond to hashes.
It sorts the elements of a given array by their values, but
keeps the original keyvalue associations.
As with sort, string values all appear before the numeric
values in alphabetical order.
The numeric values follow in ascending order.
The ksortfunction sorts its given array by keys, rather
than values.
The keyvalue associations are maintained by the process.
51
Sorting into the reverse
orders
The rsort, arsort, and krsortfunctions
behave like the sort, asort, and ksort
functions, respectively, except that they sort
into the reverse orders of their counterparts
The following example illustrates sort,
asort, and ksort:
SHOW sorting.php
52
User-Defined Functions
Syntactic form:
function function_name(formal_parameters) {
}
General Characteristics
functions definition does not need to appear in a
document before the function is called placement is
irrelevant
function overloading is not allowed
Functions can have a variable number of parameters
Default parameter values are supported
Function definitions can be nested
Function names are NOT case sensitive
The return function is used to return a value;
If there is no return, there is no returned value
53
Parameters
If the caller sends too many actual parameters, the
subprogram ignores the extra ones
If the caller does not send enough parameters, the
unmatched formal parameters are unbound
The default parameter passing method is pass by value
(one-way communication)
To specify pass-by-reference, prepend an ampersand to
the formal parameter
function set_max(&$max, $first, $second) {
if ($first >= $second)
$max = $first;
else
$max = $second;}
If the function does not specify its parameter to be pass
by reference, you can prepend an ampersand to the
actual parameter and still get pass-by-reference
54
semantics
The Scope of Variables
The default scope of a variable defined in a function is local.
A local variable is visible only in the function in which it is used.
To access a nonlocal variable, it must be declared to be
global, as in
global $sum;
55
global declaration Example
56
The Lifetime of Variables
In some situations, a function must be history sensitive; that is, it must
retain information about previous activations.
The default lifetime of local variables in a PHP function is from the time the
variable is first used (i. e., when storage for it is allocated) until the
functions execution terminates.
To support history sensitivity, a function must have static local variables.
The lifetime of a static variable in a function begins when the variable is
first used in the first execution of the function. Its lifetime ends when the
script execution ends. In the case of PHP, this is when the browser leaves
the document in which the PHP script is embedded.
In PHP, a local variable in a function can be specified to be static by
declaring it with the reserved word static. Such a declaration can include an
initial value, which is only assigned the first time the declaration is reached
57
static local variables example
Displays the number of times it has been called,
even if it is called from several different places.
The fact that its local variable $count is static
allows this to be done
58
static local variables example
Displays the number of times it has been called,
even if it is called from several different places.
The fact that its local variable $count is static
allows this to be done
59
Pattern Matching
PHP includes two different kinds of string pattern matching
using regular expressions:
one that is based on POSIX regular expressions
one that is based on Perl regular expressions, like those
of JavaScript. ( well
The POSIX regular expressions are compiled into PHP, but
the Perl-Compatible Regular Expression (PCRE) library must
be compiled before Perl regular expressions can be used
The preg_match function takes two parameters, the first
of which is the Perl-style regular expression as a string. The
second parameter is the string to be searched.
60
Pattern Matching
The preg_split function operates on strings but
returns an array and uses patterns
The function takes two parameters, the first of which is
a Perl-style pattern as a string.
The second parameter is the string to be split. For
example, consider the following sample code:
$fruit_string = apple : orange : banana;
$fruits = preg_split(/ : /, $fruit_string);
The array $fruits now has (apple, orange,
banana).
The following example illustrates the use of preg_split
on text to parse out the words and produce a
frequency-of-occurrence table:
SHOW word_table.php
61
Form Handling
Forms could be handled by the same document that
creates the form, but that may be confusing
PHP particulars:
It does not matter whether GET or POST method is used to
transmit the form data
PHP builds an array of the form values ($_GET for the GET
method and $_POST for the POST method subscripts are
the widget names)
SHOW popcorn3.html & popcorn3.php
62
Cookies
Recall that the HTTP protocol is stateless;
however, there are several reasons why it is useful
for a server to relate a request to earlier requests
Targeted advertising
Shopping baskets
A cookie is a name/value pair that is passed
between a browser and a server in the HTTP
header
63
Cookies
In PHP, cookies are created with setcookie
setcookie(cookie_name, cookie_value, lifetime)
e.g., setcookie("voted", "true", time() + 86400);
(86,400 is the number of seconds in a day).
Cookies are implicitly deleted when their lifetimes
are over
Cookies must be created before any other HTML is
created by the script
Cookies are obtained in a script the same way form values
are gotten, using the $_COOKIES array
64
Session Tracking
A session is the time span during which a
browser interacts with a particular server
For session tracking, PHP creates and maintains
a session tracking id
Create the id with a call to session_start with
no parameters
Subsequent calls to session_start retrieves
any session variables that were previously
registered in the session
65
Session Tracking
To create a session variable, use
session_register
The only parameter is a string literal of the name of the session variable
(without the dollar sign)
Example: count number of pages visited
Put the following code in all documents
session_start();
if (!IsSet($page_number))
$page_number = 1;
print("You have now visited $page_number");
print(" pages <br />");
$page_number++;
$session_register("page_number");
66