[go: up one dir, main page]

0% found this document useful (0 votes)
419 views62 pages

Working With Files and Directories: Chapter 11

This document provides an overview of working with files and directories in PHP. It discusses PHP functions for getting information about files such as file_exists() and filesize() to check if a file exists and get its size. It also covers functions for getting time-related file properties like last modified, accessed, and changed times. The document shows how to retrieve just the filename from a file path using basename() and how to open files using file handles for reading and writing file contents.

Uploaded by

Abdelahad Satour
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
419 views62 pages

Working With Files and Directories: Chapter 11

This document provides an overview of working with files and directories in PHP. It discusses PHP functions for getting information about files such as file_exists() and filesize() to check if a file exists and get its size. It also covers functions for getting time-related file properties like last modified, accessed, and changed times. The document shows how to retrieve just the filename from a file path using basename() and how to open files using file handles for reading and writing file contents.

Uploaded by

Abdelahad Satour
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

20/12/2014 Microsoft, 

Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

(http://www.ucertify.com/)

 
Chapter 11

Working with Files and
Directories
  As a server­side programming language, PHP allows you to work with files and
directories stored on the Web server. This is very useful, because it means your
PHP scripts can store information outside the scripts themselves.

Files are stored in directories on a hard drive, and because they retain their data
after the computer is shut down, they are a persistent storage mechanism, instead
of temporary storage such as RAM. Directories are a special kind of file made for
storing other files. Directories are created hierarchically inside other directories,
starting with the root (top­level) directory and proceeding down from there.

Files can contain any kind of data, and also can contain quite a bit of information
about themselves, such as who owns them and when they were created. PHP
makes working with the file system easy by including functions that allow you to
obtain information about files, as well as open, read from, and write to them.

This chapter is all about the PHP functions for working with the file system. You
learn:
More about files and directories, and how to find out more information about
them in your scripts
How to open and close files, as well as how to read data from, and write data
to, files
The concept of file permissions and how to work with them
How to copy, move, and delete files
All about working with directories, including reading their contents, creating
them, and deleting them
As well as learning the theory of file and directory handling, you get to write a script

http://www.ucertify.com/?func=ebook&chapter_no=11#top 1/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

that can move through a directory tree, listing all the files and directories it finds as it
goes. You also create a simple Web­based text editor to illustrate many of the
points covered in the chapter.

 
11.1 Understanding Files and
Directories
Everything on your hard drive is stored as a file of one kind or another, although
most folks think in terms of files and directories. There are ordinary program files,
data files, files that are directories, and special files that help the hard drive keep
track of the contents of folders and files. PHP has functions that can work with any
file type, but typically you'll be working with text files that contain data.

The terms "directory" and "folder" are used interchangeably in this book (and in the
PHP community); they mean exactly the same thing.

A file is nothing more than an ordered sequence of bytes stored on a hard disk or
other storage media. A directory is a special type of file that holds the names of the
files and directories inside the folder (sometimes denoted as subdirectories or
subfolders) and pointers to their storage areas on the media.

Many differences exist between UNIX­based and Windows operating systems, one
of them being the way directory paths are specified. UNIX­based systems such as
Linux use slashes to delimit elements in a path, like this:

/home/matt/data/data.txt

Windows uses backslashes:

C:\MyDocs\data\data.txt

Fortunately, PHP on Windows automatically converts the former to the latter in most
situations, so you can safely use slashes in your script, regardless of the operating
system that the script is running on. Occasionally, though, backslashes are
necessary. In this situation, you need to use two backslashes in a row, because
PHP interprets a backslash as escaping the following character:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 2/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

"C:\\MyDocs\\data\\data.txt"

 
11.2 Getting Information on Files
PHP provides functions that enable you to access useful file information. For
example, you can use file_exists() to discover whether a file exists before
attempting to open it:

file_exists( "/home/chris/myfile.txt" )

file_exists() returns true if the file at the specified path exists, or false otherwise.

In a similar fashion, you can use the filesize() function to determine the size of a file
on the hard disk. Just as with file_exists(), this function takes a filename as an
argument:

filesize( "/home/chris/myfile.txt" )

This returns the size of the specified file in bytes, or false upon error.

 
Time­Related Properties
Besides their contents, files have other properties that can provide useful
information. The available properties depend on the operating system in which the
files are created and modified. On UNIX platforms such as Linux, for example,
properties include the time the file was last modified, the time it was last accessed,
and the user permissions that have been set on the file.

PHP provides three time­related file functions:

fileatime() — Returns the time at which the file was last accessed as a
UNIX timestamp. A file is considered accessed if its contents are read
filectime() — Returns the time at which the file was last changed as a UNIX
timestamp. A file is considered changed if it is created or written, or when its
permissions have been changed
filemtime() — Returns the time at which the file was last modified as a UNIX
timestamp. The file is considered modified if it is created or has its contents

http://www.ucertify.com/?func=ebook&chapter_no=11#top 3/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

changed
A UNIX timestamp is an integer value indicating the number of seconds between
the UNIX epoch (midnight on January 1, 1970) and the specified time and date.

The getdate() function is very useful when working with UNIX timestamps. It
returns an associative array containing the date information present in a timestamp.
The array includes such values as the year, the month, the day of the month, and so
on. For example, you can set a variable such as $myDate to the value returned by 
getdate(), and then access the month component with $myDate["month"].

Find out more about working with dates and times in Chapter 16.

 
Retrieving a Filename from a Path
It's often very useful to be able to separate a filename from its directory path, and
the basename() function does exactly that, taking a complete file path and returning
just the filename. For example, the following code assigns index.html to $filename:

$filename = basename( "/home/james/docs/index.html" );

You can specify a directory path instead, in which case the rightmost directory name
is returned. Here's an example that assigns the value docs to $dir:

$dir = basename( "/home/james/docs" );

Basically, basename() retrieves the last whole string after the rightmost slash.

If you don't want the filename extension, or suffix, you can strip that off too by
supplying the suffix as a second argument to basename(). The following example
assigns "myfile" to $filename:

$filename = basename( "/home/james/docs/myfile.doc", ".doc" );

 
11.3 Opening and Closing Files
Usually, to work with a file from within your PHP script, you first need to open the

http://www.ucertify.com/?func=ebook&chapter_no=11#top 4/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

file. When you open a file, you create a file handle. A file handle is a pointer
associated with the open file that you can then use to access the file's contents.
When you've finished with the file, you close it, which removes the file handle from
memory.
In the next sections you will look at opening files with the fopen() function, and
closing files with fclose().

 
Opening a File with fopen()
The fopen() function opens a file and returns a file handle associated with the file.
The first argument passed to fopen() specifies the name of the file you want to
open, and the second argument specifies the mode, or how the file is to be used.
For example:

$handle = fopen( "./data.txt", "r" );

The first argument can be just a filename ("data.txt"), in which case PHP will look for
the file in the current directory, or it can be a relative ("./data.txt") or absolute
("/myfiles/data.txt") path to a file. You can even specify a file on a remote Web or
FTP server, as these examples show:

$handle = fopen( "http://www.example.com/index.html", "r" );
$handle = fopen( "ftp://ftp.example.com/pub/index.txt", "r" );

A remote file can only be opened for reading — you can't write to the file.

Note: If you're not familiar with command­line file operations, you might be a little
confused by the concept of a current directory and the relative path notation.

Usually, the current directory is the same directory as the script, but you can change
this by calling chdir(). This is covered later in the chapter.

Within a relative path, a dot (.) refers to the current directory, and two dots (..) refer
to the immediate parent directory. For example, ./data.txt points to a file called
data.txt in the current directory, and ../data.txt points to a file called data.txt in the
directory above the current directory. ../../../data.txt backs up the directory tree three
levels before looking for the data.txt file.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 5/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Meanwhile, an absolute path is distinguished by the fact that it begins with a /
(slash), indicating that the path is relative to the root of the file system, not to the
current directory. For example, /home/chris/website/index.php is an absolute path.
The second argument of fopen() function tells PHP how you're going to use the file.
It can take one of the following string values:

Value Description

r Open the file for reading only. The file pointer is placed at the beginning
of the file.

r+ Open the file for reading and writing. The file pointer is placed at the
beginning of the file.

w Open the file for writing only. Any existing content will be lost. If the file
does not exist, PHP attempts to create it.

w+ Open the file for reading and writing. Any existing file content will be lost.
If the file does not exist, PHP attempts to create it.

a Open the file for appending only. Data is written to the end of an existing
file. If the file does not exist, PHP attempts to create it.

a+ Open the file for reading and appending. Data is written to the end of an
existing file. If the file does not exist, PHP attempts to create it.

Note: The file pointer is PHP's internal pointer that specifies the exact character
position in a file where the next operation should be performed.

You can also append the value b to the argument to indicate that the opened file
should be treated as a binary file (this is the default setting). Alternatively, you can
append t to treat the file like a text file, in which case PHP attempts to translate end­
of­line characters from or to the operating system's standard when the file is read or
written. For example, to open a file in binary mode use:

$handle = fopen( "data.txt", "rb" );

Although this flag is irrelevant for UNIX­like platforms such as Linux and Mac OS X,
which treat text and binary files identically, you may find the text mode useful if

http://www.ucertify.com/?func=ebook&chapter_no=11#top 6/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

you're dealing with files created on a Windows computer, which uses a carriage
return followed by a line feed character to represent the end of a line (Linux and the
Mac just use a line feed).

That said, binary mode is recommended for portability reasons. If you need your
application's data files to be readable by other applications on different platforms,
you should use binary mode and write your code to use the appropriate end­of­line
characters for the platform on which you are running. (The PHP constant PHP_EOL
is handy for this; it stores the end­of­line character(s) applicable to the operating
system that PHP is running on.)

By default, if you specify a filename that isn't a relative or absolute path (such as
"data.txt"), PHP just looks in the current (script) directory for the file. However, you
can optionally pass the value true as a third argument to fopen(), in which case PHP
will also search the include path for the file.

Find out more about include paths in Chapter 20.

If a problem is occurred while opening a file, fopen() returns false rather than a file
handle resource. Operations on files and directories are prone to errors, so you
should always allow for things to go wrong when using them. It's good practice to
use some form of error­checking procedure so that if an error occurs (perhaps you
don't have necessary privileges to access the file, or the file doesn't exist), your
script will handle the error gracefully. For example:

1.  if ( !( $handle = fopen( "./data.txt", "r" ) ) )
2.   die( "Cannot open the file" );

Rather than exiting with die(), you might prefer to raise an error or throw an
exception. Find out more about error handling in Chapter 20.

 
Closing a File with fclose()
Once you've finished working with a file, it needs to be closed. You can do this using
fclose(), passing in the open file's handle as a single argument, like this:

fclose( $handle );

http://www.ucertify.com/?func=ebook&chapter_no=11#top 7/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Although PHP should close all open files automatically when your script terminates,
it's good practice to close files from within your script as soon as you're finished with
them because it frees them up quicker for use by other processes and scripts — or
even by other requests to the same script.

 
Video: Files and File system functions

 
11.4 Reading and Writing to Files
Now that you know how to open and close files, it's time to take a look at reading
and writing data in a file. In the following sections you learn about these functions:

fread() — Reads a string of characters from a file
fwrite() — Writes a string of characters to a file
fgetc() — Reads a single character at a time
feof() — Checks to see if the end of the file has been reached
fgets() — Reads a single line at a time
fgetcsv() — Reads a line of comma­separated values
file() — Reads an entire file into an array
file_get_contents() — Reads an entire file into a string without needing to
open it

http://www.ucertify.com/?func=ebook&chapter_no=11#top 8/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

file_put_contents() — Writes a whole string to a file without needing to
open it
fpassthru() — Displays the contents of an open file
readfile() — Displays the contents of a file without needing to open it
fseek() — Moves the file pointer to a specific location within an open file
ftell() — Returns the position of the file pointer
rewind() — Moves the file pointer to the start of the file

As you can see, PHP gives you many different ways to read and write to files, so
you can always find a function to suit your needs!

 
Reading and Writing Strings of Characters
The fread() function can be used to read a string of characters from a file. It takes
two arguments: a file handle and the number of characters to read. The function
reads the specified number of characters (or less if the end of the file is reached)
and returns them as a string. For example:

1.  $handle = fopen( "data.txt", "r" );
2.  $data = fread( $handle, 10 );

This code reads the first ten characters from data.txt and assigns them to $data as
a string.

Note: When working with binary files a character is always one byte long, so ten
characters equals ten bytes. However, this doesn't apply when working with
Unicode files, where each character may take up several bytes. In this case,
reading ten characters may in fact result in reading, say, twenty bytes from the file.

After fread() has finished executing, the file pointer, which holds the current position
in the file, moves forward in the file by the number of characters read. So, after the
previous example code runs, the file pointer moves forward to ten characters after
the start of the file. If you repeat the same call to fread(), you'll get the next ten
characters in the file. If there are less than ten characters left to read in the file,
fread() simply reads and returns as many as there are. By the way, if you want to
read only one character at a time you can use the fgetc() function. fgetc() takes a
single argument — a file handle — and returns just one character from the file it
points to; it returns false when it reaches the end of the file:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 9/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

$one_char = fgetc( $handle );

However, fgetc() is slow when working with large files. It's faster to read a bunch of
characters at once using fread(), or one of the other file­reading functions
mentioned in this chapter.

You can use the fwrite() function to write data to a file. It requires two arguments: a
file handle and a string to write to the file. The function writes the contents of the
string to the file, returning the number of characters written (or false if there's an
error). For example:

1.  $handle = fopen( "data.txt", "w" );
2.  fwrite( $handle, "ABCxyz" );

The first line opens the file data.txt for writing, which erases any existing data in the
file. (If the file doesn't exist, PHP attempts to create it.) The second line writes the
character string "ABCxyz" to the beginning of the file. As with fread(), the file pointer
moves to the position after the written string; if you repeat the second line, fwrite()
appends the same six characters again, so that the file contains the characters
"ABCxyzABCxyz".

You can limit the number of characters written by specifying an integer as a third
argument. The function stops writing after that many characters (or when it reaches
the end of the string, whichever occurs first). For example, the following code writes
the first four characters of "abcdefghij" (that is, "abcd") to the file:

fwrite( $handle, "abcdefghij", 4 );

Try It Out: A Simple Hit Counter

One very popular use for Web scripts is a hit counter, which is used to show
how many times a Web page has been visited and therefore how popular the
Web site is. Hit counters come in different forms, the simplest of which is a text
counter. Here's a simple script for such a counter:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 10/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
2.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
3.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en
" lang="en">
4.     <head>
5.       <title>Hit counter</title>
6.       <link rel="stylesheet" type="text/css" href="common
.css" />
7.     </head>
8.     <body>
9.       <h1>A simple hit counter</h1>
10.   <?php
11.   $counterFile = "./count.dat";
12.   if ( !file_exists( $counterFile ) ) {
13.     if ( !( $handle = fopen( $counterFile, "w" ) ) ) {
14.       die( "Cannot create the counter file." );
15.     } else {
16.       fwrite( $handle, 0 );
17.       fclose( $handle );
18.     }
19.   }
20.   if ( !( $handle = fopen( $counterFile, "r" ) ) ) {
21.     die( "Cannot read the counter file." );
22.   }
23.   $counter = (int) fread( $handle, 20 );
24.   fclose( $handle );
25.   $counter++;
26.   echo "<p>You're visitor No. $counter.</p>";
27.   if ( !( $handle = fopen( $counterFile, "w" ) ) ){
28.     die( "Cannot open the counter file for writing." );
29.   }
30.   fwrite( $handle, $counter );
31.   fclose( $handle );
32.   ?>
33.     </body>
34.   </html>

Save this script as hit_counter.php and give it a try. Figure 11­1 shows a sample
run.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 11/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Figure 11­1

To start with, you'll see "You're visitor No. 1." If you now reload the page, you'll
see the counter change to 2. Each time you reload, the counter increments by 1.

How It Works

After displaying a page header, the script stores the filename of the file that will
hold the hit count:

$counterFile = "./count.dat";

Next, the script checks to see if the counter file exists. If it doesn't, it is created
by opening the file for writing, writing a zero to it (thereby initializing the hit count
to zero), then closing it:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 12/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  if ( !file_exists( $counterFile ) ) {
2.     if ( !( $handle = fopen( $counterFile, "w" ) ) ) {
3.       die( "Cannot create the counter file." );
4.     } else {
5.       fwrite( $handle, 0 );
6.       fclose( $handle );
7.     }
8.   }
9.   //Next the counter file is opened for reading:
10.   if ( !( $handle = fopen( $counterFile, "r" ) ) ) {
11.     die( "Cannot read the counter file." );
12.   }

The script now uses the file handle to read the hit counter value from the open
file. As you can see, the script calls fread() to read up to 20 bytes from the data
file (enough to store a very large integer):

$counter = (int) fread( $handle, 20 );

Because fread() returns a string value, and the counter needs to be an integer
value, the return value is cast into an integer using (int). (See Chapter 3 for
more on type casting.)

The call to fclose() closes the file referenced by the file handle $handle, freeing
up the file for reading or writing by other processes:

fclose( $handle );

After closing the data file, the script increments the counter and tells the visitor
how many times the page has been accessed:

1.  $counter++;
2.  echo "<p>You're visitor No. $counter.</p>";

Next the script writes the new counter value back to the data file. To do this it
opens the file in write mode (w), then calls fwrite() to write the $counter

http://www.ucertify.com/?func=ebook&chapter_no=11#top 13/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

variable's value to the file, followed by fclose() to close the open file again:

1.  if ( !( $handle = fopen( $counterFile, "w" ) ) ){
2.     die( "Cannot open the counter file for writing." );
3.   }
4.   fwrite( $handle, $counter );
5.   fclose( $handle );

 
In­Action: File Input and Output

 
Testing for the End of a File
The feof() function serves a single, simple purpose: it returns true when the file
pointer has reached the end of the file (or if an error occurs) and returns false
otherwise. It takes just one argument — the file handle to test. Notice that feof() only
returns true once the script has tried to read one or more characters past the last
character in the file:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 14/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  // hello_world.txt contains the characters "Hello, world!"
2.   $handle = fopen( "hello_world.txt", "r" );
3.   $hello = fread( $handle, 13 );
4.   echo $hello . "<br />";          // Displays "Hello, world
!"
5.   echo feof( $handle ) . "<br />"; // Displays "" (false)
6.   $five_more_chars = fread( $handle, 5 );
7.   echo $five_more_chars . "<br />";  // Displays "" (or poss
ibly a newline)
8.   echo feof( $handle ) . "<br />"; // Displays "1" (true)
9.   fclose( $handle );

feof() is useful with fread() or fgetc() in a while loop when you don't know how long
the file is:

1.  // hello_world.txt contains the characters "Hello, world!"
2.   $handle = fopen( "hello_world.txt", "r" );
3.   $text = "";
4.   while ( !feof( $handle ) ) {
5.     $text .= fread( $handle, 3 );  // Read 3 chars at a time
6.   }
7.   echo $text . "<br />";          // Displays "Hello, world!
"
8.   fclose( $handle );

 
Reading One Line at a Time
Often it's useful to read text from a file one line at a time. A line is a nice
manageable chunk of text to process or display. For example, data files and
configuration files often contain one chunk of information per line, such as a data
record or a configuration setting.

To read a line of text from an open file, call the fgets() function, passing in the file
handle. The function reads from the current file pointer to the end of the current line,
and returns the read characters as a string (or false if there was a problem, such as
the end of the file being reached). Note that any end­of­line character (or
characters) at the end of the line is also included in the string.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 15/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

You can limit the number of characters read by passing in a second, integer
argument, in which case fgets() stops when it reaches that number of characters
minus one (unless the end of the line is reached first). It's a good idea to include this
argument when reading large files that might not contain line breaks.

The following example uses fgets() to read and display a three­line text file, one line
at a time. The while loop exits when fgets() returns false (which means it's reached
the end of the file):

1.  /*
2.     milton.txt contains:
3.       The mind is its own place, and in it self
4.       Can make a Heav'n of Hell, a Hell of Heav'n.
5.       What matter where, if I be still the same,
6.   */
7.   $handle = fopen( "milton.txt", "r" );
8.   $lineNumber = 1;
9.   while ( $line = fgets( $handle ) ) {
10.     echo $lineNumber++ . ": $line<br />";
11.   }
12.   fclose( $handle );

The code produces the following output:

1: The mind is its own place, and in it self
2: Can make a Heav'n of Hell, a Hell of Heav'n.
3: What matter where, if I be still the same,

 
Reading CSV Files
If you've ever done any work with importing and exporting data, you probably know
about the comma­separated­value (CSV) data format. (CSV even has its own file
extension: .csv.) In CSV files, each data record sits on its own line, and the fields
within each record are separated by commas. String values are often enclosed
within double quotes:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 16/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

"John","Smith",45
"Anna","Clark",37
"Bill","Murphy",32

To read CSV files, you can use fgetcsv(). This function reads a line of CSV­
formatted data from an open file starting from the position of the file pointer, and
puts the data it finds into an array, with one field value per array element. Once you
have an array of data you can easily manipulate it.

To call the fgetcsv() function, pass it the file handle of an open file. You can also
optionally specify:
The maximum number of characters to read. You can leave this value out, or
use 0, in which case PHP reads as many characters as necessary to read the
whole line. However, specifying a value makes the function slightly quicker
The delimiter that is used to separate each data value. The default is the
comma (,). If you're reading a tab­separated­value (TSV) file, specify "\t" (the
tab character) for this argument instead
The character that is used to enclose string values. The default is the double
quote (")
The character used to escape special characters. The default is the backslash
(\)
fgetcsv() returns false if there was a problem reading the line, or if the end of the file
has been reached.

The following code snippet shows how you might retrieve three lines of data from a
file in CSV format:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 17/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1. /*
2.    people.csv contains:
3.      "John","Smith",45
4.      "Anna","Clark",37
5.      "Bill","Murphy",32
6.  */
7.  $handle = fopen( "people.csv", "r" );
8.  while ( $record = fgetcsv( $handle, 1000 ) ) {
9.    echo "Name: {$record[0]} {$record[1]}, Age: {$record[2]}
<br />";
10.   }
11.   fclose( $handle );

This code displays:

Name: John Smith, Age: 45
Name: Anna Clark, Age: 37
Name: Bill Murphy, Age: 32

The str_getcsv() function is used to read CSV data from a string instead of from a
file. This is handy if you already have your CSV data in memory. For details see
http://www.php.net/manual/en/function.str­
getcsv.php(http://www.php.net/manual/en/function.str­getcsv.php).

 
Reading and Writing Entire Files
Writing code to read a file line by line, or string by string, can be tedious.
Fortunately, PHP provides you with some functions that can access the complete
contents of a file in one go. These include:
file() — For reading a whole file into an array, without needing to open it
file_get_contents() and file_put_contents() — For reading and writing the
contents of a file without needing to open it
fpassthru() — For displaying the contents of an open file
readfile() — For displaying the contents of a file without needing to open it
Note: Because these functions read the entire file into memory in one go, they
should really be used for relatively small files (a few MB at most). If you're working
with a 100MB text file, it's probably best to use fread() or fgets() to read and process

http://www.ucertify.com/?func=ebook&chapter_no=11#top 18/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

the file in chunks.

file() reads the contents of a file into an array, with each element containing a line
from the file. It takes just one argument — a string containing the name of the file to
read — and returns the array containing the lines of the file:

$lines = file( "/home/chris/myfile.txt" );

The newline character remains attached at the end of each line stored in the array.

Note: This function, like most of the others described in this section, doesn't require
you to specify a file handle. All you need to do is pass in the filename of the file to
read. The function automatically opens, reads, and, once it's done, closes the file.

You can optionally specify some useful flags as the second parameter to file():

Flag Description

FILE_USE_INCLUDE_PATH Look for the file in the include path (see Chapter
20 for more on include paths)

FILE_IGNORE_NEW_LINES Remove newline characters from the end of each
line in the array

FILE_SKIP_EMPTY_LINES Ignore empty lines in the file

As with other flags in PHP, you can combine any of these flags with the bitwise OR
operator (see Chapter 3 for details). For example, the following code looks for a file
in the include path and, when found, reads the file, ignoring any empty lines in the
file:

$lines = file( "myfile.txt", FILE_USE_INCLUDE_PATH | FILE_SKIP_EM
PTY_LINES );

As with fopen(), you can also use file() to fetch files on a remote host:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 19/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  $lines = file( "http://www.example.com/index.html" );
2.  foreach ( $lines as $line ) echo $line . "<br />";

A related function is file_get_contents(). This does a similar job to file(), but it returns
the file contents as a single string, rather than an array of lines. The end­of­line
characters are included in the string:

$fileContents = file_get_contents( "myfile.txt" );

If there was a problem reading the file, file_get_contents() returns false.

You can pass the FILE_USE_INCLUDE_PATH flag (described earlier) as the
second argument to file_get_contents().

You can also optionally pass in an offset and/or a length parameter to determine
where you want the file reading to start, and how many characters you want to read.
For example, the following code reads 23 characters from myfile.txt, starting at
character 17:

$fileContents = file_get_contents( "myfile.txt", null, null, 17, 
23 );

Note: The first null argument avoids setting the FILE_USE_INCLUDE_PATH
flag,  and the second null argument avoids setting a context. Contexts are out of the
scope of this book, but you can find out more about them in the online manual at
http://www.php.net/manual/en/stream.contexts.php(http://www.php.net/manual/en/st
ream.contexts.php).

file_put_contents() is the complement to file_get_contents(). As you'd imagine, it
takes a string and writes it to a file:

$numChars = file_put_contents( "myfile.txt", $myString );

The function returns the number of characters written, or false if there was a
problem. You can affect the behavior of the function by passing various flags as the

http://www.ucertify.com/?func=ebook&chapter_no=11#top 20/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

third argument. file_put_contents() supports the same flags as file_get_contents(),
as well as two additional flags:

Flag Description

FILE_APPEND If the file already exists, append the string to the end of the file,
rather than overwriting the file.

LOCK_EX Lock the file before writing to it. This ensures that other
processes can't write to the file at the same time.

You can also lock files that are opened using fopen(). To do this, use flock(). See
http://www.php.net/manual/en/function.flock.php(http://www.php.net/manual/en/func
tion.flock.php) for more details.

fpassthru() and readfile() both take a file and output its unmodified contents straight
to the Web browser. fpassthru() requires the handle of an open file to work with:

$numChars = fpassthru( $handle );

readfile() instead works on an unopened file:

$numChars = readfile( "myfile.txt" );

As you can see, both functions return the number of characters read (or false if
there was a problem). fpassthru() reads from the current file pointer position, so if
you've already read some of the file only the remaining portion of the file will be
sent.

You can make readfile() search the include path for the file by passing true as the
second argument. Incidentally, readfile() is handy for sending binary files — such as
images and PDF documents — to the Web browser for displaying or downloading.
You see an example of this in Chapter 16.

 
Random Access to File Data
Using the functions you've met so far, you can only manipulate data sequentially,

http://www.ucertify.com/?func=ebook&chapter_no=11#top 21/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

that is, in the same order that it is arranged in the file. However, sometimes you
need to skip around the contents of an open file. For example, you might want to
read a file once to search for a particular string, then return to the start of the file in
order to search for another string. Of course, this is easy if you've read the entire file
using, for example, file_get_contents(). However, this isn't practical for large files.

Fortunately, it's possible to move the file pointer around within an open file, so that
you can start reading or writing at any point in the file. PHP gives you three
functions that let you work with the file pointer:

fseek() — Repositions the file pointer to a specified point in the file
rewind() — Moves the file pointer to the start of the file
ftell() — Returns the current position of the file pointer

To use fseek(), pass the handle of the open file, and an integer offset. The file
pointer moves to the specified number of characters from the start of the file (use
zero to move the pointer to the first character). For example, the following code
moves the pointer to the eighth character in the file (that is, seven characters after
the first character) and displays the next five characters from that point:

1.  // hello_world.txt contains the characters "Hello, world!"
2.   $handle = fopen( "hello_world.txt", "r" );
3.   fseek( $handle, 7 );
4.   echo fread( $handle, 5 );  // Displays "world"
5.   fclose( $handle );

To specify how the offset is calculated, you can add a third optional argument
containing one of the following constants:

SEEK_SET — Sets the pointer to the beginning of the file plus the specified
offset (the default setting)
SEEK_CUR — Sets the pointer to the current position plus the specified offset
SEEK_END — Sets the pointer to the end of the file plus the specified offset (use
with a negative offset)
fseek() returns 0 if the pointer was successfully positioned, or ­1 if there was a
problem.

Note: You can't use this function with files on remote hosts opened via HTTP or FTP
(for example, fopen( "http://www.example.com/" )).

