Handling a null stream resource? (SSH2 issue.)

I have the following code:

    $domain='whatever.whatever.com';
    $user='username';
    $pass='password';

    header('Content-Encoding: none;');
    set_time_limit(0);

    $connection = ssh2_connect($domain, 22);
   
    if(ssh2_auth_password($connection, $user, $pass)){//If authentication is successful...
        $stream = ssh2_exec($connection, 'cat test.sh');//WORKS (as long as it's on the server)...
        //$stream = ssh2_exec($connection, 'ls && cat test.sh');//WORKS
        //$stream = ssh2_exec($connection, 'man ping');//WORKS

        $stdout_stream = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);

        if (ob_get_level() == 0)
            ob_start();

        while (!feof($stdout_stream)) {
            $line = fgets($stdout_stream);
            if($line !== false){
                echo $line.'<br />';
                echo str_pad('', 4096);
            }
            ob_flush();
            flush();
            usleep(100000);
        }

        fclose($stdout_stream);
        ob_end_flush();
    }

Long story short, I’m using the above to output various tidbits from my server but depending on the command issued with ssh2_exec(), the WHILE logic may or may not become an infinite loop. From what I’ve researched so far, this comes from how feof() handles null pointers but I’m not entirely sure I understand why. I think it has something to do with how a null pointer is provided from the beginning and how feof() interprets null pointers: it doesn’t appear to change null pointer values to true? Is that right? Because otherwise, if it did, you wouldn’t wind up with the infinite loops. For example, if I issue something like, “cat test.sh” in the above ssh2_exec() and test.sh isn’t on the server (or in the directory the command is issued against), it creates a null pointer that feof() can’t handle correctly–for whatever reasons.

My question is this: is there any way I can trap these instances so that I can properly handle them, provide better error output, etc.? If so, how? I can’t find anything from Google about this that actually works and the manual pages are ambiguous at best, if not vacant of anything useful that helps me understand this. (Not blaming anything here–just saying that this, to me, is as clear as mud! :slight_smile: )

(Bonus question: why the odd / extra characters when issuing, “man ping,” in the ssh2_exec() function? I expect readable man page information but what I get back is…well…odd English.)

Thanks in advance.