PHP File Handling
The fopen() function is used to open a file in PHP.
Opening a File
The fopen() function is used to open a file in PHP.
The first parameter of this function contains the name of the file to open, and the second parameter specifies which mode to use to open the file:
A file may be opened in the following modes:
| Mode | Description |
|---|---|
| r | Read only. Starts at the beginning of the file. |
| r+ | Read/write. Starts at the beginning of the file. |
| w | Write only. Opens and empties the file's content; if the file does not exist, creates a new file. |
| w+ | Read/write. Opens and empties the file's content; if the file does not exist, creates a new file. |
| a | Append. Opens and writes to the end of the file; if the file does not exist, creates a new file. |
| a+ | Read/append. Preserves the file content by writing to the end of the file. |
| x | Write only. Creates a new file. If the file already exists, returns FALSE and an error. |
| x+ | Read/write. Creates a new file. If the file already exists, returns FALSE and an error. |
**Note:** If the fopen() function cannot open the specified file, it returns 0 (false).
Example
If the fopen() function cannot open the specified file, the example below generates a message:
Closing a File
The fclose() function is used to close an open file:
Detecting the End of a File (EOF)
The feof() function detects whether the end of the file (EOF) has been reached.
The feof() function is useful when looping through data of unknown length.
**Note:** In w, a, and x modes, you cannot read the open file!
if (feof($file)) echo "End of file";
Reading a File Line by Line
The fgets() function is used to read a file line by line.
**Note:** After calling this function, the file pointer moves to the next line.
Example
The example below reads the file line by line until the end of the file:
"; } fclose($file); ?>Reading a File Character by Character
The fgetc() function is used to read a file character by character.
**Note:** After calling this function, the file pointer moves to the next character.
Example
The example below reads the file character by character until the end of the file:
PHP Filesystem Reference Manual
To view the complete reference manual for PHP filesystem functions, please visit ourPHP Filesystem Reference Manual.