Creating or Opening a File

You want to open a local file to read data from it or write data to it.

Use fopen(). It opens a file and returns a filehandle, and if it fails, returns false. The first argument is the file to open. The second argument is the mode in which to open the file. The third argument, if set to true, tells PHP to check the PHP include path.

filehandle = fopen("filename", mode, [1 or true])

Mode Name Description
r Read Opens only for reading; starts at the beginning of the file
r+ Read Opens only for reading and writing; starts at the beginning of the file
w Write Opens only for writing; starts at the beginning of the file. If the file exists, truncates it; if not creates it.
w+ Write Opens only for reading and writing; starts at the beginning of the file. If the file exists, truncates it; if not creates it. If the file doesn't exist, attempts to create it.
a Append Opens for writing only; appends at the end of the file. If the file does not exist, attempts to create it.
a+ Append Opens for reading and writing only; appends at the end of the file. If the file does not exist, attempts to create it.
x Cautious Write Creates and opens a local file for writing only; starts at the beginning of the file. If the file already exists, fopen() returns false, and PHP sends a warning. If the file does not exist, attemps to create it.
x+ Cautious Write Creates and opens a local file for reading and writing only; starts at the beginning of the file. If the file already exists, fopen() returns false, and PHP sends a warning. If the file does not exist, attemps to create it.
b   The default mode, used with one of the other modes for file systems that differentiate between binary and text files. Necessary with Windows, but not with Unix or Mac.
t   Used with one of the other modes to represent Windows text files. Translates end of line character \n to \r\n. Used with the b mode for portability.


Files | Introduction | File Permissions | Creating or Opening a File | Writing to Files | Locking Files | Reading from Files | Reading Files Incrementally | Reading Files with CSV | File Upload
© 2008: Hann So
email: hso@voyager.deanza.edu