Lecture 6.
PHP: Part 1
1
Origins and Uses of PHP
Developed by Rasmus Lerdorf, a member of the Apache
Group, in 1994 to track visitors to his Web site
PHP‟s development was transferred to a small group of
devoted volunteers and now is an open-source product
PHP is originally an acronym for Personal Home Page, later
PHP: Hypertext Preprocessor
PHP, as a server-side scripting language, is used for form
handling, file processing, and database access
has driver support for 15 database systems
supports electronic mail protocols POP3 and IMAP
supports distributed object architectures COM and CORBA
2
Overview of PHP
PHP is a server-side scripting language whose scripts are
embedded in HTML documents
Similar to JavaScript, but on the server side
PHP is an alternative to CGI, Active Server Pages (ASP),
and Java Server Pages (JSP)
Filename extension is .php, .php3, or .phtml
PHP syntax is similar to that of JavaScript
PHP is dynamically typed
PHP has an extensive library of functions, making a flexible
and powerful
http://www.php.net
3
Overview of PHP
The PHP processor has two modes: copy (XHTML) and
interpret (PHP).
PHP processor takes a PHP document as input and
produces an XHTML document file
When it finds XHTML code in the input file, simply
copies it to the output file
When it finds PHP script, it interprets it and send any
output of the script to the output file
This new output file is sent to the requesting browser.
The client never sees the PHP script.
4
Operation Overview
Request
a page
Web browser Web Server
Transfer
XHTML file Request
Client data Generate
processing XHMTL file
Other
Server PHP Engine DB
Platform
5
General Syntactic Characteristics
PHP code can be specified in an HTML document
internally or externally:
Internally: <?php
...
?>
Externally: include ("myScript.inc")
The included file can contain XHTML or client-side
script as well as PHP
If the file has PHP, the PHP must be in <?php ... ?>,
even if the include appears in <?php ... ?>
6
General Syntactic Characteristics
All variable names begin with $
The name part is like the names of variables in many
programming languages: a letter or an underscore
followed by any number of letters, digits, or underscores
PHP variables are case sensitive, but reserved words
and function names are not. (Table 12.1)
(Ex) while, WHILE, While, and wHiLe are same
Comments - three different kinds (Java and Perl)
(a) // ... ; for single line
(b) # ... ; for single line
(c) /* ... */ ; for multiple-line
7
PHP Reserved Words
and else function not this
break elseif global or true
case extends if require var
class false include return virtual
continue for list static xor
default foreach new switch while
do
8
General Syntactic Characteristics
PHP statements are terminated with semicolons.
Compound statements for control structures are
formed with braces
Unless used as the body of a function definition,
compound statements cannot be blocks
They cannot define locally scoped variables
9
Example
10
PHP TYPES
Four scalar types
Boolean
Integer
Double
String
Two compound types
Array
Object*
Two special types
NULL
Resource*
* will not be covered here.
11
Variables
There are no type declarations because of dynamic typing
The type of a variable is set every time it is assigned a value
An unassigned ( unbound ) variable has the value, NULL
A variable of NULL in the expression will be coerced to a value
dictated by the context of the use
(Ex) If a number, NULL is coerced to 0
If a string, NULL is coerced to the empty string
The unset function sets a variable to NULL
The IsSet function tests whether a variable is NULL
(Ex) IsSet ( $fruit ) returns TRUE if $fruit has non-NULL value
12
Variables
If you prefer to be informed when an unbound variable
is referenced, place the error_reporting(15) at the
beginning of the script in the document file
The error_reporting function is used to change the error –
reporting level of the PHP interpreter
The default error-reporting level is 7
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
13
primitive types
Integer type corresponds to the long type of C and its
successors
Double type corresponds to the double type of C and
its successors. Decimal point, an exponent, or both.
There is no character type
A single character data value is a string of length one
Strings
Characters are single bytes
String literals use single (′)or double quotes(″)
14
Example
Integer
$var = 1234; // Decimal
$var = -1234; // Decimal
$var = 01234; // Octal
$var = 0x1234; // Hexadecimal
Floating point
$a = 1.234; // Float
$a = 0.1234e1; // Exponential
15
String
Single-quoted string literals
Embedded variables are NOT interpolated
(Ex) „The sum is: $sum‟ = The sum is: $sum
Embedded escape sequences are NOT recognized
Double-quoted string literals
Embedded variables ARE interpolated
(Ex) “The sum is: $sum” = The sum is: 12.4
If there is a variable name in a double-quoted string but
you don‟t 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
16
Special character
Special char. Semantics
\n new line
\r Return carriage
\t Tab
\\ Backslash
\$ Dollar
\” Quotation mark
17
Boolean
The only two possible values are TRUE and FALSE
(case insensitive)
If an integer expression is used in Boolean context, it
is FALSE if it is zero; otherwise, it is TRUE.
If a string expression is used in Boolean context, it is
FALSE if it is either the empty string or the string "0";
otherwise, it is TRUE.
18
Arithmetic Operators and Expressions
+, -, *, /, %, ++, --
For +,- and *, if either operand is double, then it
produces a double result
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 non-integer
operands to integer
19
Predefined Functions
Functi Paramet
Returns
on er
floor Double Largest integer less than or equal to the parameter
ceil Smallest integer greater than or equal to the
Double parameter
round Double Nearest integer
srand Integer Initializes a random number generator with the
parameter
rand Two A pseudorandom number greater than the first
numbers parameter and smaller than the second
abs Integer or Absolute value of the parameter
double
min Numbers Smallest
max Numbers Largest
20
String Operations and Functions
The only operator is period(.) for catenation
String variables can be treated like arrays for access to
individual characters
The position can be specified in braces
(Ex) If $str has “apples”, $str{3} is the fourth (l)
Functions:
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
21
String functions
Function Parameter Returns
strlen A string The no. of characters in the string
strcmp Two strings 0, negative, or positive number
strpos Two strings The character position...
substr A string and The substring of the string, starting from
an integer the second parameter (possibly, third
parameter for length)
chop A string Remove all whitespace from its end
trim A string Remove all whitespace from both ends
ltrim A string Remove all whitespace from its begin
strtolower A string All uppercase letters converted to
lowercase
strtoupper A string All lowercase letters converted to
uppercase
22
Example
$str = “Apples are good”;
$sub = substr ($str, 7, 1);
The value of $sub is „a‟.
23
Scalar Type Conversions
Implicit type conversions (coercions)
The context of an expression determines the type that is
expected or required
When a numeric value appears in string context, the
numeric value is coerced to a string
When a string value appears in numeric context, the
string value is coerced to a number.
String to numeric
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
Nonnumeric characters following the number in the
string are ignored.
24
Scalar Type Conversions
Explicit type conversions in three different ways
Using cast: (type_name) exp
(Ex) $total = 4.333; (int) $total // 4
Using function: intval, doubleval, strval
(Ex) $total = 4.333; intval($total) // 4
Using settype function: settype (variable, type_name)
(Ex) settype($total, "integer") // 4
The type of a variable can be determined with gettype
or type testing functions
gettype($total) - returns the type of the current value.
It may return "unknown"
is_integer($total), is_float(), is_bool(), is_string()
– a predicate function
25
Output
Any output from a PHP script becomes part of the
document the PHP processor is building
An output from a PHP script is in the form of XHTML
that is sent to the browser
XHTML is sent to the browser through standard output
There are three ways to produce output :
echo
print
printf
26
Output
echo function
If parentheses are included, only a single string parameter
is acceptable
Otherwise, any number of parameters are acceptable
(Ex) echo "whatever", "it may <br />";
echo ("first <br />") ;
returns no value
echo and print take a string, but coerce other values
to strings
(Ex) echo 47 or print(47) will produce 47
27
Output
print function:
Called with only one parameter, possibly in a parenthesis
(Ex) print "Welcome to my site!";
Will coerce non-string type value to a string
Return a value (1 if successful, 0 otherwise)
printf function
Is like its counterpart in C
Can control the format of displayed data completely
(Ex) $day = “Tuesday”;
$high = 79;
printf (“The high on %7s was %3d”, $day, $high);
28
Example
<!-- today.php: An example to illustrate a php document -->
<html>
<head> <title> today.php </title>
</head>
<body>
<p>
<?php
print “<b>Welcome to my home page <br /><br />”;
print “Today is: “;
print date(“l, F jS”);
print “<br />”;
?>
</p>
</body>
Welcome to my home page
</html>
Today is: Saturday, June 1st
29
Control Statements
Relational Operators
Use eight relational operators of JavaScript
> , < , >= , <= , != , == , === , !==
For string op number
If the string converted to a number, do numeric
comparison
If the string not converted to a number, do string
comparison
For string op string
If both converted to numbers, do numeric comparison
Boolean operators
(and , &&), (or , ||) , xor , !
The precedence of and and or is higher than that of &&
and || 30
Control Statements
Selection statements
if, if-else, elseif
switch - as in C
while - just like C
do-while - just like C
for - just like C
foreach - discussed later
break - in any for, foreach, while, do-while, or switch
continue - in any loop
31
Alternative compound delimiters
Applicable to if, switch, for, and while control
statements
Opening delimiter is the colon with its own closing
reserved word
More readable.
while ($a < 100) { while ($a < 100) :
$a = $a * $b + 7; $a = $a * $b + 7;
$b++; $b++;
} endwhile;
SHOW powers.html
32
Example
if ($day ==== “Saturday” || $day == “Sunday”)
$today = “weekend”;
else {
$today = “weekday”;
$work = true;
}
switch ($bordersize) {
case “0”: print “<table>”; break;
case “1”: print “<table border = „1‟>”; break;
case “4”: print “<table border = „4‟>”; break;
case “8”: print “<table border = „8‟>”; break;
default: print “Error-invalid value: $bordersize <br />”;
}
33
Example
$fact = 1;
$count = 1;
while ($count < $n) {
$count ++;
$fact *= $count;
}
for ($count = 1, $fact = 1; $count < $n) {
$count++;
$fact *= $count;
}
34
HTML/PHP document
HTML can be intermingled with PHP script
35
Example
<!-- powers.php
An example to illustrate loops and arithmetic -->
<html>
<head><title> powers.php </title>
</head>
<body>
<table border = "border">
<caption> Powers table </caption>
<tr>
<th> Number </th>
<th> Square Root </th>
<th> Square </th>
<th> Cube </th>
<th> Quad </th>
</tr>
36
<?php
for ($number = 1; $number <=10; $number++) {
$root = sqrt($number);
$square = pow($number, 2);
$cube = pow($number, 3);
$quad = pow($number, 4);
print("<tr align = 'center'> <td> $number </td>");
print("<td> $root </td> <td> $square </td>");
print("<td> $cube </td> <td> $quad </td> </tr>");
}
?>
</table>
</body>
</html>
37
Result
Powers table
Number Square Root Square Cube Quad
1 1 1 1 1
2 1.4142125623731 4 8 16
3 1.7320508075689 9 27 81
4 2 16 64 256
5
6
7
8
9
10
38
PHP in HTML
HTML
<html>
<body>
<h1> PHP </h1><br>
<h2> Programming </h2>
</body>
</html>
PHP in HTML
<html>
<body>
<?php
print(“<h1> PHP </h1><br>”);
print(“<h2> Programming </h2>”);
?>
</body>
</html>
39
PHP in HTML
Using variable
<?php
$time = date(“Y - m - d - H : i : s ”);
?>
<html>
<body>
<?php
// Print current time...
print(“<h2> Current time is $time. </h2>”);
?>
</body>
</html>
40