Web Programming Step by Step, 2nd Edition

Lecture 7: File I/O

Reading: 5.4.1–5.4.5

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 HTML5 Valid CSS

5.4: Advanced PHP Syntax

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

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"

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

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

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

5.4: Including Files

Common site HTML/code

screenshot screenshot

Including files: include

include("filename");
include("header.html");      // repeated HTML content
include("shared-code.php");  // repeated PHP code

Including a common HTML file

<!DOCTYPE html>
<!-- this is top.html -->
<html><head><title>This is some common code</title>
...
include("top.html");      // this PHP file re-uses top.html's HTML content

Including a common PHP file

<?php
// this is common.php
function useful($x) { return $x * $x; }

function top() {
	?>
	<!DOCTYPE html>
	<html><head><title>This is some common code</title>
	...
	<?php
}
include("common.php");   // this PHP file re-uses common.php's PHP code
$y = useful(42);         // call a shared function
top();                   // produce HTML output
...