Search code examples
phpeoffgets

Php function loop with file handle


This function is causing big trouble on my server because is in loop:

function loadFiles()
{
$email = $_POST["emailp"];
$file_handle = fopen("/tmpphp/dmbigmail.file", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
if(stristr($line,$email)){
    $show = trim(str_replace($email,' ',$line));
    //echo $show;
    $parsedata = substr($show,0,11);
    $parselink = substr($show,10);
    $total = $parsedata.'<a href=' . $parselink. ">$parselink</a><br>";
    echo $total;
    }
     }
     fclose($file_handle);
 }

In my log I can see this: "PHP Warning: fgets() expects parameter 1 to be resource, boolean given in /path/file.php on line 42"

The line interested is:

$line = fgets($file_handle);

The function is ok, but I dont know why give me this strange error.


Solution

  • Because $file_handle is boolean false (you can check for this with var_dump), which in turn happens because the fopen call fails.

    fopen

    Returns a file pointer resource on success, or FALSE on error.