Using PHP feof() to Detect End‑of‑File: Syntax, Parameters, Return Values, and Example
This article explains the PHP feof() function, covering its syntax, parameter description, return values, and provides a complete code example that reads a file line‑by‑line, checks for end‑of‑file, and demonstrates proper use of fopen() and fclose().
PHP is a widely used scripting language for web development, offering a rich set of functions for handling files; among them, feof() is used to determine whether a file pointer has reached the end of a file.
The function signature is: bool feof ( resource $handle ) Parameter: $handle – the file pointer resource returned by fopen().
Return value: true if the pointer is at EOF, otherwise false.
Below is a practical example. Assume a file example.txt containing:
Hello World!
This is an example file.The following PHP script opens the file, reads it line by line, checks for EOF with feof(), and finally closes the handle:
$handle = fopen("example.txt", "r");
if ($handle) {
// Read each line
while (($line = fgets($handle)) !== false) {
echo $line;
}
// Check if pointer reached EOF
if (feof($handle)) {
echo "文件指针已到达文件末尾。";
} else {
echo "文件指针未到达文件末尾。";
}
fclose($handle);
}When executed, the script outputs the file contents followed by the message indicating that the file pointer has reached the end of the file.
In summary, feof() is a built‑in PHP file‑handling function that helps developers detect the end of a file, preventing unnecessary reads; it should be used after opening a file with fopen() and the file handle should be closed with fclose() to release resources.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
