Web Programming Step by Step

Chapter 5
PHP for Server-Side Programming

Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller.

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? (5.1.2)

PHP logo

Lifecycle of a PHP web request (5.1.1)

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 (5.2.2)

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!

Variables (5.2.5)

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

Types (5.2.3)

Operators (5.2.4)

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

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

Comments (5.2.7)

# single-line comment

// single-line comment

/*
multi-line comment
*/

String type (5.2.6)

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

String functions

$name = "Kenneth Kuan";
$length = strlen($name);              # 12
$cmp = strcmp($name, "Jeff Prouty");  # > 0
$index = strpos($name, "e");          # 1
$first = substr($name, 8, 4);         # "Kuan"
$name = strtoupper($name);            # "KENNETH KUAN"
NameJava Equivalent
explode, implode split, join
strlen length
strcmp compareTo
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim

Interpreted strings

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

for loop (same as Java) (5.2.9)

for (initialization; condition; update) {
	statements;
}
for ($i = 0; $i < 10; $i++) {
	print "$i squared is " . $i * $i . ".\n";
}

bool (Boolean) type (5.2.8)

$feels_like_summer = FALSE;
$php_is_rad = TRUE;

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

if/else statement

if (condition) {
	statements;
} elseif (condition) {
	statements;
} else {
	statements;
}

while loop (same as Java)

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

NULL

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

5.3: Embedded PHP

Embedding code in web pages

embedded PHP

A bad way to produce HTML in PHP

<?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>My web page</title>\n";
...
?>

Syntax for embedded PHP (5.3.1)

HTML content

<?php
PHP code
?>

HTML content

Embedded PHP 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>
		<h1>Geneva's Counting Page</h1>
		<p>Watch how high I can count:
			<?php
			for ($i = 1; $i <= 10; $i++) {
				print "$i\n";
			}
			?>
		</p>
	</body>
</html>

Embedded PHP + print = bad

...	
		<h1>Geneva's Counting Page</h1>
		<p>Watch how high I can count:
			<?php
			for ($i = 1; $i <= 10; $i++) {
				print "$i\n";
			}
			?>
		</p>

PHP expression blocks (5.3.2)

<?= 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 error: unclosed braces

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

Common error fixed

...
	<body>
		<p>Watch how high I can count:
			<?php
			for ($i = 1; $i <= 10; $i++) {     # PHP mode
				?>
				<?= $i ?>                     <!-- HTML mode -->
				<?php
			}                                  # PHP mode
			?>
		</p>
	</body>
</html>

Common error: Missing = sign

...
	<body>
		<p>Watch how high I can count:
			<?php
			for ($i = 1; $i <= 10; $i++) {
				?>
				<? $i ?>
				<?php
			}
			?>
		</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

Functions (5.4.1)

function name(parameterName, ..., parameterName) {
	statements;
}
function quadratic($a, $b, $c) {
	return -$b + sqrt($b * $b - 4 * $a * $c) / (2 * $a);
}

Calling functions

name(parameterValue, ..., parameterValue);
$x = -2;
$a = 3;
$root = quadratic(1, $x, $a - 2);

Default parameter values

function name(parameterName, ..., parameterName) {
	statements;
}
function print_separated($str, $separator = ", ") {
	if (strlen($str) > 0) {
		print $str[0];
		for ($i = 1; $i < strlen($str); $i++) {
			print $sep . $str[$i];
		}
	}
}
print_separated("hello");        # h, e, l, l, o
print_separated("hello", "-");   # h-e-l-l-o

Variable scope: global and local vars

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

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

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

Including files: include() (5.4.2)

include("filename");
include("header.php");

Arrays (5.4.3)

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

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"

Unpacking an array: list

list($var1, ..., $varN) = array;
$line = "stepp:17:m:94";
list($username, $age, $gender, $iq) = explode(":", $line);

Non-consecutive arrays

$autobots = array("Optimus", "Bumblebee", "Grimlock");
$autobots[100] = "Hotrod";

PHP file I/O functions (5.4.5)

Reading/writing files

$text = file_get_contents("schedule.txt");
$lines = explode("\n", $text);
$lines = array_reverse($lines);
$text = implode("\n", $lines);
file_put_contents("schedule.txt", $text);

Reading files example

# Returns how many lines in this file are empty or just spaces.
function count_blank_lines($file_name) {
	$text = file_get_contents($file_name);
	$lines = explode("\n", $text);
	$count = 0;
	foreach ($lines as $line) {
		if (strlen(trim($line)) == 0) {
			$count++;
		}
	}
	return $count;
}
...
print count_blank_lines("ch05-php.html");

Reading directories

$folder = "images";
$files = scandir($folder);
foreach ($files as $file) {
	if ($file != "." && $file != "..") {
		print "I found an image: $folder/$file\n";
	}
}