Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.
Continued from last week's slides (starting at #44)...
http://server/path/file
https://math-cs.gordon.edu/cps353/quote.php
math-cs.gordon.edu to run the program quote2.php and send back its output

.html file (static content): server just sends that file.php file (dynamic content): server reads it, runs any script code inside it, then sends result across the network
There are many other options for server-side languages: Ruby on Rails, JSP, ASP.NET, etc. Why choose PHP?
php.net/functionName in browser Address bar to get docs for any function
The following contents could go into a file hello.php:
<?php print "Hello, world!"; ?>
<?php and ends with ?>
.php page on your local hard drive; you'll either see nothing or see the PHP source code.php file will run the program and send you back its outputprint
print "text";
print "Hello, World!\n"; print "Escape \"chars\" are the SAME as in Java!\n"; print "You can have line breaks in a string."; print 'A string can use "single-quotes". It\'s cool!';
echo instead of print
+ - * / %
. ++ --
= += -= *= /= %= .=
5 + "7" is 12$name = expression;
$user_name = "AnthonyAardvark"; $age = 16; $drinking_age = $age + 5; $this_class_rocks = TRUE;
$, on both declaration and usage# single-line comment // single-line comment /* multi-line comment */
# is also allowed
# comments instead of //for loop
for (initialization; condition; update) {
statements;
}
for ($i = 0; $i < 10; $i++) {
print "$i squared is " . $i * $i . ".\n";
}
if/else statement
if (condition) {
statements;
} elseif (condition) {
statements;
} else {
statements;
}
elseif keyword is much more common, else if is also supportedHTML content <?php PHP code ?> HTML content <?php PHP code ?> HTML content ...
.php file between <?php and ?> are executed as PHP code$a = 3; $b = 4; $c = sqrt(pow($a, 2) + pow($b, 2));
abs
|
ceil
|
cos
|
floor
|
log
|
log10
|
max
|
min
|
pow
|
rand
|
round
|
sin
|
sqrt
|
tan
|
M_PI
|
M_E
|
M_LN2
|
int and float types$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
int for integers and float for realsint values can produce a floatString type
$favorite_food = "Ethiopian"; print $favorite_food[2];
. (period), not +
5 + "2 turtle doves" produces 75 . "2 turtle doves" produces "52 turtle doves""" or ''$age = 16; print "You are " . $age . " years old.\n"; print "You are $age years old.\n"; # You are 16 years old.
" " are interpolated
' ' are not interpolated:
print 'You are $age years old.\n'; # You are $age years old.\n
{}:
print "Today is your $ageth birthday.\n"; # $ageth not found print "Today is your {$age}th birthday.\n";
String functions# index 0123456789012345 $name = "Stefanie Hatcher"; $length = strlen($name); # 16 $cmp = strcmp($name, "Brian Le"); # > 0 $index = strpos($name, "e"); # 2 $first = substr($name, 9, 5); # "Hatch" $name = strtoupper($name); # "STEFANIE HATCHER"
| Name | Java Equivalent |
|---|---|
strlen |
length |
strpos |
indexOf |
substr |
substring |
strtolower, strtoupper |
toLowerCase, toUpperCase |
trim |
trim |
explode, implode |
split, join |
strcmp |
compareTo |
$feels_like_summer = TRUE;
$php_is_rad = FALSE;
$student_count = 12;
$nonzero = (bool) $student_count; # TRUE
FALSE (all others are TRUE):
0 and 0.0
"", "0", and NULL (includes unset variables)(bool)FALSE prints as an empty string (no output); TRUE prints as a 1TRUE and FALSE keywords are case insensitive
<?php
print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n";
print " \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
print "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
print " <head>\n";
print " <title>Geneva's web page</title>\n";
...
for ($i = 1; $i <= 10; $i++) {
print "<p> I can count to $i! </p>\n";
}
?>
print statements is bad style and error-prone:
\"print, how do we insert dynamic content into the page?<?= expression ?>
<h2> The answer is <?= 6 * 7 ?> </h2>
<?= expr ?> is equivalent to <?php print expr; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>CSE 190 M: Embedded PHP</title></head>
<body>
<?php for ($i = 99; $i >= 1; $i--) { ?>
<p> <?= $i ?> bottles of beer on the wall, <br />
<?= $i ?> bottles of beer. <br />
Take one down, pass it around, <br />
<?= $i - 1 ?> bottles of beer on the wall. </p>
<?php } ?>
</body>
</html>
<body>
<p>Watch how high I can count:
<?php for ($i = 1; $i <= 10; $i++) { ?>
<? $i ?>
</p>
</body>
</html>
</body> and </html> above are inside the for loop, which is never closed$end'= in <?=, the expression does not produce any output
<body>
<?php for ($i = 1; $i <= 3; $i++) { ?>
<h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>>
<?php } ?>
</body>
NULL
$name = "Aardvark";
$name = NULL;
if (isset($name)) {
print "This line isn't going to be reached.\n";
}
$name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # append
$a = array(); # empty array (length 0) $a[0] = 23; # stores 23 at index 0 (length 1) $a2 = array("some", "strings", "in", "an", "array"); $a2[] = "Ooh!"; # add string to end (at index 5)
| function name(s) | description |
|---|---|
count
|
number of elements in the array |
print_r
|
print array's contents |
array_pop,
array_push, array_shift,
array_unshift
|
using array as a stack/queue |
in_array,
array_search,
array_reverse, sort,
rsort,
shuffle
|
searching and reordering |
array_fill,
array_merge,
array_intersect, array_diff,
array_slice,
range
|
creating, filling, filtering |
array_sum,
array_product,
array_unique, array_filter,
array_reduce
|
processing elements |
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
} # ("md", "bh", "kk", "hm", "jp")
$morgan = array_shift($tas); # ("bh", "kk", "hm", "jp")
array_pop($tas); # ("bh", "kk", "hm")
array_push($tas, "ms"); # ("bh", "kk", "hm", "ms")
array_reverse($tas); # ("ms", "hm", "kk", "bh")
sort($tas); # ("bh", "hm", "kk", "ms")
$best = array_slice($tas, 1, 2); # ("hm", "kk")
foreach loop
foreach ($array as $variableName) {
...
}
$stooges = array("Larry", "Moe", "Curly", "Shemp");
for ($i = 0; $i < count($stooges); $i++) {
print "Moe slaps {$stooges[$i]}\n";
}
foreach ($stooges as $stooge) {
print "Moe slaps $stooge\n"; # even himself!
}
$array = explode(delimiter, string); $string = implode(delimiter, array);
$s = "CPS 353 FA 2013";
$a = explode(" ", $s); # ("CSP", "353", "FA", "2013")
$s2 = implode("...", $a); # "CSP...353...FA...2013"
explode and implode convert between strings and arraysexplodenames.txtAnthony Aardvark Frederick Fox Zelda Zebra
foreach (file("names.txt") as $name) {
$tokens = explode(" ", $name);
?>
<p> overused example animal: <?= $tokens[1] ?>, <?= $tokens[0] ?> </p>
<?php
}
overused example animal: Aardvark, Anthony
overused example animal: Fox, Frederick
overused example animal: Zebra, Zelda
function name(parameterName, ..., parameterName) {
statements;
}
function bmi($weight, $height) {
$result = 703 * $weight / $height / $height;
return $result;
}
return statements is implicitly "void"name(expression, ..., expression);
$w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h);
$school = "Gordon"; # global ... function downgrade() { global $school; $suffix = "(College)"; # local $school = "$school $suffix"; print "$school\n"; }
global statement
function name(parameterName = value, ..., parameterName = value) {
statements;
}
function print_separated($str, $separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
}
print_separated("hello"); # h, e, l, l, o
print_separated("hello", "-"); # h-e-l-l-o
| function name(s) | category |
|---|---|
file,
file_get_contents, file_put_contents
|
reading/writing entire files |
basename,
file_exists,
filesize, fileperms,
filemtime,
is_dir, is_readable,
is_writable,
disk_free_space
|
asking for information |
copy,
rename,
unlink,
chmod, chgrp,
chown,
mkdir,
rmdir
|
manipulating files and directories |
glob,
scandir
|
reading directories |
contents of foo.txt |
file("foo.txt") |
file_get_contents("foo.txt") |
|---|---|---|
Hello how r u? I'm fine |
array( "Hello\n", # 0 "how r u?\n", # 1 "\n", # 2 "I'm fine\n" # 3 ) |
"Hello\n how r u?\n # a single \n # string I'm fine\n" |
file function returns lines of a file as an array (\n at end of each)file_get_contents returns entire contents of a file as a single string
file_put_contents writes a string into a file
# reverse a file
$text = file_get_contents("poem.txt");
$text = strrev($text);
file_put_contents("poem.txt", $text);
file_get_contents returns entire contents of a file as a string
file_put_contents writes a string into a file, replacing its old contents
# add a line to a file
$new_text = "P.S. ILY, GTG TTYL!~";
file_put_contents("poem.txt", $new_text, FILE_APPEND);
| old contents | new contents |
|---|---|
Roses are red, Violets are blue. All my base, Are belong to you. |
Roses are red, Violets are blue. All my base, Are belong to you. P.S. ILY, GTG TTYL!~ |
file_put_contents can be called with an optional third parameter to append (add to the end) rather than overwritefile function# display lines of file as a bulleted list $lines = file("todolist.txt"); foreach ($lines as $line) { # for ($i = 0; $i < count($lines); $i++) print "<li>$line</li>\n"; }
file returns the lines of a file as an array of strings
\n ; to strip it, use an optional second parameter:
$lines = file("todolist.txt", FILE_IGNORE_NEW_LINES);
foreach or for loop over lines of filelistlist($var1, ..., $varN) = array;
personal.txtAnthony Aardvark (978) 555-1212 978-555-3434
list($name, $phone, $ssn) = file("personal.txt");
...
list function "unpacks" an array into a set of variables you declare
file and list to unpack it
| function | description |
|---|---|
scandir |
returns an array of all file names in a given directory (returns just the file names, such as "myfile.txt")
|
glob |
returns an array of all file names that match a given pattern (returns a file path and name, such as "foo/bar/myfile.txt")
|
glob can accept a general path with the * wildcard character
glob example
# reverse all poems in the poetry directory
$poems = glob("poetry/poem*.dat");
foreach ($poems as $poemfile) {
$text = file_get_contents($poemfile);
file_put_contents($poemfile, strrev($text));
print "<p>I just reversed " . basename($poemfile) . "</p>\n";
}
glob can match a "wildcard" path with the * character
glob("foo/bar/*.doc") returns all .doc files in the foo/bar subdirectory
glob("food*") returns all files whose names begin with "food"
basename function strips any leading directory from a file path
basename("foo/bar/baz.txt") returns "baz.txt"
scandir example
<ul>
<?php
$folder = "taxes/old";
foreach (scandir($folder) as $filename) {
print "<li>$filename</li>\n"
}
?>
</ul>
scandir includes current directory (".") and parent ("..") in the arraybasename with scandir; returns file names only without directory
# construct an object $name = new ClassName(parameters); # access an object's field (if the field is public) $name->fieldName # call an object's method $name->methodName(parameters);
$zip = new ZipArchive();
$zip->open("moviefiles.zip");
$zip->extractTo("images/");
$zip->close();
class_exists# create an HTTP request to fetch student.php $req = new HttpRequest("student.php", HttpRequest::METH_GET); $params = array("first_name" => $fname, "last_name" => $lname); $req->addPostFields($params); # send request and examine result $req->send(); $http_result_code = $req->getResponseCode(); # 200 means OK print "$http_result_code\n"; print $req->getResponseBody();
HttpRequest object can fetch a document from the web
class ClassName {
# fields - data inside each object
public $name; # public field
private $name; # private field
# constructor - initializes each object's state
public function __construct(parameters) {
statement(s);
}
# method - behavior of each object
public function name(parameters) {
statements;
}
}
$this
<?php
class Point {
public $x;
public $y;
# equivalent of a Java constructor
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
public function distance($p) {
$dx = $this->x - $p->x;
$dy = $this->y - $p->y;
return sqrt($dx * $dx + $dy * $dy);
}
# equivalent of Java's toString method
public function __toString() {
return "(" . $this->x . ", " . $this->y . ")";
}
}
?>
<?php # this code could go into a file named use_point.php include("Point.php"); $p1 = new Point(0, 0); $p2 = new Point(4, 3); print "Distance between $p1 and $p2 is " . $p1->distance($p2) . "\n\n"; var_dump($p2); # var_dump prints detailed state of an object ?>
Distance between (0, 0) and (4, 3) is 5 object(Point)[2] public 'x' => int 4 public 'y' => int 3
$p1 and $p2 are references to Point objects
class ClassName extends ClassName {
...
}
class Point3D extends Point {
public $z;
public function __construct($x, $y, $z) {
parent::__construct($x, $y);
$this->z = $z;
}
...
}
static $name = value; # declaring a static field const $name = value; # declaring a static constant
# declaring a static method
public static function name(parameters) {
statements;
}
ClassName::methodName(parameters); # calling a static method (outside class) self::methodName(parameters); # calling a static method (within class)
interface InterfaceName {
public function name(parameters);
public function name(parameters);
...
}
class ClassName implements InterfaceName { ...
abstract class ClassName {
abstract public function name(parameters);
...
}