http://www.ucertify.com/?func=ebook&chapter_no=11#top 22/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

If you want to move the pointer back to the start of the file (a common occurrence),
a handy shortcut is the rewind() function. The following two lines of code both do the
same thing:

1.  fseek( $handle, 0 );
2.  rewind( $handle );

The ftell() function takes a file handle and returns the current offset (in characters) of
the corresponding file pointer from the start of the file. For example:

$offset = ftell( $handle );

As you saw earlier, the fpassthru() function outputs file data from the current file
position onward. If you have already read data from an open file but want to output
the file's entire contents, call rewind() first.

 
11.5 Working with File Permissions
File system permissions determine what different users can do with each file and
directory in the file system. For example, whereas one user might have permission
to read and write to a file, another user may only be allowed to read the file. A third
user might not even be allowed to do that.

Permissions generally won't affect you much when writing PHP scripts, because
PHP usually does the right thing behind the scenes. For example, if you create a
new file for writing, PHP automatically gives that file read and write permission for
the user that's running your PHP script (usually the Web server user). If you create
a new directory, PHP gives the directory read, write, and execute permission for all
users by default, meaning that anyone can create and delete files within that
directory.

In this section you explore PHP's chmod() function, which lets you change the mode
(permissions) of a file or directory. You also take a look at three PHP functions that
let you determine if a file or directory is readable, writable, or executable by the
current user.

 
Changing Permissions

http://www.ucertify.com/?func=ebook&chapter_no=11#top 23/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

PHP's chmod() function is used to change the mode, or permissions, of a file or
directory. It functions much like the UNIX chmod command.
To change a file's permissions with chmod(), pass it the filename and the new mode
to use. For example, to set a file's mode to 644, use:

chmod( "myfile.txt", 0644 );

Note: The 0 (zero) before the 644 is important, because it tells PHP to interpret the
digits as an octal number.

chmod() returns true if the permission change was successful, and false if it failed
(for example, you're not the owner of the file).

So how do file modes work? Here's a quick primer.

File modes are usually expressed as octal numbers containing three digits. The first
digit determines what the file's owner—usually the user that created the file — can
do with the file. The second digit determines what users in the file's group — again,
usually the group of the user that created the file — can do with it. Finally, the last
digit dictates what everyone else can do with the file.

The value of each digit represents the access permission for that particular class of
user, as follows:

Digit Value Permission

0 Cannot read, write to, or execute the file

1 Can only execute the file

2 Can only write to the file

3 Can write to and execute the file

4 Can only read the file

5 Can read and execute the file

6 Can read and write to the file

http://www.ucertify.com/?func=ebook&chapter_no=11#top 24/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

7 Can read, write to, and execute the file

Here are some commonly used examples to make the concept of file modes
clearer:

// Owner can read and write the file; everyone else can just read
 it:
 chmod( "myfile.txt", 0644 );
  
 // Everyone can read and write the file:
 chmod( "myfile.txt", 0666 );
  
 // Everyone can read and execute the file, but only the owner ca
n write to it:
 chmod( "myfile.txt", 0755 );
  
 // Only the owner can access the file, and they can only read an
d write to it:
 chmod( "myfile.txt", 0600 );

Note: You can only change the permissions of a file or directory if you own it, or if
you're the super­user (which is highly unlikely for PHP scripts running on a Web
server).

To read the files in a directory, you need to have both read and execute permissions
on that directory. Also, to create and delete files and subdirectories inside the
directory, you need to have write and execute permissions on the directory.

 
Checking File Permissions
Before you do something to a file in your script, it can be useful to know what kinds
of things your script can do with the file. PHP provides three handy functions to help
you out.
1.  is_readable()
2.  is_writable()
3.  is_executable()
To check if you're allowed to read a file, use is_readable(), passing in the filename
of the file to check. Similarly, you can check that you're allowed to write to a file with

http://www.ucertify.com/?func=ebook&chapter_no=11#top 25/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

is_writable(), and see if you can execute a file with is_executable(). Each function
returns true if the operation is allowed, or false if it's disallowed. For example:

