Phpfile Processing
The fopen () function is used to open the file in PHP.
Open File
The fopen () function is used to open the file 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:
<body>
<?php
$file =fopen ("Welcome.txt", "R");
?>
</body>
The file may be opened in the following mode:
Mode |
Description |
R |
Read-only. Start at the beginning of the file. |
r+ |
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 |
Additional. Opens and writes to the end of the file, creating a new file if the file does not exist. |
A + |
Read/Append. Preserves the contents of the file by writing to the end of the file. |
X |
Write only. Creates a new file. If the file already exists, it returns FALSE and an error. |
x+ |
Read/write. Creates a new file. If the file already exists, it returns FALSE and an error. |
Note: if the fopen () function cannot open the specified file, 0 (FALSE) is returned.
Instance
If the fopen () function cannot open the specified file, the following instance generates a message:
<body>
<?php
$file =fopen ("Welcome.txt", "R") or exit ("Unable to open file!");
?>
</body>
Close File
The fclose () function is used to close open files:
<?php
$file = fopen ("Test.txt", "R");
Some code to be executed
Fclose ($file);
?>
Detection End-of-file
The feof () function detects if the end of file (EOF) has been reached.
The feof () function is useful when iterating through data of unknown length.
Note: You cannot read open files in W, a, and X modes!
if (feof ($file)) echo "End of File";
Read a file line-wise
The fgets () function is used to read a file from file to line.
Note: after the function is called, the file pointer moves to the next line.
Instance
The following instance 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 until the end is reached
while (!feof ($file))
{
Echo fgets ($file). "<br>";
}
Fclose ($file);
?>
Read files by character literal
The fgetc () function is used to read files verbatim from a file.
Note: after the function is called, the file pointer moves to the next character.
Instance
The following instance reads the file character by word, 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);
?>
PHP file Processing