Specifications
Using fopen() to Open a File
Let’s assume that we want to write a customer order to Bob’s order file. You can open this file
for writing with the following:
$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “w”);
When fopen is called, it expects two or three parameters. Usually you’ll use two, as shown in
this code line.
The first parameter should be the file you want to open. You can specify a path to this file as
we’ve done in the previous code—our
orders.txt file is in the orders directory. We’ve used
the PHP built-in variable $DOCUMENT_ROOT. This variable points at the base of the document
tree on your Web server. We’ve used the “..” to mean “the parent directory of the
$DOCUMENT_ROOT directory. This directory is outside the document tree, for security reasons.
We do not want this file to be Web accessible except through the interface that we provide.
This path is called a relative path as it describes a position in the file system relative to the
$DOCUMENT_ROOT.
You could also specify an absolute path to the file. This is the path from the root directory
(/ on a UNIX system and typically C:\ on a Windows system). On our UNIX server, this
would be /home/book/orders. The problem with doing this is that, particularly if you are host-
ing your site on somebody else’s server, the absolute path might change. We learned this the
hard way after having to change absolute paths in a large number of scripts when the systems
administrators decided to change the directory structure without notice.
If no path is specified, the file will be created or looked for in the same directory as the script
itself. This will be different if you are running PHP through some kind of CGI wrapper and
will depend on your server configuration.
In a UNIX environment, the slashes in directories will be forward slashes (/). If you are using
a Windows platform, you can use forward or back slashes. If you use back slashes, they must
be escaped (marked as a special character) for fopen to understand them properly. To escape a
character, you simply add an additional backslash in front of it, as shown in the following:
$fp = fopen(“..\\..\\orders\\orders.txt”, “w”);
The second parameter of fopen() is the file mode, which should be a string. This specifies
what you want to do with the file. In this case, we are passing “w” to fopen()—this means
open the file for writing. A summary of file modes is shown in Table 2.1.
Storing and Retrieving Data
C
HAPTER 2
2
STORING AND
RETRIEVING DATA
53
04 7842 CH02 3/6/01 3:37 PM Page 53