Home > Article > Backend Development > Use of PHP feof() function to read files_PHP tutorial
(PHP 4, PHP 5)
feof — Test whether the file pointer reaches the end of the file
If the server does not close the connection opened by fsockopen(), feof() will wait until timeout and return TRUE. The default timeout limit is 60 seconds, this value can be changed using stream_set_timeout().
The file pointer must be valid and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
You may get stuck in an infinite loop if the passed file pointer is invalid because EOF does not return TRUE.
Example #1 feof() example using invalid file pointer
// If the file cannot be read or does not exist, the fopen function returns FALSE
$file = @fopen("no_such_file", "r");
// FALSE from fopen will issue a warning message and get stuck in an infinite loop here
while (!feof($file)) {
}
fclose($file);
?>
Example
$file = fopen($_SERVER['DOCUMENT_ROOT']."/me/test.txt", "r");
//Output all lines in the text until the end of the file.
while(!feof($file))
{
echo fgets($file). "
";
}
fclose($file);
?>
Output:
Hello, this is a test file.
There are three lines here.
This is the last line.