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:

  1. Open the file.

  2. Write data into the file or retrieve data from the file.

  3. 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.

Table 3.3. Modes for Opening a File
ModeWhat It DoesWhat Happens When the File Doesn't Exist
rRead-only.A warning message is displayed.
r+Reading and writing.A warning message is displayed.
wWrite only.PHP attempts to create it. (If the file exists, PHP overwrites it.)
w+

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.