Open File
The fopen () function is used to open a file in PHP.
The first parameter of this function contains the name of the file you want to open, and the second parameter sets which mode is used to open the file:
<html> <body> <?php $file =fopen ("Welcome.txt", "R");?> </body> </html>
The file may be opened in the following modes:
Mode description R Read only. Start at the beginning of the file. Intermolecular read/write. Start at the beginning of the file. W write only. Open and empty the contents of the file, or create a new file if the file does not exist. w+ read/write. Open and empty the contents of the file, or create a new file if the file does not exist. A append. Opens and writes to the end of the file file, and creates a new file if the file does not exist. A + read/append. Maintains the contents of the file by writing to the end of the file. X write only. Create a new file. Returns FALSE if the file is present. x+
Read/write. Create a new file. Returns FALSE and an error if the file already exists.
Note: Returns 0 (false) if fopen () cannot open the specified file.
Example
If fopen () 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> Close File
The fclose () function closes the open file.
<?php $file = fopen ("Test.txt", "R"); Some code to is executed fclose ($file);?> detection End-of-file
The feof () function detects whether the end of the file (EOF) has been reached.
The feof () function is useful when iterating through unknown length of data.
Note: You cannot read open files in W, a, and x mode!
if (feof ($file)) echo "End of File"; Read files line by row
The fgets () function is used to read files line by row from a file.
Note: After the function is called, the file pointer moves to the next line.
Example
The following example reads the file line by row until the end of the file:
<?php $file = fopen ("Welcome.txt", "R") or exit ("Unable to open file!"); Output a line of the file loop The "End is reached while (!feof ($file)) {echo fgets ($file). "<br/>"; Fclose ($file);?> verbatim read file
The fgetc () function is used to read files verbatim from a file.
Note: After calling the function, the file pointer moves to the next character.
Example
The following example reads the file verbatim, until the end of the file:
<?php $file =fopen ("Welcome.txt", "R") or exit ("Unable to open file!"); while (!feof ($file)) {echo fgetc ($file);} fclose ($file);