首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中运行实时输出的进程

在PHP中运行实时输出的进程
EN

Stack Overflow用户
提问于 2009-08-15 04:23:43
回答 8查看 92K关注 0票数 75

我正在尝试在网页上运行一个进程,该进程将实时返回其输出。例如,如果我运行'ping‘进程,它应该在每次返回新行时更新我的页面(现在,当我使用exec(command,output)时,我被迫使用-c选项,并等待进程结束才能看到网页上的输出)。在php中可以做到这一点吗?

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

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-05-27 03:48:58

这对我很有效:

代码语言:javascript
复制
$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>";
票数 100
EN

Stack Overflow用户

发布于 2011-05-11 05:30:49

这是显示shell命令实时输出的一种很好的方式:

代码语言:javascript
复制
<?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);

您将需要此函数来防止输出缓冲:

代码语言:javascript
复制
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编写的虚拟示例:

代码语言:javascript
复制
<?php
header("Content-type: text/plain");

disable_ob();

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

我希望这对其他用谷歌搜索过的人有所帮助。

票数 37
EN

Stack Overflow用户

发布于 2017-09-08 00:37:51

已检查所有答案,均不起作用...

找到解决方案Here

它可以在windows上工作(我认为这个答案对用户在那里搜索很有帮助)

代码语言:javascript
复制
<?php
    $a = popen('ping www.google.com', 'r'); 
    
    while($b = fgets($a, 2048)) { 
        echo $b."<br>\n"; 
        ob_flush();flush(); 
    }

    pclose($a); 
?>
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1281140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档