Web Programming Step by Step, 2nd Edition

Chapter 5: PHP

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid XHTML 1.1 Valid CSS!

5.1: Server-Side Basics

URLs and web servers

http://server/path/file

Server-Side web programming

php jsp ruby on rails asp.net

What is PHP?

PHP logo

Lifecycle of a PHP web request

PHP server

Why PHP?

There are many other options for server-side languages: Ruby on Rails, JSP, ASP.NET, etc. Why choose PHP?

Hello, World!

The following contents could go into a file hello.php:

<?php
print "Hello, world!";
?>
Hello, world!

Viewing PHP output

PHP local output PHP server output

5.2: PHP Basic Syntax

Console output: print

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!';
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!

Arithmetic operators

Variables

$name = expression;
$user_name = "PinkHeartLuvr78";
$age = 16;
$drinking_age = $age + 5;
$this_class_rocks = TRUE;

Types

Comments

# single-line comment

// single-line comment

/*
multi-line comment
*/

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;
}

while loop (same as Java)

while (condition) {
	statements;
}
do {
	statements;
} while (condition);

5.2: PHP Basic Syntax

PHP syntax template

HTML content

	<?php
		PHP code
	?>

HTML content

	<?php
		PHP code
	?>

HTML content ...

Math operations

$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
math functions
abs ceil cos floor log log10 max
min pow rand round sin sqrt tan
math constants
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

String type

$favorite_food = "Ethiopian";
print $favorite_food[2];            # h

Interpreted strings

$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n";    # You are 16 years old.

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"
NameJava Equivalent
strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join
strcmp compareTo

bool (Boolean) type

$feels_like_summer = FALSE;
$php_is_rad = TRUE;

$student_count = 217;
$nonzero = (bool) $student_count;     # TRUE
  • TRUE and FALSE keywords are case insensitive

5.3: Embedded PHP

Printing HTML tags in PHP = bad style

<?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";
}
?>

PHP expression blocks

<?= expression ?>
<h2> The answer is <?= 6 * 7 ?> </h2>

The answer is 42

Expression block example

<!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>

Common errors: unclosed braces, missing = sign

	<body>
		<p>Watch how high I can count:
			<?php for ($i = 1; $i <= 10; $i++) { ?>
				<? $i ?>
		</p>
	</body>
</html>

Complex expression blocks

	<body>
		<?php for ($i = 1; $i <= 3; $i++) { ?>
			<h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>>
		<?php } ?>
	</body>

This is a level 1 heading.

This is a level 2 heading.

This is a level 3 heading.

5.4: Advanced PHP Syntax

NULL

$name = "Victoria";
$name = NULL;
if (isset($name)) {
	print "This line isn't going to be reached.\n";
}

Arrays

$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)

Array functions

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

Array function example

$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")

The 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!
}

Splitting/joining strings

$array = explode(delimiter, string);
$string = implode(delimiter, array);
$s  = "CSE 190 M";
$a  = explode(" ", $s);     # ("CSE", "190", "M")
$s2 = implode("...", $a);   # "CSE...190...M"

Example with explode

contents of input file names.txt
Martin D Stepp
Jessica K Miller
Victoria R Kirst
foreach (file("names.txt") as $name) {
$tokens = explode(" ", $name);
?>
<p> author: <?= $tokens[2] ?>, <?= $tokens[0] ?> </p>
<?php
}

author: Stepp, Marty

author: Miller, Jessica

author: Kirst, Victoria

Query strings and parameters

URL?name=value&name=value...
http://www.google.com/search?q=Obama

http://example.com/student_login.php?username=stepp&id=1234567

6.1: Parameterized Pages

Query parameters: $_REQUEST

$user_name = $_REQUEST["username"];
$id_number = (int) $_REQUEST["id"];
$eats_meat = FALSE;
if (isset($_REQUEST["meat"])) {
	$eats_meat = TRUE;
}

Functions

function name(parameterName, ..., parameterName) {
	statements;
}
function bmi($weight, $height) {
	$result = 703 * $weight / $height / $height;
	return $result;
}

Calling functions

name(expression, ..., expression);
$w = 163;  # pounds
$h = 70;   # inches
$my_bmi = bmi($w, $h);

Variable scope: global and local vars

$school = "UW";                   # global
...

function downgrade() {
	global $school;
	$suffix = "(Wisconsin)";        # local

	$school = "$school $suffix";
	print "$school\n";
}

Default parameter values

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

5.4: PHP File Input

PHP file I/O functions

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

Reading/writing files

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"

Reading/writing an entire file

# reverse a file
$text = file_get_contents("poem.txt");
$text = strrev($text);
file_put_contents("poem.txt", $text);

Appending to a file

# 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!~

The file 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";
}

Unpacking an array: list

list($var1, ..., $varN) = array;
contents of input file personal.txt
Marty Stepp
(206) 685-2181
570-86-7326
list($name, $phone, $ssn) = file("personal.txt");
...

Reading directories

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 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";
}

scandir example

<ul>
	<?php
	$folder = "taxes/old";
	foreach (scandir($folder) as $filename) {
		print "<li>$filename</li>\n"
	}
	?>
</ul>
  • .
  • ..
  • 2007_w2.pdf
  • 2006_1099.doc

Why use classes and objects?

Constructing and using objects

# 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();

Object example: Fetch file from web

# 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();

Class declaration syntax

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;
	}
}

Class example

<?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 . ")";
	}
}
?>

Class usage example

<?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

Basic inheritance

class ClassName extends ClassName {
	...
}
class Point3D extends Point {
	public $z;
	
	public function __construct($x, $y, $z) {
		parent::__construct($x, $y);
		$this->z = $z;
	}
	
	...
}

Static methods, fields, and constants

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)

Abstract classes and interfaces

interface InterfaceName {
	public function name(parameters);
	public function name(parameters);
	...
}

class ClassName implements InterfaceName { ...
abstract class ClassName {
	abstract public function name(parameters);
	...
}