Web Programming Step by Step

Lecture 7
More PHP; File I/O

Reading: 5.2, 5.4

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

Valid XHTML 1.1 Valid CSS!

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

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

$favorite_food = $favorite_food . " cuisine";
print $favorite_food;               # Ethiopian cuisine

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

NULL

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

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

5.4: PHP File Input

PHP file I/O functions (5.4.5)

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