问题描述
我只是在Linux服务器上试验PHP和shell_exec
.这是一个非常酷的功能,到目前为止,我真的很喜欢它.有没有一种方法可以查看命令运行时正在进行的实时输出?
I'm just experimenting with PHP and shell_exec
on my Linux server. It's a really cool function to use and I am really enjoying it so far. Is there a way to view the live output that is going on while the command is running?
例如,如果运行ping stackoverflow.com
,同时对目标地址执行ping操作,则每次ping操作时,都使用PHP显示结果吗?有可能吗?
For example, if ping stackoverflow.com
was run, while it is pinging the target address, every time it pings, show the results with PHP? Is that possible?
我希望看到缓冲区正在运行时进行实时更新.也许不可能,但肯定会很好.
I would love to see the live update of the buffer as it's running. Maybe it's not possible but it sure would be nice.
这是我正在尝试的代码,我尝试过的所有方式都始终在命令完成后显示结果.
This is the code I am trying and every way I have tried it always displays the results after the command is finished.
<?php
$cmd = 'ping -c 10 127.0.0.1';
$output = shell_exec($cmd);
echo "<pre>$output</pre>";
?>
我尝试将echo
部分放入循环中,但还是没有运气.有没有人建议将其显示在屏幕上,而不是等到命令完成后再显示?
I've tried putting the echo
part in a loop but still no luck. Anyone have any suggestions on making it show the live output to the screen instead of waiting until the command is complete?
我尝试了exec
,shell_exec
,system
和passthru
.完成后,每个人都会显示内容.除非我使用了错误的语法或没有正确设置循环.
I've tried exec
, shell_exec
, system
, and passthru
. Everyone of them displays the content after it's finished. Unless I'm using the wrong syntax or I'm not setting up the loop correctly.
推荐答案
要读取进程的输出,可以使用popen()
.您的脚本将与程序并行运行,并且可以通过读取和写入脚本的输出/输入来与脚本进行交互,就像文件一样.
To read the output of a process, popen()
is the way to go. Your script will run in parallel with the program and you can interact with it by reading and writing it's output/input as if it was a file.
但是,如果您只想转储结果,直接将其发送给用户,则您可以切入正题并使用passthru()
:
But if you just want to dump it's result straight to the user you can cut to the chase and use passthru()
:
echo '<pre>';
passthru($cmd);
echo '</pre>';
如果要在程序运行时在运行时显示输出,可以执行以下操作:
If you want to display the output at run time as the program goes, you can do this:
while (@ ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
@ flush();
}
echo '</pre>';
此代码应运行命令,并在运行时将输出直接推送给最终用户.
This code should run the command and push the output straight to the end user at run time.
这篇关于PHP阅读shell_exec实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!