The method PHP feof USES to recognize the characters at the end of a file

  • 2020-03-31 21:01:35
  • OfStack

EOF is such an important concept that almost every major programming language provides built-in functions to verify that the parser has reached the file EOF. In PHP, this function is feof (). The feof () function is used to determine if the resource end is reached. It is often used in file I/O operations. Its form is:
Int feof (string resource)
Examples are as follows:
 
<?php 
$fh = fopen("/home/www/data/users.txt", "rt"); 
while (!feof($fh)) echo fgets($fh); 
fclose($fh); 
?> 

Bool feof (resource $handle):Tests for end-of-file on a file pointer
The exact words in the PHP manual.
I used to use it this way for convenience
 
<?php 
// if file can not be read or doesn't exist fopen function returns FALSE 
$file = @fopen("no_such_file", "r"); 
// FALSE from fopen will issue warning and result in infinite loop here 
while (!feof($file)) { 
} 
fclose($file); 
?> 

Indeed, it is easier to use. However, if the variable $file above is not a valid file pointer or has been closed by fclose.
Then in the sixth line of the program, there will be a waring, concurrent life and death cycle.
Why is that?
The reason is that
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); Otherwise returns FALSE.
So, to be on the safe side, it's best to add a judgment when using the above code that is_resource is safe.

Related articles: