CSSE 290 Web Programming

Lecture 7: Advanced PHP; File I/O

Reading: 5.3, 5.4

Attribution: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.

Otherwise noted: Claude Anderson was given permission to modify the slides for CSSE 290 at Rose-Hulman by author Jessica Miller. The authors' original slides, based on Web Programming Step by Step, can be seen at http://webstepbook.com.
Some of the examples in some days' slides are from David Fisher at Rose-Hulman, who was kind enough to allow me to use them. My intention is to mark these examples with [DSF].

Valid HTML Valid CSS!

5.4: Advanced PHP Syntax

== vs. ===

if (3 == 3.0)
	print "== yes "
if (3 === 3.0)
	print " === yes "

== yes

=== only returns TRUE if both values and types match.

How Are Parameters Passed in PHP?

Usually by value (except for objects).
But you can use & to specify pass-by-reference

function triple($n) {
	$n = 3 * $n;
	return $n;
	}
function triple2(&$n) {
	$n = 3 * $n;
	return $n;
	}
$n = 7;
print triple($n) . "  ";
print $n  . "  ";
print triple2($n)  . "  ";
print $n;

21 7 21 21

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)
$a = array();
$a[3] = 5;
$a[5] = 7;
print_r($a);
    Array
(
    [3] => 5
    [5] => 7
)	

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

Some More String Details

Strings in PHP are mutable:

$s = "abcd";
$s[1]="x";
print "$s\n";
axcd

A very useful string function:

$s2 =  htmlspecialchars('<p style="display:none">invisible</p>');
print $s2;

&lt;p style=&quot;display:none&quot;&gt;invisible&lt;/p&gt;

Note:The output shown above is what we'd see if we "view source" for the page.
What does it look like on the actual web page?

Splitting/joining strings

$array = explode(delimiter, string);
$string = implode(delimiter, array);
$s  = "CSSE 290 01";
$a  = explode(" ", $s);     # ("CSSE", "290", "01")
$s2 = implode("...", $a);   # "CSSE...290...01"

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

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

NULL

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

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"

The file function

# display lines of file
$lines = file("todolist.txt");
foreach ($lines as $line) {        # for ($i = 0; $i < count($lines); $i++)
	print $line;
}

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");
...
list($area_code, $prefix, $suffix) = explode(" ", $phone);

Reading directories

function description
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")
scandir returns an array of all file names in a given directory
(returns just the file names, such as "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 "I just reversed " . basename($poemfile) . "\n";
}

scandir Example

<ul>
	<?php foreach (scandir("taxes/old") as $filename) { ?>
		<li>I found a file: <?= $filename ?></li>
	<?php } ?>
</ul>
  • .
  • ..
  • 2007_w2.pdf
  • 2006_1099.doc

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

*See http://en.wikipedia.org/wiki/All_your_base_are_belong_to_us
and http://www.zazzle.com/all_my_base_are_belong_to_you_valentines_day_tees-235673828263506759

6.1: Parameterized Pages

Query Strings and Parameters

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

http://example.com/student_login.php?username=claude&id=1234

Query Parameters: $_GET

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

Example: Exponents

$base = $_GET["base"];
$exp = $_GET["exponent"];
$result = pow($base, $exp);
print "$base ^ $exp = $result";
exponent.php?base=3&exponent=4
3 ^ 4 = 81

Example: Print All Parameters

<?php foreach ($_GET as $param => $value) { ?>
	<p>Parameter <?= $param ?> has value <?= $value ?></p>
<?php } ?>
print_params.php?name=Claude+Anderson&sid=1234567

Parameter name has value Claude Anderson

Parameter sid has value 1234567

or (for debugging) call print_r or var_dump on $_GET


Let's do an exercise together:
Add a parameter to Pascal's Triangle program: value of n for the last row.

Exercise Using Functions and Arrays

Write PHP code to produce output like the following. Below, I show the beginning and end of the page it produces. My entire well-formatted PHP file is 35 lines long. I strongly recommend that you do pair programming with your partner.

99 bottles start 99 bottles end

Exercise: Traverse a Directory System

Write PHP code that recursively traverses a folder and all its subfolders, counting the number of files of a specic type (both the root folder and the type can be constants in your program)

mp3_count

Below I show some of my PHP code, all but the function body(mine is 11 lines long). Feel free to use this code or not. glob is useful; print and print_r can help with debuging. I strongly recommend that you do pair programming with your partner


mp3_count code 1
mp3_count code 2