Home >Backend Development >PHP Tutorial >PHP feof tests whether the file pointer reaches the end of the file_PHP tutorial
EOF is a very important concept. Almost every mainstream programming language provides corresponding built-in functions to verify whether the parser has reached the file EOF. In PHP, this function is feof (). The feof () function is used to determine whether the end of the resource has been reached. It is frequently used in file I/O operations. Its form is:
int feof(string resource)
The example code is as follows:
$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 original words in this php manual.
For convenience, I used to use it like this before
// if file can not be read or doesnt 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 this way. However, if the above variable $file is not a legal file pointer or has been closed by fclose.
Then in the sixth line of the program, a warning will be generated and an infinite loop will occur.
Why?
The reason is that
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
So, for safety reasons, it is best to add a Judgment, is_resource is relatively safe