PHP Slides
PHP Slides
http://server/path/file
Usually when you type a URL in your
browser:
Your computer looks up the server's IP address
using DNS
Your browser connects to that IP address and
requests the given file
The web server software (e.g. Apache) grabs that file
from the server's local file system
The server sends back its contents to you
CS380 2
Apache,
Websphere
SW(Java Servlets,
XML Files)
3
http://www.facebook.com/home.p
hp
Some URLs actually specify programs that the
web server should run, and then send their
output back to you as the result:
The above URL tells the server facebook.com to run
the program home.php and send back its output
CS380 4
Server-side pages are programs written using
one of many web programming
languages/frameworks
examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl
CS380 5
Also called server side scripting:
Dynamically edit, change or add any content to a
Web page
Respond to user queries or data submitted from
HTML forms
Access any data or databases and return the results
to a browser
Customize a Web page to make it more useful for
individual users
Provide security since your server code cannot be
viewed from a browser
6
Web server:
contains software that allows it to run server side
programs
sends back their output as responses to web requests
Each language/framework has its pros and
cons
we use PHP
CS380 7
PHP stands for "PHP Hypertext Preprocessor"
Server-side scripting language
Used to make web pages dynamic:
provide different content depending on context
interface with other services: database, e-mail, etc.
authenticate users
process form information
PHP code can be embedded
in XHTML code
CS380 8
Hello.php
Hello world!
CS380 10
PHP is server side scripting system
PHP stands for "PHP: Hypertext Preprocessor"
Syntax based on Perl, Java, and C
Very good for creating dynamic content
Powerful, but somewhat risky!
If you want to focus on one system for dynamic
content, this is a good one to choose
Started as a Perl hack in 1994 by Rasmus
Lerdorf (to handle his resume), developed to
PHP/FI 2.0
By 1997 up to PHP 3.0 with a new parser
engine by Zeev Suraski and Andi Gutmans
Version 5.2.4 is current version, rewritten by
Zend (www.zend.com) to include a number of
features, such as an object model
Current is version 5
php is one of the premier examples of what an
open source project can be
A Commercial Enterprise
Zend provides Zend engine for PHP for free
They provide other products and services for a
fee
Server side caching and other optimizations
Encoding in Zend's intermediate format to protect
source code
IDE-a developer's package with tools to make life
easier
Support and training services
Zend's web site is a great resource
Zend engine as parser (Andi Gutmans and Zeev
Suraski)
SAPI is a web server abstraction layer
PHP components now self contained (ODBC, Java,
LDAP, etc.)
This structure is a good general design for software
(compare to OSI model, and middleware applications)
<?php
echo "<html><head><title>Howdy</title>
…
?>
<?php
print "Hello, world!";
?> PHP
Hello world!
output
CS380 18
Hello world!
19
HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ... PHP
Contents of a .php file between <?php and ?> are executed as PHP code
All other contents are output as pure HTML
We can switch back and forth between HTML and PHP "modes"
20
print "text";
PHP
Hello world! Escape "chars" are the SAME as in Java! You can have line
breaks in a string. A string can use "single-quotes". It's cool!
output
CS380 21
$name = expression; PHP
$user_name = “mundruid78";
$age = 16;
$drinking_age = $age + 5;
$this_class_rocks = TRUE; PHP
00
The phpinfo() function shows the php
environment
Use this to read system and server variables,
setting stored in php.ini, versions, and modules
Notice that many of these data are in arrays
This is the first script you should write…
00_phpinfo.php
Using the value of a variable as the name of a
second variable)
$a = "hello";
$$a = "world";
Thus:
echo "$a ${$a}";
Is the same as:
echo "$a $hello";
00_hello_world.php
+ - * / % . ++ --
= += -= *= /= %= .=
many operators auto-convert types: 5 + "7" is
12
CS380 27
# single-line comment
// single-line comment
/*
multi-line comment
*/ PHP
CS380 28
$favorite_food = "Ethiopian";
print $favorite_food[2];
$favorite_food = $favorite_food . " cuisine";
print $favorite_food;
PHP
CS380 29
# index 0123456789012345
$name = "Stefanie Hatcher";
$length = strlen($name);
$cmp = strcmp($name, "Brian Le");
$index = strpos($name, "e");
$first = substr($name, 9, 5);
$name = strtoupper($name);
PHP
CS380 30
Name Java Equivalent
strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join
strcmp compareTo
CS380
31
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n"; # You are 16 years old.
PHP
CS380 32
print "Today is your $ageth birthday.\n"; # $ageth not
found
print "Today is your {$age}th birthday.\n";
PHP
CS380 33
$name = “Xenia";
$name = NULL;
if (isset($name)) {
print "This line isn't going to be reached.\n";
} PHP
a variable is NULL if
it has not been set to any value (undefined variables)
CS380 34
Defined: A method of specifying a search string
using a number of special characters that can
precisely match a substring.
36
Description: Anchors define a specific location for the
match to take place.
Anchor Meaning
^ Match start of line
$ Match end of line
. Match any single character
\b Match word boundary
\B Match non-word boundary
37
Defined: A method of matching a set of characters.
Examples
Match any upper or lower case alpha character:
[A-Za-z]
Examples
Match any non-alpha character:
[^A-Za-z]
Example:
Match the string “red”, “white”, or “blue”:
Regular Expression:
red|white|blue
40
Defined: Parentheses can be used to group
regular expressions.
Example:
Match any of the following:
a long time ago
a long long time ago
a long long long time ago
Regular Expression:
(long )+
41
Greedy Defined: By default, regular expressions are
“greedy” meaning that '.*' and '.+' will always
match as the longest string.
Example:
Given the string:
do <b>not</b> press
Example:
Given the string:
do <b>not</b> press
44
Description: Modifiers change the matching
behavior of the regular expression.
Modifier Meaning
i Ignore case (case insensitive)
s Dot matches all characters
m Match start and end of line
anchors at embedded new lines
in search string
Example match upper and lower case “abc”:
'/abc/i'
45
Discussion: PHP functions that use Perl
regular expressions start with
“preg_”. The regular expressions are
in Perl format meaning, they start and
end with a slash. In order to prevent
variable expansion, regular
expressions are usually specified with
single quotes.
46
Discussion: The function “preg_match()” returns the number of times a
pattern matches a string. Because it returns zero if there are no matches,
this function works ideal in an “if” statement.
Example:
<?php
$subject = "Jack and Jill went up the hill.";
$pattern = '/jack|jill/i';
Example:
<?php
$subject = "Every good boy deserves fudge.";
$pattern = '/[aeiou]/i';
CS380 63
$feels_like_summer = FALSE;
$php_is_great = TRUE;
$student_count = 7;
$nonzero = (bool) $student_count; # TRUE
PHP
the following values are considered to be
FALSE (all others are TRUE):
0 and 0.0 (but NOT 0.00 or 0.000)
"", "0", and NULL (includes unset variables)
CS380 65
while (condition) {
statements;
} PHP
do {
statements;
} while (condition);
PHP
CS380 66
$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
PHP
math functions
CS380 67
$a = 7 / 2; # float: 3.5
$b = (int) $a; # int: 3
$c = round($a); # float: 4.0
$d = "123"; # string: "123"
$e = (int) $d; # int: 123 PHP
CS380 68
$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append PHP
CS380 69
function name(s) description
count number of elements in the array
print_r print array's contents
array_pop, array_push,
using array as a stack/queue
array_shift, array_unshift
in_array, array_search, array_reverse,
searching and reordering
sort, rsort, shuffle
array_fill, array_merge,
array_intersect, creating, filling, filtering
array_diff, array_slice, range
array_sum, array_product,
array_unique, processing elements
array_filter, array_reduce
70
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
PHP
CS380 71
foreach ($array as $variableName) {
...
} PHP
CS380 72
<?php $AmazonProducts = array( array(“BOOK",
"Books", 50),
array("DVDs",
“Movies", 15),
array(“CDs", “Music",
20)
);
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) { ?>
<p> | <?=
$AmazonProducts[$row][$column] ?>
<?php } ?>
</p>
<?php } ?>
PHP
CS380 73
<?php $AmazonProducts = array( array(“Code” =>“BOOK",
“Description” => "Books", “Price” => 50),
array(“Code” => "DVDs",
“Description” => “Movies", “Price” => 15),
array(“Code” => “CDs",
“Description” => “Music", “Price” => 20)
);
for ($row = 0; $row < 3; $row++) { ?>
<p> | <?= $AmazonProducts[$row][“Code”] ?> | <?=
$AmazonProducts[$row][“Description”] ?> | <?=
$AmazonProducts[$row][“Price”] ?>
</p>
<?php } ?>
PHP
CS380 74
You can directly read data into individual
array slots via a direct assignment:
$pieces[5] = "poulet resistance";
From a file:
Use the file command to read a delimited file (the
delimiter can be any unique char):
$pizza = file(./our_pizzas.txt)
Use explode to create an array from a line within a
loop:
$pieces = explode(" ", $pizza);
The power of php lies partially in the wealth of
functions---for example, the 40+ array
functions
array_flip() swaps keys for values
array_count_values() returns an associative array of
all values in an array, and their frequency
array_rand() pulls a random element
array_unique() removes duppies
array_walk() applies a user defined function to each
element of an array (so you can dice all of a dataset)
count() returns the number of elements in an array
array_search() returns the key for the first match in
an array
08_array_fu.php
Like javascript, php supports user defined
functions
Declare your functions towards the top of your
php file--this is not a requirement, just good
practice
Functions are created when the program is
read, and before execution
Or, build an exterior file with commonly used
functions, and give that a version number.
Then require that file to reuse your code (see
the general functions file in the samples for
examples I use)
The simplest way to pass data into a
function is through that functions argument
list of variable (and arrays are a type of
variable)
// wrap the variable in p
function echo_p($wrapped_item) {
echo "<p>$wrapped_item</p>";
}
You can also set default values, but watch
placement--defaults to the right please
// wrap the variable in h
// default to level 2
function echo_h($wrapped_item, $level="2") {
echo "<h" . $level . ">$wrapped_item</h" . $level. ">\n";
}
12
Functions themselves have global scope--
functions defined within functions are
available everywhere
Variables assigned or modified inside of a
function have their value only within the
function
A variable can be declared global within a
function, however, if you want to pass that
variable into and out of the function
Generally, it's better to leave variable scope
limited, this makes the function portable….
15
function foo() {
Unlike variables, function bar() {
functions are echo "I don't exist until foo() is called.\n";
global in scope }
}
But a function
doesn't execute /* We can't call bar() yes since it doesn't exist.
*/
until called
Here, foo() is used foo();
to create bar() /* Now we can call bar(), foo()'s processing has
Once foo() is made it accessible. */
called, bar() exists bar();
function greet() {
print "Hello\n";
} Hello
Hello
greet(); Hello
greet();
greet();
Often a function will take its arguments, do some
computation and return a value to be used as the
value of the function call in the calling
expression. The return keyword is used for this.
function greeting() {
return "Hello"; Hello Glenn
} Hello Sally
function howdy($lang) {
if ( $lang == 'es' ) return "Hola";
if ( $lang == 'fr' ) return "Bonjour";
return "Hello"; Hola Glenn
Bonjour Sally
}
function double($alias) {
$alias = $alias * 2;
return $alias; Value = 10 Doubled = 20
}
$val = 10;
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
Sometimes we want a function to change one
of its arguments - so we indicate that an
argument is "by reference" using ( & )
function triple(&$realthing) {
$realthing = $realthing * 3;
}
$val = 10;
triple($val);
echo "Triple = $val\n"; Triple = 30
In general, variable names used inside of function
code, do not mix with the variables outside of the
function. They are walled-off from the rest of the
code. This is done because you want to avoid
"unexpected" side effects if two programmers use
the same variable name in different parts of the
code.
We call this "name spacing" the variables. The
function variables are in one "name space" whilst
the main variables are in another "name space"
Like little padded cells of names - like silos to keep
things spearate
function tryzap() {
$val = 100;
}
TryZap = 10
$val = 10;
tryzap();
echo "TryZap = $val\n";
function dozap() {
global $val;
$val = 100;
}
DoZap = 100
$val = 10;
dozap();
echo "DoZap = $val\n";