23.1.1. ProblemYou want to open a local file to read data from it or write data to it. 23.1.2. SolutionUse fopen( ), as in Example 23-7. Opening a file
23.1.3. DiscussionThe first argument to fopen( ) is the file to open; the second argument is the mode in which to open the file. 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 23-1.
The x and x+ modes return false and generate a warning if the file already exists. They are available in PHP 4.3.2 and later. On non-POSIX systems, such as Windows, you need to add a b to the mode when opening a binary file (as shown in Example 23-8), or reads and writes get tripped up on NUL (ASCII 0) characters. Safely reading a binary file
Even though Unix systems handle binary files fine without the b in the mode, it's a good idea to use it always. That way, your code is maximally portable and runs well on both Unix and Windows. To operate on a file, pass the filehandle 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 true as a third argument. Example 23-9 searches for file.inc in the include_path. Opening files in the include_path
23.1.4. See AlsoDocumentation on fopen( ) at http://www.php.net/fopen. |