在 PHP 中使用实时输出运行进程

新手上路,请多包涵

我正在尝试在网页上运行一个进程,该进程将实时返回其输出。例如,如果我运行“ping”进程,它应该在每次返回新行时更新我的页面(现在,当我使用 exec(command, output) 时,我被迫使用 -c 选项并等到进程完成才能看到在我的网页上输出)。是否可以在 php 中执行此操作?

我也想知道当有人离开页面时终止这种进程的正确方法是什么。在“ping”进程的情况下,我仍然能够看到系统监视器中运行的进程(这是有道理的)。

原文由 Maksim Vi. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 649
2 个回答

这对我有用:

 $cmd = "ping 127.0.0.1";

$descriptorspec = array(
   0 => array("pipe", "r"),   // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),   // stdout is a pipe that the child will write to
   2 => array("pipe", "w")    // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
echo "<pre>";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        flush();
    }
}
echo "</pre>";

原文由 egafni 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是显示 shell 命令实时输出的好方法:

 <?php
header("Content-type: text/plain");

// tell php to automatically flush after every output
// including lines of output produced by shell commands
disable_ob();

$command = 'rsync -avz /your/directory1 /your/directory2';
system($command);

您将需要此功能来防止输出缓冲:

 function disable_ob() {
    // Turn off output buffering
    ini_set('output_buffering', 'off');
    // Turn off PHP output compression
    ini_set('zlib.output_compression', false);
    // Implicitly flush the buffer(s)
    ini_set('implicit_flush', true);
    ob_implicit_flush(true);
    // Clear, and turn off output buffering
    while (ob_get_level() > 0) {
        // Get the curent level
        $level = ob_get_level();
        // End the buffering
        ob_end_clean();
        // If the current level has not changed, abort
        if (ob_get_level() == $level) break;
    }
    // Disable apache output buffering/compression
    if (function_exists('apache_setenv')) {
        apache_setenv('no-gzip', '1');
        apache_setenv('dont-vary', '1');
    }
}

虽然它不适用于我尝试过的每台服务器,但我希望我能就在你的 php 配置中寻找什么提供建议,以确定你是否应该拔掉头发试图让这种行为起作用在你的服务器上!还有人知道吗?

这是一个纯 PHP 的虚拟示例:

 <?php
header("Content-type: text/plain");

disable_ob();

for($i=0;$i<10;$i++)
{
    echo $i . "\n";
    usleep(300000);
}

我希望这可以帮助其他在这里用谷歌搜索的人。

原文由 Robb 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题