3.4. Reading and Writing Files
This book is about using PHP and MySQL together. In most applications, you store the data needed by the application in a MySQL database. However, occasionally you need to read or write information in a text file that isn't a database. This section describes how to read and write data in a text file, also called a flat file.
You use PHP statements to read from or write to a flat file.
Using a flat file requires three steps:
Open the file.
Write data into the file or retrieve data from the file.
Close the file.
These steps are discussed in detail in the following sections.
3.4.1. Accessing files
The first step, before you can write information into or read information from a file, is to open the file. The following is the general format for the statement that opens a file:
$fh = fopen("filename","mode")
The variable, $fh, referred to as a file handle, is used in the statements that write data to or read data from the open file so that PHP knows which file to write into or read from. $fh contains the information that identifies the location of the open file.
You use a mode when you open the file to let PHP know what you intend to do with the file. Table 3-3 shows the modes you can use.
|Mode||What It Does||What Happens When the File Doesn't Exist|
|r||Read-only.||A warning message is displayed.|
|r+||Reading and writing.||A warning message is displayed.|
|w||Write only.||PHP attempts to create it. (If the file exists, PHP overwrites it.)|