PHP 从输出流写入文件只写入前几行

PHP writing to a file from an output stream only writes the first few lines

我正在尝试从远程服务器的输出流写入文件 (file.txt)。输出流的内容是从远程服务器上的 bash/expect 脚本生成的。我不确定 fwrite() 是如何工作的,但是,当我回显 fget() 时,我可以看到脚本的整个输出。

有谁知道 fwrite() 是否只写输出流的前几行?或者什么时候停止写入?我尝试使用 while 循环让它连续写入,但我只看到 file.txt while($line = fgets($stream_out)) {fwrite($fopenText, $line);} 中的前几行。但是,当我回显 fget() 时,我可以在网页上看到整个输出流,我需要将完整的输出写入我的 file.txt,但这是行不通的。

我怎样才能做到这一点?

$gwUser = 'user';
$gwPwd = 'pwd';
$pathToScript1 = '/home/user/up.sh';
$pathToScript2 = '/home/user/down.sh';

if ($connection = @ssh2_connect($gateway, 22)) {
    ssh2_auth_password($connection, $gwUser, $gwPwd);            
    if(isset($_POST['option']) && $_POST['option'] == 1) { 
        $stream = ssh2_exec($connection, $pathToScript1);
        stream_set_blocking($stream, true);
        $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
        $stream_err = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

        $path = $_SERVER['DOCUMENT_ROOT'] . "/my/path/file.txt";
        touch($path);
        chmod($path, 0777);
        $fopenText = fopen($path, "w");
        while($line = fgets($stream_out)) {fwrite($fopenText, $line);} //this doesn't give me the full output stream
        echo '<pre>' . "------------------------\n" . '</pre>';
        while($line = fgets($stream_err)) {flush(); echo '<pre>' . $line . '</pre>';}
        fclose($stream);
        fclose($fopenText);
    }

    //I can get the the output stream this way, but this is not what i want.
    if(isset($_POST['option'])  && $_POST['option'] == 2) { 

        $stream = ssh2_exec($connection, "$pathToScript2");
        stream_set_blocking($stream, true);
        $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
        $stream_err = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
        while($line = fgets($stream_out)) {flush(); echo '<pre>' . $line . '</pre>';}
        echo '<pre>' . "------------------------\n" . '</pre>';
        while($line = fgets($stream_err)) {flush(); echo '<pre>' . $line . '</pre>';}
        fclose($stream);                
    }
}

file.txt 输出:

[root@psat main]# cat file.txt
cd /home/user/
My current directory is:/home/user
./myExpectScript.sh

预期 file.txt 输出(我从 $_POST['option'] == 2 echo 返回的内容):

cd /home/user/
My current directory is:/home/user/
./myExpectScript.sh
spawn /bin/bash
[user@gateway user]$ spawn /bin/bash
[user@gateway user]$ ./hexMsg -o 3 20000 0 0 0
??
[user@gateway user]$ /usr/local/bin/ssh " @ "
...
...
(omitted for simplicity)

听起来好像 SSH 连接还没有返回,所以 fwrite() 循环还没有结束,文件也没有关闭。结果,一些输出可能被缓冲。每次写入后尝试刷新缓冲区:

    while($line = fgets($stream_out)) {
        fwrite($fopenText, $line);
        fflush($fopenText);
    }