Specifications
Overview of File Processing
There are three steps to writing data to a file:
1. Open the file. If the file doesn’t already exist, it will need to be created.
2. Write the data to the file.
3. Close the file.
Similarly, there are three steps to reading data from a file:
1. Open the file. If the file can’t be opened (for example, if it doesn’t exist), we need to rec-
ognize this and exit gracefully.
2. Read data from the file.
3. Close the file.
When you want to read data from a file, you have choices about how much of the file to read
at a time. We’ll look at each of those choices in detail.
For now, we’ll start at the beginning by opening a file.
Opening a File
To open a file in PHP, we use the fopen() function. When we open the file, we need to specify
how we intend to use it. This is known as the file mode.
File Modes
The operating system on the server needs to know what you want to do with a file that you are
opening. It needs to know if the file can be opened by another script while you have it open,
and to work out if you (the owner of the script) have permission to use it in that way.
Essentially, file modes give the operating system a mechanism to determine how to handle
access requests from other people or scripts and a method to check that you have access and
permission to this particular file.
There are three choices you need to make when opening a file:
1. You might want to open a file for reading only, for writing only, or for both reading and
writing.
2. If writing to a file, you might want to overwrite any existing contents of a file or to
append new data to the end of the file.
3. If you are trying to write to a file on a system that differentiates between binary and text
files, you might want to specify this.
The
fopen() function supports combinations of these three options.
Using PHP
P
ART I
52
04 7842 CH02 3/6/01 3:37 PM Page 52