1.  if ( is_readable( "myfile.txt" ) {
2.     echo "I can read myfile.txt";
3.   }
4.   if ( is_writable( "myfile.txt" ) {
5.     echo "I can write to myfile.txt";
6.   }
7.   if ( is_executable( "myfile.txt" ) {
8.     echo "I can execute myfile.txt";
9.   }

You can also use the fileperms() function to return an integer representing the
permissions that are set on a file or directory. For example, to print the octal value of
the permissions on a file you might use:

1.  chmod( "myfile.txt", 0644 );
2.  echo substr( sprintf( "%o", fileperms( "myfile.txt") ), ‐4 
);  // Displays "0644"

(The substr() function in above script is used to return just the last four digits,
because the other octal digits in the returned value aren't relevant.)

 
11.6 Copying, Renaming, and Deleting
Files
PHP also lets you copy, rename, and delete files. The functions to perform these
operations are copy(), rename(), and unlink(), respectively.

The copy() function takes two string arguments: the first argument is the path to the
file to copy, and the second argument is the path to copy it to. It returns true if the
file was successfully copied, or false if there was a problem copying the file. The
following example copies the source file copyme.txt to the destination file copied.txt
in the same folder:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 26/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

copy( "./copyme.txt", "./copied.txt" );

The rename() function is used to rename (or move) a file. It works in much the same
way as copy(). For example, to rename a file within a folder you could use:

rename( "./address.dat", "./address.backup" );

To move a file to a different folder, you might use:

rename( "/home/joe/myfile.txt", "/home/joe/archives/myfile.txt" )
;

The unlink() function lets you delete files from the server. To use it, pass the
filename of the file you want to delete. For example, if you wanted to say adiós to
the file trash.txt in the current directory, you could write:

unlink( "./trash.txt" );

copy(), rename(), and unlink() raise warning­level errors if the file or directory in
question can't be found. Make sure the file or directory exists first (for example, by
using file_exists()) to avoid such errors.

 
11.7 Working with Directories
PHP lets you work with directories in much the same way as files, using a variety of
equivalent functions. Some directory functions use a directory handle, whereas
others use a string containing the name of the directory with which you want to
work. A directory handle is similar to a file handle; it's a special variable pointing to a
directory, which you can obtain via the opendir() function:

$handle = opendir( "/home/james" );

If there's a problem opening the directory (for example, if the directory doesn't exist),
opendir() returns false instead of the directory handle. As you may have guessed,

http://www.ucertify.com/?func=ebook&chapter_no=11#top 27/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

you can close a directory by passing the directory handle to the function closedir():

closedir( $handle );

The readdir() function expects a directory handle for an opened directory, and
returns the filename of the next entry in the directory:

$filename = readdir( $handle );

Each directory contains a list of entries for each of the files and subdirectories inside
it, as well as entries for . (representing the directory) and .. (the parent of the
directory). PHP maintains an internal pointer referring to the next entry in the list,
just as a file pointer points to the position in a file where the next file operation
should occur.

Try It Out: List Directory Entries

Here's how to set up a loop to get all the files and folders inside a specified
directory. Save the following script as dir_list.php in your document root folder.
Now change the $dirPath variable in the file so that it contains the path to a real
directory on your Web server. Open the script's URL in your Web browser to test
it.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 28/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
2.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
3.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en
" lang="en">
4.     <head>
5.       <title>Listing the contents of a directory</title>
6.       <link rel="stylesheet" type="text/css" href="common
.css" />
7.     </head>
8.     <body>
9.       <h1>Listing the contents of a directory</h1>
10.   <?php
11.   $dirPath = "/home/matt/images";
12.   if ( !( $handle = opendir( $dirPath ) ) ) die( "Cannot 
open the directory." );
13.   ?>
14.       <p><?php echo $dirPath ?> contains the following fi
les and folders:</p>
15.       <ul>
16.   <?php
17.   while ( $file = readdir( $handle ) ) {
18.     if ( $file != "." && $file != ".." ) echo "<li>$file<
/li>";
19.   }
20.   closedir( $handle );
21.   ?>
22.       </ul>
23.     </body>
24.   </html>

Figure 11­2 shows an example result.

Figure 11­2

http://www.ucertify.com/?func=ebook&chapter_no=11#top 29/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

How It Works:

After displaying the page header and storing the path to the directory to scan in
the $dirPath variable, the script gets a handle on the directory:

if ( !( $handle = opendir( $dirPath ) ) ) die( "Cannot open th
e directory." );

If the directory was successfully opened, its name is displayed in the page and
an unordered list (ul) HTML element is started. Next the script uses readdir() to
loop through each entry in the directory and, as long as the entry isn't "." or "..",
display it. The loop exits when readdir() returns false, which occurs when the list
of entries is exhausted:

1.  while ( $file = readdir( $handle ) ) {
2.     if ( $file != "." && $file != ".." )
3.   echo "<li>$file</li>";
4.   }

Finally, the script calls closedir() to close the directory, then finishes off the
markup for the list and the page.

You can see that the returned filenames are not sorted in any way. To sort
them, first read the entries into an array:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 30/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  $filenames = array();
2.  while ( $file = readdir( $handle ) ) $filenames[] = $fil
e;
3.  closedir( $handle );

The $filenames array now contains every entry in the directory. Now you can
call sort() to arrange the array elements in ascending order, then loop through
the array displaying all except the "." and ".." entries:

1.  sort( $filenames );
2.   foreach ( $filenames as $file ) {
3.     if ( $file != "." && $file != ".." ) {
4.       echo "<li>$file</li>";
5.     }
6.   }

 
Other Directory Functions
Just as with files, PHP provides a range of ways to manipulate directories, including
the following functions:

rewinddir() — Moves the directory pointer back to the start of the list of
entries
chdir() — Changes the current directory
mkdir() — Creates a directory
rmdir() — Deletes a directory
dirname() — Returns the directory portion of a path

Resetting the Directory Pointer

The rewinddir() function resets PHP's internal pointer back to the first entry in a
given directory. This function is the directory counterpart to the rewind() function for
files. To use rewinddir(), pass an open directory handle to it, as follows:

rewinddir( $handle );

http://www.ucertify.com/?func=ebook&chapter_no=11#top 31/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Changing the Current Directory

The chdir() function call changes the current directory to a new directory:

chdir( "/home/matt/myfolder" );

The chdir() function returns true if PHP managed to change to the specified
directory, or false if there was an error (such as the directory not being found).

The current directory is the directory where PHP first looks for files. If you specify a
path that isn't an absolute or relative path, PHP looks for the file inside the current
directory. So the following code

1.  chdir( "/home/matt/myfolder" );
2.  $handle = fopen( "myfile.txt" );

opens the same myfile.txt file as:

$handle = fopen( "/home/matt/myfolder/myfile.txt" );

The current directory is also used as the base directory for relative file paths. For
example:

1.  chdir( "/home/joe/images" );
2.  $handle = fopen( "../myfile.txt" );  // Looks for myfile.tx
t in /home/joe

Usually the current directory defaults to the directory containing the running script.
You can retrieve the current directory by calling getcwd():

1.  chdir( "/home/matt/newfolder" );
2.  echo getcwd();  // Displays "/home/matt/newfolder"

Creating Directories

http://www.ucertify.com/?func=ebook&chapter_no=11#top 32/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

To create a new directory, call the mkdir() function, passing in the path of the
directory you want to create:

mkdir( "/home/matt/newfolder" );

Note that the parent directory has to exist already ("/home/matt" in the example just
shown) for the function to work. mkdir() returns true if the directory was created, or
false if there was a problem.

You can also set permissions for the directory at the time you create it by passing
the mode as the second argument. This works much like using chmod() — see the
"Changing Permissions" section earlier in the chapter for details. For example, the
following code creates a directory with read, write, and execute permissions granted
to all users:

mkdir( "/home/matt/newfolder", 0777 );

File and directory modes only work on UNIX systems such as Linux and Mac OS;
they have no effect when used on Windows machines.

Deleting Directories

The rmdir() function removes a given directory. The directory must be empty, and
you need appropriate permissions to remove it. For example:

rmdir( "/home/matt/myfolder" );

If PHP can't remove the directory — for example, because it's not empty — rmdir()
returns false; otherwise it returns true.

Getting the Directory Path

The dirname() function returns the directory part of a given path. It complements the
basename() function, which returns the filename portion of a given path (see the
section "Retrieving a Filename from a Path" earlier in the chapter).

http://www.ucertify.com/?func=ebook&chapter_no=11#top 33/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

For example:

1.  $path = "/home/james/docs/index.html";
2.  $directoryPath = dirname( $path );
3.  $filename = basename( $path );

After running this code, $directoryPath contains "/home/james/docs", and $filename
holds "index.html".

 
Working with Directory Objects
PHP offers an alternative object­oriented mechanism for working with directories:
the Directory class. To use it, first create a Directory object by calling the dir()
function with the name of the directory you want to work with, as follows:

$dir = dir( "/home/james/docs" );

The Directory object provides two properties: handle and path. These refer to the
directory handle and the path to the directory, respectively:

1.  echo $dir‐>handle . "<br />"; // Displays the directory han
dle
2.  echo $dir‐>path . "<br />";   // Displays "/home/james/docs
"

Note: You can use the handle property with other directory functions such as
readdir(), rewinddir(), and closedir(), just as if you were using a regular directory
handle.

The Directory object supports three methods — read(), rewind(), and close()—
which are functionally equivalent to readdir(), rewinddir(), and closedir(),
respectively. For example, you can rewrite the dir_list.php script from earlier in the
chapter using a Directory object:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 34/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
2.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
3.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" l
ang="en">
4.     <head>
5.       <title>Listing the contents of a directory</title>
6.       <link rel="stylesheet" type="text/css" href="common.cs
s" />
7.     </head>
8.     <body>
9.       <h1>Listing the contents of a directory</h1>
10.   <?php
11.   $dirPath = "/home/matt/images";
12.   $dir = dir( $dirPath );
13.   ?>
14.       <p><?php echo $dirPath ?> contains the following files
 and folders:</p>
15.       <ul>
16.   <?php
17.   while ( $file = $dir‐>read() ) {
18.     if ( $file != "." && $file != ".." ) echo "<li>$file</li
>";
19.   }
20.   $dir‐>close();
21.   ?>
22.       </ul>
23.     </body>
24.   </html>

 
Identifying a file: Directory or a Regular file
Often you need to know whether a particular file is a regular file or a directory. For
example, suppose you want to write some code that travels down through a tree of
folders. You'd need to detect when a file was actually a folder, so you could enter
the folder and continue working through the tree. By the same token, if you want to
display the files in a folder, you'd need to detect when a file is in fact a regular file.

Remember: both directories and regular files are all essentially files, but directories
are a special kind of file.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 35/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

PHP has two functions to help you test for a file or a directory:

is_dir() — Returns true if the given filename refers to a directory
is_file() — Returns true if the given filename refers to a regular file

Here's a simple example that determines if a file called myfile is a file or a directory:

1.  $filename = "myfile";
2.   if ( is_dir( $filename ) ) {
3.     echo "$filename is a directory.";
4.   } elseif ( is_file( $filename ) ) {
5.     echo "$filename is a file.";
6.   } else {
7.     echo "$filename is neither a directory nor a file.";
8.   }

Try It Out: Traversing a Directory Hierarchy

As you learned in Chapter 7, recursion is particularly useful when a script has to
perform repetitive operations over a set of data of unknown size, and traversing
a directory hierarchy is a very good example.

A directory may hold subdirectories as well as files. If you want to create a script
that lists all the files and subdirectories under a given directory — including
subdirectories of subdirectories, and so on — you need to write a recursive
function, as follows:
1.  Read the entries in the current directory.
2.  If the next entry is a file, display its name.
3.  If the next entry is a subdirectory, display its name, then call the function
recursively to read the entries inside it.
As you can see, the third step repeats the whole process by itself, when
necessary. The recursion continues until there are no more subdirectories left to
traverse.

To try out this technique, first save the following script as directory_tree.php.
Now change the $dirPath variable at the top of the script to point to a folder on
your Web server's hard drive, and open the script's URL in your Web browser.
You should see a page similar to Figure 11­3.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 36/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
2.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
3.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en
" lang="en">
4.     <head>
5.       <title>Listing the contents of a directory</title>
6.       <link rel="stylesheet" type="text/css" href="common
.css" />
7.     </head>
8.     <body>
9.       <h1>Listing the contents of a directory</h1>
10.   <?php
11.   $dirPath = "/home/matt/images";
12.   function traverseDir( $dir ) {
13.     echo "<h2>Listing $dir ...</h2>";
14.     if ( !( $handle = opendir( $dir ) ) ) die( "Cannot op
en $dir." );
15.     $files = array();
16.     while ( $file = readdir( $handle ) ) {
17.       if ( $file != "." && $file != ".." ) {
18.         if ( is_dir( $dir . "/" . $file ) ) $file .= "/";
19.         $files[] = $file;
20.       }
21.     }
22.     sort( $files );
23.     echo "<ul>";
24.     foreach ( $files as $file ) echo "<li>$file</li>";
25.     echo "</ul>";
26.     foreach ( $files as $file ) {
27.       if ( substr( $file, ‐1 )  == "/" ) traverseDir( "$d
ir/" . substr( $file,
28.   0, ‐1 ) );
29.     }
30.     closedir( $handle );
31.   }
32.   traverseDir( $dirPath );
33.   ?>
34.     </body>
35.   </html>

http://www.ucertify.com/?func=ebook&chapter_no=11#top 37/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Figure 11­3

How It Works:

The traverseDir() recursive function traverses the whole directory hierarchy
under a specified directory. First, the function displays the path of the directory it
is currently exploring. Then, it opens the directory with opendir():

1.  if ( !( $handle = opendir( $dir ) ) )
2.   die( "Cannot open $dir." );

Next the function sets up a $files array to hold the list of filenames within the
directory, then uses readdir() with a while loop to move through each entry in the
directory, adding each filename to the array as it goes ("." and ".." are skipped).
If a particular filename is a directory, a slash (/) is added to the end of the
filename to indicate to the user (and the rest of the function) that the file is in fact
a directory:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 38/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  $files = array();
2.   while ( $file = readdir( $handle ) ) {
3.      if ( $file != "." && $file != ".." ) {
4.         if ( is_dir( $dir . "/" . $file ) ) $file .= "/";
5.         $files[] = $file;
6.       }
7.   }

Now the array of filenames is sorted alphabetically to aid readability, and the
filenames are displayed in an unordered list:

1.  sort( $files );
2.  echo "<ul>";
3.  foreach ( $files as $file ) echo "<li>$file</li>";
4.  echo "</ul>";

The last part of the function loops through the array again, looking for any
directories (where the filename ends in a slash). If it finds a directory, the
function calls itself with the directory path (minus the trailing slash) to explore
the contents of the directory:

1.  foreach ( $files as $file ) {
2.   if ( substr( $file, ‐1 )  == "/" ) traverseDir( "$dir/"
 . substr( $file, 0, ‐1 ) );
3.     }

Finally, the directory handle is closed:

closedir( $handle );

The last line of code in the script kicks off the directory traversal, starting with
the path to the initial, topmost directory:

traverseDir( $dirPath );

http://www.ucertify.com/?func=ebook&chapter_no=11#top 39/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

 
11.8 Building a Text Editor
With the basics of PHP's file and directory handling capabilities under your belt, it's
time to create a simple Web­based text file editor application. The editor will display
a list of text files in a designated folder, inviting the user to edit a file by clicking its
name. The edit page will simply display the file's contents in an HTML text area
field, with buttons for saving changes or canceling edits.

The user will also be able to create new text files to work with. For the sake of
simplicity the editor will only handle text files with the .txt filename extension.

 
The Text Editor Script
Here's the code for the text editor. Save it as text_editor.php in your document root
folder:

1.  <?php
2.   define( "PATH_TO_FILES", "/home/matt/sandbox" );
3.   if ( isset( $_POST["saveFile"] ) ) {
4.     saveFile();
5.   } elseif ( isset( $_GET["filename"] ) ) {
6.     displayEditForm();
7.   } elseif ( isset( $_POST["createFile"] ) ) {
8.     createFile();
9.   } else {
10.     displayFileList();
11.   }
12.   function displayFileList( $message="" ) {
13.     displayPageHeader();
14.     if ( !file_exists( PATH_TO_FILES ) ) die( "Directory not
 found" );
15.     if ( !( $dir = dir( PATH_TO_FILES ) ) ) die( "Can't open
 directory" );
16.   ?>
17.       <?php if ( $message ) echo '<p class="error">' . $mess
age . '</p>' ?>
18.       <h2>Choose a file to edit:</h2>
19.       <table cellspacing="0" border="0" style="width: 40em; 

http://www.ucertify.com/?func=ebook&chapter_no=11#top 40/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

border: 1px solid
20.   #666;">
21.         <tr>
22.           <th>Filename</th>
23.           <th>Size (bytes)</th>
24.           <th>Last Modified</th>
25.         </tr>
26.   <?php
27.     while ( $filename = $dir‐>read() ) {
28.       $filepath = PATH_TO_FILES . "/$filename";
29.       if ( $filename != "." && $filename != ".." && !is_dir(
 $filepath ) &&
30.   strrchr( $filename, "." ) == ".txt" ) {
31.          echo '<tr><td><a href="text_editor.php?filename=' .
 urlencode(
32.   $filename ) . '">' . $filename . '</a></td>';
33.          echo '<td>' . filesize( $filepath ) . '</td>';
34.          echo '<td>' . date( "M j, Y H:i:s", filemtime( $fil
epath ) ) .
35.   '</td></tr>';
36.       }
37.     }
38.     $dir‐>close();
39.   ?>
40.       </table>
41.       <h2>...or create a new file:</h2>
42.       <form action="text_editor.php" method="post">
43.         <div style="width: 20em;">
44.           <label for="filename">Filename</label>
45.           <div style="float: right; width: 7%; margin‐top: 0
.7em;"> .txt</div>
46.           <input type="text" name="filename" id="filename" s
tyle="width: 50%;"
47.   value="" />
48.           <div style="clear: both;">
49.             <input type="submit" name="createFile" value="Cr
eate File" />
50.           </div>
51.         </div>
52.       </form>

http://www.ucertify.com/?func=ebook&chapter_no=11#top 41/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

53.     </body>
54.   </html>
55.   <?php
56.   }
57.   function displayEditForm( $filename="" ) {
58.     if ( !$filename ) $filename = basename( $_GET["filename"
] );
59.     if ( !$filename ) die( "Invalid filename" );
60.     $filepath = PATH_TO_FILES . "/$filename";
61.     if ( !file_exists( $filepath ) ) die( "File not found" )
;
62.     displayPageHeader();
63.   ?>
64.       <h2>Editing <?php echo $filename ?></h2>
65.       <form action="text_editor.php" method="post">
66.         <div style="width: 40em;">
67.           <input type="hidden" name="filename" value="<?php 
echo $filename ?>" />
68.           <textarea name="fileContents" id="fileContents" ro
ws="20" cols="80"
69.   style="width: 100%;"><?php
70.              echo htmlspecialchars( file_get_contents( $file
path ) )
71.           ?></textarea>
72.           <div style="clear: both;">
73.             <input type="submit" name="saveFile" value="Save
 File" />
74.             <input type="submit" name="cancel" value="Cancel
" style=
75.   "margin‐right: 20px;" />
76.           </div>
77.         </div>
78.       </form>
79.     </body>
80.   </html>
81.   <?php
82.   }
83.   function saveFile() {
84.     $filename = basename( $_POST["filename"] );
85.     $filepath = PATH_TO_FILES . "/$filename";

http://www.ucertify.com/?func=ebook&chapter_no=11#top 42/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

86.     if ( file_exists( $filepath ) ) {
87.       if ( file_put_contents( $filepath, $_POST["fileContent
s"] ) === false )
88.   die( "Couldn't save file" );
89.       displayFileList();
90.     } else {
91.       die( "File not found" );
92.     }
93.   }
94.   function createFile() {
95.     $filename = basename( $_POST["filename"] );
96.     $filename = preg_replace( "/[^A‐Za‐z0‐9_\‐ ]/", "", $fil
ename );
97.     if ( !$filename ) {
98.       displayFileList( "Invalid filename ‐ please try again"
 );
99.       return;
100.     }
101.     $filename .= ".txt";
102.     $filepath = PATH_TO_FILES . "/$filename";
103.     if ( file_exists( $filepath ) ) {
104.       displayFileList( "The file $filename already exists!" 
);
105.     } else {
106.       if ( file_put_contents( $filepath, "" ) === false ) di
e( "Couldn't create file" );
107.       chmod( $filepath, 0666 );
108.       displayEditForm( "$filename" );
109.     }
110.   }
111.   function displayPageHeader() {
112.   ?>
113.   <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
114.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
115.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" l
ang="en">
116.     <head>
117.       <title>A simple text editor</title>
118.       <link rel="stylesheet" type="text/css" href="common.cs
s" />

http://www.ucertify.com/?func=ebook&chapter_no=11#top 43/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

119.       <style type="text/css">
120.         .error { background: #d33; color: white; padding: 0.
2em; }
121.         th { text‐align: left; background‐color: #999; }
122.         th, td { padding: 0.4em; }
123.       </style>
124.     </head>
125.     <body>
126.       <h1>A simple text editor</h1>
127.   <?php
128.   }
129.   ?>

 
Testing the Editor
To try out your text editor, first create a folder somewhere on your Web server's
hard drive to store the text files. Give the Web server user permission to create files
in this folder. To do this on Linux and Mac OS X, open a terminal window, then
change to the parent folder and use the chmod command on the text file folder. For
example, if your text file folder was /home/matt/sandbox, you could type:

1.  $ cd /home/matt
2.  $ chmod 777 sandbox

If you're running a Windows Web server, see the "Changing Permissions" section
earlier in the chapter for details on how to change permissions. However, it's quite
likely that you won't need to change permissions for the script to work on Windows.

Once you've created your text files folder and given it appropriate permissions, you
need to tell the script about the new folder. To do this, set the PATH_TO_FILES
constant at the top of the script:

define( "PATH_TO_FILES", "/home/matt/sandbox" );

Now you're all set. Open the text editor script's URL in your Web browser and you
should see a page like Figure 11­4 (though it won't list any files at this stage). Enter
a new filename (minus the ".txt" extension) in the text field, and click Create File.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 44/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

You'll see a form like the one shown in Figure 11­5 appear; enter your text and click
Save File to save the changes to your new file. You can then reedit the file by
clicking its name in the list.

Figure 11­4

Figure 11­5

http://www.ucertify.com/?func=ebook&chapter_no=11#top 45/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

 
Examining the Editor Code
The text editor demonstrates many of the functions you've learned in this chapter,
and also illustrates some useful coding techniques. In the following sections you
explore the workings of each part of the text editor script, and take a look at how the
parts fit together to make the application work.

The Main Logic

The script kicks off by defining the path to the folder that will hold the text files. It
does this using a constant called PATH_TO_FILES:

define( "PATH_TO_FILES", "/home/matt/sandbox" );

The user will create and edit all his text files in this folder. For security reasons it's
important to make sure that the user isn't allowed to create or modify files outside
this folder, and you see how this is done in a moment.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 46/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Next comes the main decision logic of the script. This code examines the $_POST
and $_GET superglobal arrays and, depending on what field it finds, it calls an
appropriate function to handle the request:

1.  if ( isset( $_POST["saveFile"] ) ) {
2.     saveFile();
3.   } elseif ( isset( $_GET["filename"] ) ) {
4.     displayEditForm();
5.   } elseif ( isset( $_POST["createFile"] ) ) {
6.     createFile();
7.   } else {
8.     displayFileList();
9.   }

If the saveFile form field was submitted, the user wants to save his edits, so the 
saveFile() function is called. If the filename field was found in the query string, the
user has clicked a file to edit in the list; displayEditForm() is called to let the user
edit the file. If the createFile form field was found, the user has clicked the Create
File button to make a new file, so createFile() is called to create the new file.
Finally, if none of these fields exist, the file list is displayed by calling 
displayFileList().

The displayFileList() Function

When the user first runs the application, displayFileList() is called to display the list
of files to edit, along with a form field to allow the user to add a new file (Figure 11­
4). This function accepts one optional argument, $message, containing any error
message to display to the user in the form.

First the function calls the displayPageHeader() helper function (described in a
moment) to generate a standard page header. Next it checks that the text files
directory exists (if not, the script exits with an error message) and attempts to open
the directory and retrieve a Directory object by calling the dir() function (again, if
there's a problem the script exits):

http://www.ucertify.com/?func=ebook&chapter_no=11#top 47/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

displayPageHeader();
if ( !file_exists( PATH_TO_FILES ) ) die( "Directory not found" )
;
if ( !( $dir = dir( PATH_TO_FILES ) ) ) die( "Can't open director
y" );

After displaying any error message passed to the function, and kicking off an HTML
table to display the file list, the function uses a while construct along with calls to the
$dir­>read() method to loop through the entries in the text files directory. For each
entry, the script checks that the entry's filename is not "." or "..", and that the file isn't
a directory and its filename extension is ".txt". If the entry matches all these criteria,
it is displayed as a row in the table. Notice that the loop stores the complete path to
each file in a temporary $filepath variable for convenience:

1.  while ( $filename = $dir‐>read() ) {
2.   $filepath = PATH_TO_FILES . "/$filename";
3.   if ( $filename != "." && $filename != ".." && !is_dir( $fi
lepath ) && strrchr( $filename, "." ) == ".txt" ) {
4.    echo '<tr><td><a href="text_editor.php?filename=' . urlen
code( $filename ) . '">' . $filename . '</a></td>';
5.    echo '<td>' . filesize( $filepath ) . '</td>';
6.    echo '<td>' . date( "M j, Y H:i:s", filemtime( $filepath 
) ) . '</td></tr>';
7.       }
8.   }

To display each file in the table, the script wraps a link around the filename to allow
the user to edit the file. The link's URL includes the query string "?filename="
followed by the name of the file to edit. Notice that the filename is encoded in the
query string by passing it through the urlencode() function. The script also displays
the file's size by calling the filesize() function. Finally, the file's "last modified" time is
displayed by calling the filemtime() function and passing the resulting timestamp to
the date() function to format it.

Find out more about urlencode() in Chapter 10, and date() in Chapter 16.

Once the loop's finished, the function closes the directory and displays the form for
creating a new file. The form includes a filename text field and a createFile submit

http://www.ucertify.com/?func=ebook&chapter_no=11#top 48/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

button.

The displayEditForm() Function

When the user clicks a file to edit, the displayEditForm() function is called to display
the file contents for editing. This function can take an optional $filename argument
containing the filename of the file to edit; if this isn't passed, it looks up the filename
in the query string, passing it through basename() to ensure that no additional path
information is in the filename; this is a good security measure, because it thwarts
any attempt to edit files outside the designated folder. Furthermore, if the filename is
empty for some reason, the script exits with an error:

function displayEditForm( $filename="" ) {
 if ( !$filename ) $filename = basename( $_GET["filename"] );
 if ( !$filename ) die( "Invalid filename" );

Next the function stores the full path to the file in a $filepath variable (because this
path is needed many times in the function), and checks to make sure the file to edit
actually exists — if it doesn't, it exits with a "File not found" message:

$filepath = PATH_TO_FILES . "/$filename";
 if ( !file_exists( $filepath ) ) die( "File not found" );

The rest of the function calls displayPageHeader() to output the standard page
header markup, then displays the name of the file being edited, as well as the HTML
form for editing the file. The form consists of a hidden field storing the filename of
the file being edited; a text area for the file contents; and Save File and Cancel
buttons. The file's contents are displayed in the text area simply by calling
file_get_contents() and outputting the result.

Notice that the filename and fileContents field values are passed through PHP's
htmlspecialchars() function to encode characters such as &, <, and > in the markup.
This is a good security measure to take:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 49/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

<textarea name="fileContents" id="fileContents" rows="20" cols="8
0" style="width: 100%;">
 <?php
   echo htmlspecialchars( file_get_contents( $filepath ) )
 ?></textarea>

Note: You can find out more about htmlspecialchars(), and security in general, in
Chapter 20.

The saveFile() Function

The saveFile() function is called when the user sends back the edit form containing
the file contents. It reads the filename from the form data — passing the filename
through basename() to sanitize it — then stores the full path to the file in $filepath:

1.    $filename = basename( $_POST["filename"] );
2.    $filepath = PATH_TO_FILES . "/$filename";

Next, the function checks that the file exists; if so, it writes the file contents to the file
by calling file_put_contents(), then re­displays the file list page by calling
displayFileList(). If there was a problem, an appropriate error message is displayed
and the script exits. Notice that the function uses the === operator to test if the
return value of file_put_contents() exactly equals false. Merely using the == or !
operator wouldn't do the job. Why? Because file_put_contents() returns the number
of characters written if successful. Because this value will be zero if the file contents
happen to be empty, and 0 == false, using == or ! would incorrectly exit the script
with an error in this situation:

1.    if ( file_exists( $filepath ) ) {
2.       if ( file_put_contents( $filepath, $_POST["fileContent
s"] ) === false ) die( "Couldn't save file" );
3.       displayFileList();
4.     } else {
5.       die( "File not found" );
6.     }

Find out more on true, false, and the === operator in Chapter 3.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 50/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

The createFile() Function

If the user clicks the Create File button in the file list page, the createFile() function
is called to attempt to create the new file. The function reads and sanitizes the
filename field sent from the form. If the filename is empty, the file list page is
redisplayed with an error message:

1.    $filename = basename( $_POST["filename"] );
2.     $filename = preg_replace( "/[^A‐Za‐z0‐9_\‐ ]/", "", $fil
ename );
3.    
4.     if ( !$filename ) {
5.       displayFileList( "Invalid filename ‐ please try again"
 );
6.       return;
7.     }

Notice that the function uses a regular expression to strip all characters from the
filename except letters, digits, underscores, hyphens, and spaces. For security
reasons it's always good to restrict user input to a set of known safe characters
(without being too restrictive). You can find out more on regular expressions in
Chapter 18, and user input filtering and validation in Chapter 20.

Next the function appends a .txt extension to the end of the filename and sets the
$filepath variable to store the full path to the file:

1.    $filename .= ".txt";
2.    $filepath = PATH_TO_FILES . "/$filename";

The file path is then checked to make sure the file doesn't already exist; if it does,
the user is warned and the file isn't created:

1.    if ( file_exists( $filepath ) ) {
2.      displayFileList( "The file $filename already exists!" )
;

http://www.ucertify.com/?func=ebook&chapter_no=11#top 51/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

If the file doesn't exist, it is created by calling file_put_contents() with an empty
string for the file contents. (file_put_contents() automatically creates a file if it
doesn't already exist.) If file_put_contents() returns exactly false (tested with the
=== operator), the file can't be created and the script exits with an error:

1.    } else {
2.       if ( file_put_contents( $filepath, "" ) === false ) di
e( "Couldn't create file" );

Once the file has been created its permissions are set so that anyone can read and
write to the file. Finally, displayEditForm() is called, passing in the name of the
newly created file so the user can begin editing it:

1.  chmod( $filepath, 0666 );
2.  displayEditForm( "$filename" );

The displayPageHeader () Function

The displayPageHeader() utility function simply outputs the XHTML page header
common to all pages in the application. This saves having to include the markup
more than once in the script. As well as including the standard common.css style
sheet from Chapter 2, the header defines some extra CSS rules to style any error
messages and the file list table:

1.  <link rel="stylesheet" type="text/css" href="common.css" />
2.     <style type="text/css">
3.       .error { background: #d33; color: white; padding: 0.2e
m; }
4.       th { text‐align: left; background‐color: #999; }
5.       th, td { padding: 0.4em; }
6.     </style>

This text editor has used many of the file­related functions described in the chapter,
and has also demonstrated some important concepts such as security and error
handling. You can take many of these concepts and apply them to other Web
applications that you create.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 52/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

 
Streams
Streams are a way of generalizing file, network, data compression, and other
operations which share a common set of functions and uses. In a simple way,
stream is a resource object that exhibits streamable behavior. That is, it can be read
from or written to in a linear fashion, and may be able to seek to an arbitrary
locations within the stream using fseek(). Every stream also has an implementation
wrapper that has the additional code necessary to handle the specific protocol or
encoding.

A wrapper tells the stream how to handle specific protocols/encodings. For
example, the http wrapper knows how to translate a URL into an HTTP/1.0 request
for a file on a remote server.

 
Video: Streams

 
stream_copy_to_stream() function
The stream_copy_to_stream() function is used to copy data from one stream to
another. It is mainly useful in copying data between two open files. The syntax of
the stream_copy_to_stream() function is as follows:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 53/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

int stream_copy_to_stream ( resource $source , resource $dest [, 
int $maxlength = ‐1 [, int $offset = 0 ]] ) 

Here, if maxlength is not specified, the stream_copy_to_stream() function will copy
all data to the destination.

Example:

1.  <?php
2.   $src = fopen('http://www.google.com', 'r');
3.   $file1 = fopen('f1.txt', 'w');
4.   $file2 = fopen('ext.txt', 'w');
5.   echo stream_copy_to_stream($src, $file1, 1024) . " bytes c
opied to f1.txt<br />";
6.   echo stream_copy_to_stream($src, $file2) . " bytes copied 
to ext.txt\n";
7.   ?>

 
stream_set_timeout() function
The stream_set_timeout() function alters the amount of time PHP waits for a stream
before timing out during reading or writing. When the stream times out, the
'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE. It
denotes that the connection has timed out. The syntax of the stream_set_timeout()
function is as follows:

bool stream_set_timeout( resource $stream_name , int $number_seco
nds [, int $microseconds = 0 ] ) 

where $stream_name is the name of the target stream, $number_seconds denotes
the seconds part of the timeout to be set, and $microseconds denotes the
microseconds part of the timeout to be set.

 
Stream filters
Stream filters are the piece of code, which may perform operations on data as it is
being read from or written to a stream. You can add any number of stream filters.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 54/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

You can also define custom filters by using the stream_filter_register() function. You
can get the information about filters by using the stream_get_filters() function.

 
stream_get_filters() function
The stream_get_filters() function is used to retrieve the list of registered filters. The
example of stream_get_filters() is as follows:

1.  <?php
2.   $streamlist = stream_get_filters();
3.   print_r($streamlist);
4.   ?>

 
stream_get_line() function
The stream_get_line() function is used to retrieve a line from stream resource up to
a given delimiter. The stream_get_line() function works in the same manner as the
fgets() function, except in that it allows end of line delimiters other than the standard
\n, \n, and \n\n, and does not return the delimiter itself. The syntax of the
stream_get_line() function is as follows:

string stream_get_line ( resource $handle , int $length [, string
 $ending ] )

Example:

1.  <?php
2.   $myFile = "myfile.txt";
3.   $fhandle = fopen($myFile, 'r');
4.   $Data = stream_get_line($fhandle,4096,";");
5.   fclose($fhandle);
6.   echo $Data;
7.   ?>

 
Contexts
A context is a set of parameters and wrapper specific options, which is used to

http://www.ucertify.com/?func=ebook&chapter_no=11#top 55/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

modify the behavior of a stream. It can be created by using stream_context_create()
function. It can be passed to filesystem stream creation functions, such as, fopen(),
file(), file_get_contents(), etc.

 
stream_context_create() function
The stream_context_create function is used to create and return a stream context
with any options supplied in options preset. The syntax is:

resource stream_context_create ([ array $opt [, array $par ]])

Where, $opt must be an associative array of associative arrays in the format
$arr['wrapper']['option'] = $value, and $par must be an associative array in the
format $arr['parameter'] = $value.

The following example explains the working of the stream_context_create() function:

1.  <?php
2.   $opt = array(
3.   'http'=>array(
4.   'method'=>"GET",
5.   'header'=>"Accept‐language: en\n\n" .
6.   "Cookie: foo=bar\n\n"
7.   )
8.   );
9.   $context = stream_context_create($opt);
10.   $fo = fopen('http://www.ucertify.com', 'r', false, $contex
t);
11.   fpassthru($fo);
12.   fclose($fo);
13.   ?>

 
stream_set_write_buffer() function
The stream_set_write_buffer() function is used to set write file buffering on the given
stream. The following example is setting 1024 bytes for the buffer:

http://www.ucertify.com/?func=ebook&chapter_no=11#top 56/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

1.  <?php
2.   $file="name_of_the_file.txt";
3.   $fp = fopen($file, "w");
4.   if ($fp) 
5.   {
6.   stream_set_write_buffer($fp, 1024); //sets the buffer size
 to 1024 bytes
7.   fclose($fp);
8.   }
9.   ?>

 
11.9 Summary
In this chapter you learned how to work with files and explored PHP's various file­
handling functions. You looked at:
How files and directories work, and the differences between file paths on
UNIX­like servers and Windows servers
Retrieving information on files using file_exists(), filesize(), 
fileatime(), filectime(), filemtime(), basename(), and dirname()
Using fopen() and fclose() to open and close files for reading and writing
Reading and writing to files using fread(), fwrite(), fgetc(), feof(), 
fgets(), fgetcsv(), file(), file_get_contents(), 
file_put_contents(), fpassthru(), readfile(), fseek(), ftell(), and 
rewind()
Setting file permissions with chmod(), and checking permissions with 
is_readable(), is_writable(), and is_executable()
Copying files with copy(), renaming and moving files with rename(), and
deleting files with unlink()
Reading directories with opendir(), closedir(), readdir(), rewinddir(),
and dir()
Manipulating directories with chdir(), mkdir(), and rmdir()
Testing for files and directories with is_file() and is_dir()

Along the way you learned how to use recursion to move through a directory tree,
and you also built a simple text editor to illustrate many of the functions and
concepts covered in the chapter.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 57/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

Some functions rarely used in Web applications weren't discussed. For a full list of
PHP's file and directory functions, refer to the online PHP function list at:
http://www.php.net/manual/ref.filesystem.php(http://www.php.net/manual/ref.filesyst
em.php).

In the next chapter you are introduced to another popular way of storing application
data: databases. This is quite a big topic, so it's spread over the next three chapters.
Chapter 12 introduces the concept of databases; Chapter 13 shows how to read
data from a database; and Chapter 14 shows how to manipulate data in a database.

Before leaving this chapter, try the following exercise to test your knowledge of file
and directory handling in PHP. You can find the solution to this exercise in Appendix
A.

 
11.10 Exercise
Create a PHP application that can be used to find a particular directory by name
when given a top­level directory to search. Make the application look through the
given directory, as well as all directories under the given directory.

 
11.11 Exercise Solution
This solution uses recursion to drill down through all the subdirectories under the
top­level directory, looking for the searched folder. If the form has been posted
($_POST['posted'] is set), the script calls the recursive searchFolder() function,
supplying the top­level directory to begin the search from, the folder name to search
for, and a reference to an array to hold the matches. searchFolder() reads all the
entries in the current folder, and if it finds a folder, it searches it, and so on. Any
matching folders are added to the $matches array.

Finally, the script displays any matches, followed by the search form.

1.  <!DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 Strict//EN"
2.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1‐strict.dtd">
3.   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" l
ang="en">
4.     <head>
5.       <title><?php echo $pageTitle?></title>
6.       <link rel="stylesheet" type="text/css" href="common.cs
s" />

http://www.ucertify.com/?func=ebook&chapter_no=11#top 58/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

7.     </head>
8.     <body>
9.       <h1>Welcome to Beginning PHP, Chapter 11, Exercise 1</
h1>
10.   <?php
11.   define( "TOP_LEVEL_DIR", "." );
12.   if ( isset( $_POST['posted'] ) ) {
13.     // Get the folder to search for
14.     $folderName = isset( $_POST['folderName'] ) ? $_POST['fo
lderName'] : "";
15.     // Search for the folder
16.     echo "<p>Searching for '$folderName' in '" . TOP_LEVEL_D
IR . "' ...</p>";
17.     $matches = array();
18.     searchFolder( TOP_LEVEL_DIR, $folderName, $matches );
19.     // Display any matches
20.     if ( $matches ) {
21.       echo "<h2>The following folders matched your search:</
h2>\n<ul>\n";
22.       foreach ( $matches as $match ) echo ( "<li>$match</li>
" );
23.       echo "</ul>\n";
24.     } else {
25.       echo "<p>No matches found.</p>";
26.     }
27.   }
28.   /**
29.   * Recursively searches a directory for a subdirectory
30.   *
31.   * @param string The path to the directory to search
32.   * @param string The subdirectory name to search for
33.   * @param stringref The current list of matches
34.   */
35.   function searchFolder( $current_folder, $folder_to_find, &
$matches )
36.   {
37.     if ( !( $handle = opendir( $current_folder ) ) ) die( "C
annot open $current_
38.   folder." );
39.     while ( $entry = readdir( $handle ) ) {

http://www.ucertify.com/?func=ebook&chapter_no=11#top 59/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

40.       if ( is_dir( "$current_folder/$entry" ) ) {
41.         if ( $entry != "." && $entry != ".." ) {
42.           // This entry is a valid folder
43.           // If it matches our folder name, add it to the li
st of matches
44.           if ( $entry == $folder_to_find ) $matches[] = "$cu
rrent_folder/$entry";
45.           // Search this folder
46.           searchFolder( "$current_folder/$entry", $folder_to
_find, $matches );
47.         }
48.       }
49.     }
50.     closedir( $handle );
51.   }
52.   // Display the search form
53.   ?>
54.       <form method="post" action="">
55.         <div>
56.           <input type="hidden" name="posted" value="true" />
57.           <label>Please enter the folder to search for:</lab
el>
58.           <input type="text" name="folderName" />
59.           <input type="submit" name="search" value="Search" 
/>
60.         </div>
61.       </form>
62.     </body>
63.   </html>

Glossary
 
chmod()
This function is used to change the mode, or permissions, of a file or directory.

 
Contexts
A context is a set of parameters and wrapper specific options that are used to
modify the behavior of a stream.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 60/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

 
CSV data format
Comma­separated­value data format

 
CSV files
In CSV files, each data record sits on its own line, and the fields within each record
are separated by commas.

 
Directory
A directory is a special type of file that holds the names of the files and directories
inside the folder and pointers to their storage areas on the media.

 
fclose
fclose is used to close a file/resource.

 
File

A file is nothing more than an ordered sequence of bytes stored on a hard disk or
other storage media.

 
file pointer
The file pointer is PHP's internal pointer that specifies the exact character position in
a file where the next operation should be performed.

 
fopen
fopen is used to open a file/resource.

 
fread()
This function reads a string of characters from a file.

 
fwrite()
This function writes a string of characters to a file.

http://www.ucertify.com/?func=ebook&chapter_no=11#top 61/62
20/12/2014 Microsoft, Oracle, OCP, CompTIA, A+, MCSE, CCNA, PMP, PHP Courses & Labs ­uCertify

rewind()
This function moves the file pointer to the start of the file.

Next Steps
1.  Study flashcards to ensure your understanding of
the material(http://www.ucertify.com/?
func=get_flash_card&item_sequence=1&chapter_guid=01ovA)
Open(http://www.ucertify.com/?func=get_flash_card&item_sequence=1&chapter_guid=01ovA)

2.  Quiz yourself to check your understanding of
fundamental facts(http://www.ucertify.com/?
func=start_test&test_type=­3&parent_guid=01ovA)
Open(http://www.ucertify.com/?func=start_test&test_type=­3&parent_guid=01ovA)
3.  Do the
exercises to practice and apply
concepts(http://www.ucertify.com/?
func=custom_test&parent_guid=01ovA)
Open(http://www.ucertify.com/?func=custom_test&parent_guid=01ovA)
4.  Proceed to the
next chapter(http://www.ucertify.com/?
func=ebook&chapter_no=11&useraction=next)
Open(http://www.ucertify.com/?func=ebook&chapter_no=11&useraction=next)

http://www.ucertify.com/?func=ebook&chapter_no=11#top 62/62

You might also like