Specifications

There are many different functions that can be used to read from files. The fgets() function is
useful when dealing with files that contain plain text that we want to deal with in chunks.
An interesting variation on fgets() is fgetss(), which has the following prototype:
string fgetss(int fp, int length, string [allowable_tags]);
This is very similar to fgets() except that it will strip out any PHP and HTML tags found in
the string. If you want to leave any particular tags in, you can include them in the
allowable_tags string. You would use fgetss() for safety when reading a file written by
somebody else or containing user input. Allowing unrestricted HTML code in the file could
mess up your carefully planned formatting. Allowing unrestricted PHP could give a malicious
user almost free rein on your server.
The function fgetcsv() is another variation on fgets(). It has the following prototype:
array fgetcsv(int fp, int length, string [delimiter]);
It is used for breaking up lines of files when you have used a delimiting character, such as the
tab character as we suggested earlier or a comma as commonly used by spreadsheets and other
applications. If we want to reconstruct the variables from the order separately rather than as a
line of text, fgetcsv() allows us to do this simply. You call it in much the same way as you
would call fgets(), but you pass it the delimiter you used to separate fields. For example
$order = fgetcsv($fp, 100, “\t”);
would retrieve a line from the file and break it up wherever a tab (\t) was encountered. The
results are returned in an array ($order in this code example). We will cover arrays in more
detail in Chapter 3.
The length parameter should be greater than the length in characters of the longest line in the
file you are trying to read.
Reading the Whole File: readfile(), fpassthru(), file()
Instead of reading from a file a line at a time, we can read the whole file in one go. There are
three different ways we can do this.
The first uses readfile(). We can replace the entire script we wrote previously with one line:
readfile(“$DOCUMENT_ROOT/../orders/orders.txt”);
A call to the readfile() function opens the file, echoes the content to standard output (the
browser), and then closes the file. The prototype for readfile() is
int readfile(string filename, int [use_include_path]);
Storing and Retrieving Data
C
HAPTER 2
2
STORING AND
RETRIEVING DATA
61
04 7842 CH02 3/6/01 3:37 PM Page 61