Page 349 - Beginning PHP 5.3
P. 349
Chapter 11: Working with Files and Directories
You can also lock files that are opened using fopen() . To do this, use flock() . See http://www
.php.net/manual/en/function.flock.php for more details.
fpassthru() and readfile() both take a file and output its unmodified contents straight to the Web
browser. fpassthru() requires the handle of an open file to work with:
$numChars = fpassthru( $handle );
readfile() instead works on an unopened file:
$numChars = readfile( “myfile.txt” );
As you can see, both functions return the number of characters read (or false if there was a problem).
fpassthru() reads from the current file pointer position, so if you ’ ve already read some of the file only
the remaining portion of the file will be sent.
You can make readfile() search the include path for the file by passing true as the second argument.
Incidentally, readfile() is handy for sending binary files — such as images and PDF documents — to
the Web browser for displaying or downloading. You see an example of this in Chapter 16.
Random Access to File Data
Using the functions you ’ ve met so far, you can only manipulate data sequentially, that is, in the same
order that it is arranged in the file. However, sometimes you need to skip around the contents of an open
file. For example, you might want to read a file once to search for a particular string, then return to the
start of the file in order to search for another string. Of course, this is easy if you ’ ve read the entire file
using, for example, file_get_contents() . However, this isn ’ t practical for large files.
Fortunately, it ’ s possible to move the file pointer around within an open file, so that you can start
reading or writing at any point in the file. PHP gives you three functions that let you work with the file
pointer:
❑ fseek() — Repositions the file pointer to a specified point in the file
❑ rewind() — Moves the file pointer to the start of the file
❑ ftell() — Returns the current position of the file pointer
311
9/21/09 9:10:15 AM
c11.indd 311
c11.indd 311 9/21/09 9:10:15 AM