. 33
( 132 .)


tories on the host computer. In the course of creating applications for this book, we
encountered only one instance in which files needed to be written to or taken from
the file system: in the Catalog and Shopping Cart applications, when we needed to
provide the user with the ability to store images that have been uploaded. But if
you work with PHP frequently there™s little doubt that you will need to become
familiar with these functions. By way of introduction, we will say that the directory
and file-system functions in PHP are simply terrific. The PHP developers have
really done a great job of making working with files, either on the local system or
elsewhere on the Internet, a piece of cake. Just to give a quick example, it took
about two minutes to write the following script, which will grab a stock quote from
a site we will not specify for legal reasons.

$farray = file(“http://domain.com/stockquote?symbols=ORCL”, “r”);
foreach ($farray as $value)
if( ereg(“last:.*$”, $value) )
$value = strip_tags($value);


This brief script slurps up an entire page and assigns each line to an element in
the $farray. We then loop through the array looking for the string last. On the
site we played with, the word “last” indicates the most recent quote. All we had to
do was strip the HTML tags, and we had all the information we needed. If we had
wanted to, we could have done some more string processing to format the informa-
tion in a way we liked.
Chapter 6: PHP™s Built-in Functions 171

If you would like to see these in use, check out Chapters 12 and 14.

FOPEN() This function opens a file pointer to the indicated file or URL in the first
argument. (The pointer is very much like the result identifier returned by

int fopen (string filename, string mode [, int use_include_path])

The mode determines what you can do with the file. Table 6-2 shows the avail-
able modes.


Mode Meaning

Open for reading only; place the file pointer at the beginning of the file.

Open for reading and writing; place the file pointer at the beginning of the file.

Open for writing only; place the file pointer at the beginning of the file and
truncate the file to zero length. If the file does not exist, attempt to create it.
Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file does not exist, attempt to create it.
Open for writing only; place the file pointer at the end of the file. If the file does
not exist, attempt to create it.
Open for reading and writing; place the file pointer at the end of the file. If the
file does not exist, attempt to create it.

Note that this function returns a resource identifier. If you wish to read from or
write to a file you will need to do something like this:

//open a file and read contents into a variable
$fp = fopen($filename, “r+”) or
die(“could not open $filename”);
$contents = fread ($fp, filesize($filename));
//replace all occurrences of Jayson
$new_contents = str_replace(“Jayson”, “Jay”, $contents);
//write out new file contents.
172 Part II: Working with PHP

fwrite($fp, $new_contents);
//ftruncate assures there won™t be extra
//characters if the resulting file is shorter
//than the original.

FCLOSE() This function closes the pointer to a file.

int fclose (int fp)

It is good form to use it when you are done with a file. If you don™t, PHP will do
it for you, just like mysql_close().


int fwrite (int fp, string string [, int length])

fwrite() writes the value of the string argument to the file indicated by the file
pointer. The function returns a value of -1 if an error is encountered; otherwise it
returns the number of bytes it wrote successfully.


string fread (int fp, int length)

fread() reads from the file pointer given in the first argument the number of
bytes given in the second argument, or until the end of the file, whichever comes

FEOF() This function tests whether a file pointer has reached the end of a file.

bool feof (int fp)

See the fgets() function for an example of feof().

FGETS() This function returns a single line from the file indicated by the file
pointer (usually taken from fopen()). If you are working with a large file, it™s easier
on the system to load files into memory one line at a time, rather than in one big
chunk as is done with fread().

string fgets (int fp, int length)
Chapter 6: PHP™s Built-in Functions 173

This function will read a line up until a newline character. Optionally, you can
specify the maximum number of bytes to read within a line in the second argument.
The number 2048 is traditionally used in the second argument because on many old
file systems that was the maximum line length. These days, you™re safe using some-
thing larger. You shouldn™t use this function with binary files.

$fp = fopen(“/path/to/file”,”r”);
while ($fp && !feof($fp))
print fgets($fp,2048);

FILE() This function reads a file line by line, each line becoming an element in an

array file (string filename [, int use_include_path])

UMASK() This function sets the umask value (see your Solaris man page ” man
umask ” if you don™t know what this is).

int umask (int mask)

umask() sets PHP™s umask to mask & 0777 and returns the old umask.


bool file_exists (string filename)

If the local file specified in the argument exists, this function returns TRUE.


string file_get_contents (string filename [, int use_include_path])

The contents of the file specified in this function™s argument are returned in a
string. If the optional second argument is set to 1, the function looks for the file in
the include path specified in the configuration.

COPY() This function makes a copy of the file in argument one and copies it to
the location in argument two.

bool copy (string source, string dest)
174 Part II: Working with PHP

If the copy works, the function returns TRUE. If not, it returns FALSE. This func-
tion is used in Chapter 12.

TEMPNAM() This function creates a unique file name in the directory indicated in
the first argument.

string tempnam (string dir, string prefix)

The string prefix in argument two will be placed before each file name. This can
help you keep track of what files belong to what scripts.

DIRNAME() This function will return the directory name of the supplied string.

string dirname (string path)

For example,

echo dirname(“/www/htdocs/testfile.txt”);

will return



int mkdir (string pathname, int mode)

This function creates in the local file system a directory with the name pathname
and the permissions given by the octal integer mode. Permissions in this form are
governed by standard Unix rules, nicely explained by Linux vendor Slackware
here: http://www.slackware.com/book/index.php?source=x2163.html.


bool is_dir (string pathname)

If the argument is an existing directory, this function returns TRUE.


bool is_uploaded_file (string filename)

If the specified file was uploaded via HTTP by the user, this function returns
TRUE. It is useful for determining that the files a script is operating on are not
native system files.
Chapter 6: PHP™s Built-in Functions 175


bool move_uploaded_file (string filename, string destination)

This function incorporates the functionality of is_uploaded_file(). It first
checks whether the argument file name was uploaded via HTTP POST, and, if so,
moves it to the destination location. If it is not an uploaded file, the function
returns FALSE.


string basename (string path [, string suffix])

Given a file path, this function will cut off all elements of the path except the
base file name. If a suffix is given as an optional argument, that suffix will also be
cut off of the file name. For example:

$path = “/www/htdocs/testfile.txt”;
echo basename($path, “.txt”);

will output



string realpath (string path)

Given a pathname containing symbolic links or ../ shortcuts, realpath() will
return an absolute pathname with none of these components.

File system functions are an important topic, and one you should spend some time
learning about. Most of the more popular file system commands are available
through PHP, and many commands are available for opening, reading, writing, and
displaying files. But, as this book deals with a relational database for data storage,
we will not cover them here.

Script Control functions
This is a group of functions and language constructs that can be used to control the
execution of PHP scripts.
176 Part II: Working with PHP


mixed call_user_func (callback function [, mixed parameter [, mixed ...]])

This function takes a user-defined function as its argument and calls the func-
tion, passing it any parameters given.


. 33
( 132 .)