Specifications
TABLE 2.1 Summary of File Modes for fopen
Mode Meaning
r Read mode—Open the file for reading, beginning from the start of the file.
r+ Read mode—Open the file for reading and writing, beginning from the start
of the file.
w Write mode—Open the file for writing, beginning from the start of the file. If
the file already exists, delete the existing contents. If it does not exist, try and
create it.
w+ Write mode—Open the file for writing and reading, beginning from the start
of the file. If the file already exists, delete the existing contents. If it does not
exist, try and create it.
a Append mode—Open the file for appending (writing) only, starting from the
end of the existing contents, if any. If it does not exist, try and create it.
a+ Append mode—Open the file for appending (writing) and reading, starting
from the end of the existing contents, if any. If it does not exist, try and cre-
ate it.
b Binary mode—Used in conjunction with one of the other modes. You might
want to use this if your file system differentiates between binary and text
files. Windows systems differentiate; UNIX systems do not.
The file mode to use in our example depends on how the system will be used. We have used
“w”, which will only allow one order to be stored in the file. Each time a new order is taken, it
will overwrite the previous order. This is probably not very sensible, so we are better off speci-
fying append mode:
$fp = fopen(“../../orders/orders.txt”, “a”);
The third parameter of fopen() is optional. You can use it if you want to search the
include_path (set in your PHP configuration—see Appendix A, “Installing PHP 4 and
MySQL”) for a file. If you want to do this, set this parameter to
1. If you tell PHP to search the
include_path, you do not need to provide a directory name or path:
$fp = fopen(“orders.txt”, “a”, 1);
If fopen() opens the file successfully, a pointer to the file is returned and should be stored in a
variable, in this case $fp. You will use this variable to access the file when you actually want to
read from or write to it.
Opening Files for FTP or HTTP
As well as opening local files for reading and writing, you can open files via FTP and HTTP
using fopen().
Using PHP
P
ART I
54
04 7842 CH02 3/6/01 3:37 PM Page 54