Page 348 - Beginning PHP 5.3
P. 348
Part III: Using PHP in Practice
As with other flags in PHP you can combine any of these flags with the bitwise OR operator (see Chapter 3
for details). For example, the following code looks for a file in the include path and, when found, reads
the file, ignoring any empty lines in the file:
$lines = file( “myfile.txt”, FILE_USE_INCLUDE_PATH | FILE_SKIP_EMPTY_LINES );
As with fopen() , you can also use file() to fetch files on a remote host:
$lines = file( “http://www.example.com/index.html” );
foreach ( $lines as $line ) echo $line . “ < br / > ”;
A related function is file_get_contents() . This does a similar job to file() , but it returns the
file contents as a single string, rather than an array of lines. The end - of - line characters are included in
the string:
$fileContents = file_get_contents( “myfile.txt” );
If there was a problem reading the file, file_get_contents() returns false .
You can pass the FILE_USE_INCLUDE_PATH flag (described earlier) as the second argument to
file_get_contents().
You can also optionally pass in an offset and/or a length parameter to determine where you want the file
reading to start, and how many characters you want to read. For example, the following code reads 23
characters from myfile.txt , starting at character 17:
$fileContents = file_get_contents( “myfile.txt”, null, null, 17, 23 );
The first null argument avoids setting the FILE_USE_INCLUDE_PATH flag, and the second null
argument avoids setting a context. Contexts are out of the scope of this book, but you can find out more
about them in the online manual at http://www.php.net/manual/en/stream.contexts.php .
file_put_contents() is the complement to file_get_contents() . As you ’ d imagine, it takes a
string and writes it to a file:
$numChars = file_put_contents( “myfile.txt”, $myString );
The function returns the number of characters written, or false if there was a problem. You can affect the
behavior of the function by passing various flags as the third argument. file_put_contents() supports
the same flags as file_get_contents() , as well as two additional flags:
Flag Description
FILE_APPEND If the file already exists, append the string to the end of the file, rather than
overwriting the file.
LOCK_EX Lock the file before writing to it. This ensures that other processes can ’ t write to
the file at the same time.
310
9/21/09 9:10:15 AM
c11.indd 310 9/21/09 9:10:15 AM
c11.indd 310