This article mainly introduces the method of using feof()function in PHP to read files, compares the correct and incorrect usage in the form of examples, and explains the usage skills of the feof() function. Friends in need You can refer to the
feof() function to detect whether the end of the file (eof) has been reached. If the file pointer reaches EOF or an error occurs, it returns TRUE, otherwise it returns an error (including socket timeout), In other cases, it returns FALSE.
feof applies to PHP 4, PHP 5
-Used to 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()).
If the passed file pointer is invalid, it may fall into an infinite loop , because EOF will not return TRUE.
Example #1 feof() using invalid file pointer Example:
The code is as follows:
<?php // 如果文件不可读取或者不存在,fopen 函数返回 FALSE $file = @fopen("no_such_file", "r"); // 来自 fopen 的 FALSE 会发出一条警告信息并在这里陷入无限循环 while (!feof($file)) { } fclose($file); ?>
Example: The code is as follows:
<?php $file = fopen($_SERVER['DOCUMENT_ROOT']."/me/test.txt", "r"); //输出文本中所有的行,直到文件结束为止。 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.
The above is the detailed content of Introduction to the php feof() function and how to use the feof() function to read files. For more information, please follow other related articles on the PHP Chinese website!