The fopen() function is used to open files in PHP.
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened, and the second parameter specifies which mode to use to open the file:
<html><body><?php$file=fopen("welcome.txt","r");?></body></html>
Files may be opened in the following modes:
model | describe |
---|---|
r | Read only. Start at the beginning of the file. |
r+ | read/write. Start at the beginning of the file. |
w | Just write. Opens and clears the contents of the file; if the file does not exist, creates a new file. |
w+ | read/write. Opens and clears the contents of the file; if the file does not exist, creates a new file. |
a | Append. Opens and writes to the end of the file, or creates a new file if it does not exist. |
a+ | Read/Append. Maintain file contents by writing to the end of the file. |
x | Just write. Create new file. If the file already exists, returns FALSE and an error. |
x+ | read/write. Create 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).
If the fopen() function cannot open the specified file, the following example generates a message:
<html><body><?php$file=fopen("welcome.txt","r") or exit("Unable to open file!");?></body></html>
The fclose() function is used to close an open file:
<?php$file = fopen("test.txt","r");//Execute some code fclose($file);?>
The feof() function detects whether the end of file (EOF) has been reached.
The feof() function is useful when looping over data of unknown length.
Note: In w, a and x modes you cannot read open files!
if (feof($file)) echo "end of file";
The fgets() function is used to read a file line by line from a file.
Note: After calling this function, the file pointer moves to the next line.
The following example reads a file line by line until the end of the file:
<?php$file = fopen("welcome.txt", "r") or exit("Cannot open file!");//Read each line of the file until the end of the file while(!feof($file)) { echo fgets($file). "<br>"; }fclose($file);?>
The fgetc() function is used to read from a file character by character.
Note: After calling this function, the file pointer moves to the next character.
The following example reads a file character by character until the end of the file:
<?php$file=fopen("welcome.txt","r") or exit("Cannot open file!");while (!feof($file)) { echo fgetc($file); }fclose($ file);?>
For a complete reference manual of PHP filesystem functions, visit our PHP Filesystem Reference Manual.