PHP Read File Method Using feof of Function

  • 2021-07-24 10:31:20
  • OfStack

This paper illustrates how PHP uses feof () function to read files. Share it for your reference. The specific usage is as follows:

feof for PHP 4, PHP 5
-Used to test whether the file pointer has reached the end of the file.

If the server does not close the connection opened by fsockopen (), feof () waits until it times out and returns TRUE. The default timeout limit is 60 seconds, which 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 closed by fclose ()).

If you pass an invalid file pointer, you may fall into an infinite loop because EOF does not return TRUE.
Example # 1 feof () example with invalid file pointer:

<?php
// If the file is unreadable or does not exist, fopen Function returns FALSE
$file = @fopen("no_such_file", "r"); // From fopen Adj. FALSE Will emit 1 Warning message and fall into an infinite loop here
while (!feof($file)) {
}
fclose($file);
?>


Examples:

<?php  
$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). "<br />"; 

fclose($file); 
?>

Output:
Hello, this is a test file.
There are three lines here.
This is the last line.

I hope this article is helpful to everyone's PHP programming.


Related articles: