PHP:在Web浏览器中输出system/Shell_exec命令输出

use*_*949 7 javascript php


我尝试使用shell_exec以与在终端中显示的方式(同时)相似的方式在网页上输出简单的ping命令; 但它只在完成执行后显示,而我需要它显示在终端上显示,

我的代码是

<?php
$i= shell_exec("ping -c 4 google.com");
echo "<pre> $i <pre>";
?>
Run Code Online (Sandbox Code Playgroud)

它正在等待一段时间并将整个东西倾倒在一个镜头上...... PHP可以识别每行的输出并将其显示在网页上

编辑
我也试过这个

    <?php
    $proc = popen("ping -c 4 google.com", 'r');
    echo '<pre>';
    while (!feof($proc)) {
        echo fread($proc, 4096);
    }
    echo '</pre>';
    ?>
Run Code Online (Sandbox Code Playgroud)

但我仍然得到相同的结果..

编辑
当我试图在终端中执行这个PHP代码时,(php test.php)它正常工作,就像我们直接在服务器上执行ping一样.但在网页上它仍然是相同的.

小智 8

嗯,网络浏览器的奇怪行为。我正在使用这段代码:

<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);

function pingtest()
{
    $proc = popen("ping -c 5 google.com", 'r');
    while (!feof($proc))
    {
        echo "[".date("i:s")."] ".fread($proc, 4096);
    }
}

?>
<!DOCTYPE html>
<html>
<body>
  <pre>
Immediate output: 
<?php
pingtest();
?>
  </pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在浏览器中,接收到所有字节后将显示内容。但是,内容实际上是按时交付的,做这个测试:

wget -O - -q "http://localhost/ping.php"
Run Code Online (Sandbox Code Playgroud)

您将看到 php 和 apache2 按时交付了响应。

我在长时间任务上使用这种执行有一段时间了,但使用了更复杂的解决方案:

  • 界面的 html 文件
  • 运行长任务的 php 文件
  • 使用EventSource对象将 html 接口与 php 长执行连接起来(在 html5 上可用)

接口(测试.html)

<!DOCTYPE html>
<html>
<head>
    <title>Simple EventSource example</title>
</head>
<body>
    <script type="text/javascript">
    function eventsourcetest() {
        var ta = document.getElementById('output');
        var source = new EventSource('test.php');
        source.addEventListener('message', function(e) {
            if (e.data !== '') {
               ta.value += e.data + '\n';
            }
        }, false);
        source.addEventListener('error', function(e) {
            source.close();
        }, false);
    }
    </script>
    <p>Output:<br/><textarea id="output" style="width: 80%; height: 25em;"></textarea></p>
    <p><button type="button" onclick="eventsourcetest();">ping google.com</button>
</html>
Run Code Online (Sandbox Code Playgroud)

服务器端组件(test.php)

<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function echoEvent($datatext) {
    echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
}

echoEvent("Start!");
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc)) {
    echoEvent(fread($proc, 4096));
}
echoEvent("Finish!");
Run Code Online (Sandbox Code Playgroud)

将这两个文件放在网络服务器上的一个位置并输入 test.html,我认为这就是您从一开始就在寻找的内容。


max*_*max 1

使用输出缓冲和flush. 您可能还想研究 Symfony 2进程组件