PHP shell_exec与实时更新


php shell_exec with realtime updating

我想用php执行这个shell程序。问题是,它可能需要很长时间,因此我需要它能够实时更新到用户的浏览器。

我读到我可能需要使用popen()来做到这一点,但我有点(好吧,我真的是:p)一个PHP新手,不知道我怎么能做到这一点。

感谢您的帮助!

if( ($fp = popen("your command", "r")) ) {
    while( !feof($fp) ){
        echo fread($fp, 1024);
        flush(); // you have to flush buffer
    }
    fclose($fp);
}

有一个dirty easy选项

`yourcommand 1>&2`;

将标准输出重定向到标准输出

有两种可能的行为:

  1. 非块,你需要在冲洗之间做其他事情(@GameBit显示如何做到这一点)。

  2. With Block,等待被调用的命令完成,在本例中查看passthru函数

我使用了这个解决方案。

$commandString = "myexe";
# Uncomment this line if you want to execute the command in background on Windows
# $commandString = "start /b $commandString";
$exec = popen($commandString, "r");
# echo "Async Code Test";
while($output = fgets($exec, 2048))
{
    echo "$output <br>'n";
    ob_flush();
    flush();
}
pclose($exec);

试试这段代码(在Windows机器+ wamp服务器上测试)

        header('Content-Encoding: none;');
        set_time_limit(0);
        $handle = popen("<<< Your Shell Command >>>", "r");
        if (ob_get_level() == 0) 
            ob_start();
        while(!feof($handle)) {
            $buffer = fgets($handle);
            $buffer = trim(htmlspecialchars($buffer));
            echo $buffer . "<br />";
            echo str_pad('', 4096);    
            ob_flush();
            flush();
            sleep(1);
        }
        pclose($handle);
        ob_end_flush();