Page 338 - Beginning PHP 5.3
P. 338
Part III: Using PHP in Practice
Opening and Closing Files
Usually, to work with a file from within your PHP script, you first need to open the 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.
File handles are resource data types. Data types were covered in Chapter 3.
Some PHP functions let you work directly with a file without needing to open or close it. You read about
these later in the chapter.
In the next sections you 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.
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.
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.
300
9/21/09 9:10:11 AM
c11.indd 300 9/21/09 9:10:11 AM
c11.indd 300