我正在尝试在网页上运行一个进程,该进程将实时返回其输出。例如,如果我运行'ping‘进程,它应该在每次返回新行时更新我的页面(现在,当我使用exec(command,output)时,我被迫使用-c选项,并等待进程结束才能看到网页上的输出)。在php中可以做到这一点吗?
我也在想,当有人离开页面时,什么才是终止这种进程的正确方法。在“ping”进程的情况下,我仍然能够在系统监视器中看到正在运行的进程(这是有意义的)。
发布于 2011-05-26 19:48:58
这对我很有效:
$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>";
发布于 2011-05-10 21:30:49
这是显示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);
}
我希望这对其他用谷歌搜索过的人有所帮助。
发布于 2017-09-07 16:37:51
已检查所有答案,均不起作用...
找到解决方案Here
它可以在windows上工作(我认为这个答案对用户在那里搜索很有帮助)
<?php
$a = popen('ping www.google.com', 'r');
while($b = fgets($a, 2048)) {
echo $b."<br>\n";
ob_flush();flush();
}
pclose($a);
?>
https://stackoverflow.com/questions/1281140
复制