Specifications

The optional second parameter specifies whether PHP should look for the file in the
include_path and operates the same way as in fopen(). The function returns the total number
of bytes read from the file.
Secondly, you can use fpassthru(). You need to open the file using fopen() first. You can
then pass the file pointer as argument to fpassthru(), which will dump the contents of the file
from the pointers position onward to standard output. It closes the file when it is finished.
You can replace the previous script with fpassthru() as follows:
$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “r”);
fpassthru($fp);
The function fpassthru() returns true if the read is successful and false otherwise.
The third option for reading the whole file is using the file() function. This function is identi-
cal to readfile() except that instead of echoing the file to standard output, it turns it into an
array. We will cover this in more detail when we look at arrays in Chapter 3. Just for reference,
you would call it using
$filearray = file($fp);
This will read the entire file into the array called $filearray. Each line of the file is stored in
a separate element of the array.
Reading a Character: fgetc()
Another option for file processing is to read a single character at a time from a file. You can do
this using the fgetc() function. It takes a file pointer as its only parameter and returns the next
character in the file. We can replace the while loop in our original script with one that uses
fgetc():
while (!feof($fp))
{
$char = fgetc($fp);
if (!feof($fp))
echo ($char==”\n” ? “<br>”: $char);
}
This code reads a single character from the file at a time using fgetc() and stores it in $char,
until the end of the file is reached. We then do a little processing to replace the text end-of-line
characters, \n, with HTML line breaks, <br>. This is just to clean up the formatting. Because
browsers dont render a newline in HTML as a newline without this code, the whole file would
be printed on a single line. (Try it and see.) We use the ternary operator to do this neatly.
A minor side effect of using fgetc() instead of fgets() is that it will return the EOF character
whereas fgets() will not. We need to test feof() again after weve read the character because
we dont want to echo the
EOF to the browser.
Using PHP
P
ART I
62
04 7842 CH02 3/6/01 3:37 PM Page 62