Search code examples
phpfeof

PHP feof() False as first argument


I ended up “resolving” someone else’s code issue since the site was down and we couldn’t get a hold of them, but I don’t use PHP and I think this is working, but not for the right reasons:

They have something like:

$file = ../somedir/somefile.txt;
$fh = fopen($file, 'r');
while (!feof($fh)) {
$line = fget(...

But the page wasn’t loading.

Based on the error in the log, I ended up changing the feof line to:

while (feof(False, $fh)) {

Which actually appears to have resolved the issue, but after looking at documentation for feof(), I don’'t think what I did was right at all.

What is that impact of adding False as the first argument to PHP's feof() function?

Update: The log error was feof() expects parameter 1 to be resource, boolean given in I took Boolean to mean True False, which is why I set the False as first arg.


Solution

  • What is that impact of adding False as the first argument to PHP's feof() function?

    Well, here is what feof documentation says:

    Tests for end-of-file on a file pointer.

    And since there is only one parameter allowed in the function as indicated here:

    bool feof ( resource $handle )
    

    The False you are setting basically is telling the script:

    while ([the file handle doesn’t equals false do this]) {
    

    So you are basically short-circuiting the logic in some way. But without seeing the full code or error messages it’s 100% unclear what impact doing something like this would have on overall application behavior.

    UPDATE: Since you now say the error log says:

    feof() expects parameter 1 to be resource, boolean given in
    

    That basically means the problem is the $file that you are attempting to open and then create a file handle with $fh does’t exist or can’t be read:

    $file = ../somedir/somefile.txt;
    $fh = fopen($file, 'r');
    

    The best solution for you now is to wrap the condition in another conditional like this:

    $file = ../somedir/somefile.txt;
    if (file_exists($filename)) {
      $fh = fopen($file, 'r');
      while (!feof($fh)) {
      $line = fget(...
    }
    

    But now looking at your code is that line $file = ../somedir/somefile.txt; correct? Shouldn’t it be:

    $file = '../somedir/somefile.txt';
    

    So your code would look like this:

    $file = '../somedir/somefile.txt';
    if (file_exists($filename)) {
      $fh = fopen($file, 'r');
      while (!feof($fh)) {
      $line = fget(...
    }
    

    But past any of that, I would check if the actual file ../somedir/somefile.txt exists and is readable by your script. It could be that the location changed or the permissions or user connected to that file has been changed. That is most likely the underlying cause of the feof() expects parameter 1 to be resource, boolean given in error.