Page 339 - Beginning PHP 5.3
P. 339
Chapter 11: Working with Files and Directories
The second argument to fopen() tells PHP how you ’ re going to use the file. It can take one of the
following string values:
Value Description
r Open the file for reading only. The file pointer is placed at the beginning of the file.
r+ Open the file for reading and writing. The file pointer is placed at the beginning of the file.
w Open the file for writing only. Any existing content will be lost. If the file does not exist,
PHP attempts to create it.
w+ Open the file for reading and writing. Any existing file content will be lost. If the file
does not exist, PHP attempts to create it.
a Open the file for appending only. Data is written to the end of an existing file. If the file
does not exist, PHP attempts to create it.
a+ Open the file for reading and appending. Data is written to the end of an existing file. If
the file does not exist, PHP attempts to create it.
The file pointer is PHP ’ s internal pointer that specifies the exact character position in a file where the
next operation should be performed.
You can also append the value b to the argument to indicate that the opened file should be treated as a
binary file (this is the default setting). Alternatively, you can append t to treat the file like a text file, in
which case PHP attempts to translate end - of - line characters from or to the operating system ’ s standard
when the file is read or written. For example, to open a file in binary mode use:
$handle = fopen( “data.txt”, “rb” );
Although this flag is irrelevant for UNIX - like platforms such as Linux and Mac OS X, which treat text
and binary files identically, you may find the text mode useful if you ’ re dealing with files created on a
Windows computer, which uses a carriage return followed by a line feed character to represent the end
of a line (Linux and the Mac just use a line feed).
That said, binary mode is recommended for portability reasons. If you need your application ’ s data files
to be readable by other applications on different platforms, you should use binary mode and write your
code to use the appropriate end - of - line characters for the platform on which you are running. (The PHP
constant PHP_EOL is handy for this; it stores the end - of - line character(s) applicable to the operating
system that PHP is running on.)
301
9/21/09 9:10:11 AM
c11.indd 301
c11.indd 301 9/21/09 9:10:11 AM