The feof Function
The feof
function checks whether the end of a file has been reached while reading. It takes one parameter - a file pointer that was successfully opened by the fopen
function. Returns true
if the end of the file has been reached, and false
otherwise.
Syntax
feof(resource $handle): bool
Example
Check if the end of the file has been reached while reading:
<?php
$file = fopen('test.txt', 'r');
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
?>
In this example, we read the file line by line until we reach its end.
Example
Check the state of the file pointer after opening the file:
<?php
$file = fopen('empty.txt', 'r');
var_dump(feof($file));
fclose($file);
?>
Code execution result for an empty file:
true
Example
Handling an error when opening a file:
<?php
$file = @fopen('nonexistent.txt', 'r');
if ($file === false) {
echo "File not found";
} else {
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
}
?>
Code execution result if the file does not exist:
'File not found'