18.2. Creating or Opening a Local File
Use fopen( ):
$fh = fopen('file.txt','r') or die("can't open file.txt: $php_errormsg");
The first argument to fopen( ) is the file to open; the second argument is the mode to open the file in. The mode specifies what operations can be performed on the file (reading and/or writing), where the file pointer is placed after the file is opened (at the beginning or end of the file), whether the file is truncated to zero length after opening, and whether the file is created if it doesn't exist, as shown in Table 18-1.
Table 18-1. fopen( ) file modes
$fh = fopen('c:/images/logo.gif','rb');
To operate on a file, pass the file handle returned from fopen( ) to other I/O functions such as fgets( ), fputs( ), and fclose( ).
If the file given to fopen( ) doesn't have a pathname, the file is opened in the directory of the running script (web context) or in the current directory (command-line context).
You can also tell fopen( ) to search for the file to open in the include_path specified in your php.ini file by passing 1 as a third argument. For example, this searches for file.inc in the include_path:
$fh = fopen('file.inc','r',1) or die("can't open file.inc: $php_errormsg");
18.2.4. See Also
Documentation on fopen( ) at http://www.php.net/fopen.
Copyright © 2003 O'Reilly & Associates. All rights reserved.