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.
5.2: PHP Basic Syntax
-
5.1: Server-Side Basics
-
5.2: PHP Basic Syntax
-
5.3: Embedded PHP
-
5.4: Advanced PHP Syntax
-
6.1: Parameterized Pages
PHP syntax template
HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ...
- any contents of a
.php
file between <?php
and ?>
are executed as PHP code
- all other contents are output as pure HTML
- can switch back and forth between HTML and PHP "modes"
$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
math constants
M_PI
|
M_E
|
M_LN2
|
- the syntax for method calls, parameters, returns is the same as Java
int
and float
types
$a = 7 / 2;
$b = (int) $a;
$c = round($a);
$d = "123";
$e = (int) $d;
int
for integers and float
for reals
- division between two
int
values can produce a float
String
type
(5.2.6)
$favorite_food = "Ethiopian";
print $favorite_food[2];
$favorite_food = $favorite_food . " cuisine";
print $favorite_food;
- zero-based indexing using bracket notation
-
there is no
char
type; each letter is itself a String
- string concatenation operator is
.
(period), not +
5 + "2 turtle doves" === 7
5 . "2 turtle doves" === "52 turtle doves"
- can be specified with
""
or ''
String
functions
$name = "Stefanie Hatcher";
$length = strlen($name);
$cmp = strcmp($name, "Brian Le");
$index = strpos($name, "e");
$first = substr($name, 9, 5);
$name = strtoupper($name);
bool (Boolean) type
(5.2.8)
$feels_like_summer = FALSE;
$php_is_rad = TRUE;
$student_count = 217;
$nonzero = (bool) $student_count;
- the following values are considered to be
FALSE
(all others are TRUE
):
-
0
and 0.0
-
""
, "0"
, and NULL
(includes unset variables)
- arrays with 0 elements
- can cast to boolean using
(bool)
FALSE
prints as an empty string (no output); TRUE
prints as a 1
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";
}
- a variable is
NULL
if
- it has not been set to any value (undefined variables)
- it has been assigned the constant
NULL
- it has been deleted using the
unset
function
- can test if a variable is
NULL
using the isset
function
NULL
prints as an empty string (no output)
$name = array();
$name = array(value0, value1, ..., valueN);
$name[index]
$name[index] = value;
$name[] = value;
$a = array();
$a[0] = 23;
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!";
- to append, use bracket notation without specifying an index
- element type is not specified; can mix types
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]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
-
the array in PHP replaces many other collections in Java
-
list, stack, queue, set, map, ...
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";
}
- a convenient way to loop over each element of an array without indexes
5.4: PHP File Input
-
5.1: Server-Side Basics
-
5.2: PHP Basic Syntax
-
5.3: Embedded PHP
-
5.4: Advanced PHP Syntax
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",
"how r u?\n",
"\n",
"I'm fine\n"
)
|
"Hello\n
how r u?\n
\n
I'm fine\n"
|
file
returns lines of a file as an array (\n
at end of each)
file_get_contents
returns entire contents of a file as a single string
The file
function
$lines = file("todolist.txt");
foreach ($lines as $line) {
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");
...
-
the odd
list
function "unpacks" an array into a set of variables you declare
-
when you know a file's exact length/format, use
file
and list
to unpack it
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
can accept a general path with the *
wildcard character
glob
example
$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";
}
-
glob
can match a "wildcard" path with the *
character
-
glob("foo/bar/*.doc")
returns all .doc
files in the foo/bar
subdirectory
-
glob("food*")
returns all files whose names begin with "food"
-
the
basename
function strips any leading directory from a file path
-
basename("foo/bar/baz.txt")
returns "baz.txt"
scandir
example
<ul>
<?php
$folder = "taxes/old";
foreach (scandir($folder) as $filename) {
print "<li>$filename</li>\n"
}
?>
</ul>
-
.
-
..
-
2007_w2.pdf
-
2006_1099.doc
scandir
sucks; current directory ("."
) and parent (".."
) are included in the array
-
don't need
basename
with scandir
; returns file names only without directory