Understanding PHP's feof() Function and Safe EOF Handling
This article explains PHP's feof() function, detailing its purpose, required handle parameter, return values, and provides two practical code examples—one demonstrating a safe EOF check with timeout and another showing how to handle missing files without entering infinite loops.
The PHP function feof() checks whether a file pointer has reached the end of a file, returning TRUE on EOF or error and FALSE otherwise.
Description: It tests if the file pointer is at the end of the file.
Parameter: $handle – a valid resource obtained from fopen() or fsockopen() that has not been closed.
Return value: TRUE if the pointer is at EOF or an error occurs (including socket timeout); FALSE in other cases.
Example 1 – Safe EOF check with timeout:
<?php
function safe_feof($fp, &$start=NULL) {
$start = microtime(true);
return feof($fp);
}
$timeout = ini_get('default_socket_timeout');
while (!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout) {
// Handle
}
?>Example 2 – Handling a missing file:
<?php
// If the file cannot be read or does not exist, fopen returns FALSE
$file = @fopen("no_such_file","r");
// The FALSE from fopen triggers a warning and can cause an infinite loop
while (!feof($file)) {
// TODO
}
fclose($file);
?>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.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.
