从PHP执行的Bash脚本实时输出 [英] Bash script live output executed from PHP

查看:215
本文介绍了从PHP执行的Bash脚本实时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从php执行bash脚本并实时获取其输出.

I'm trying to execute a bash script from php and getting its output in real time.

我正在应用在此处找到的答案:

I am applying the answers found here:

但是他们不为我工作.

当我以这种方式调用.sh脚本时,它可以正常工作:

When I invoke the .sh script on this way, it works fine:

<?php
  $output = shell_exec("./test.sh");
  echo "<pre>$output</pre>";
?>

但是,这样做时:

<?php
  echo '<pre>';
  passthru(./test.sh);
  echo '</pre>';
?>

或:

<?php
  while (@ ob_end_flush()); // end all output buffers if any
  $proc = popen(./test.sh, 'r');
  echo '<pre>';
  while (!feof($proc))
    {
    echo fread($proc, 4096);
    @ flush();
    }
  echo '</pre>';
?>

我的浏览器中没有输出.

I have no output in my browser.

在两种情况下,我也都尝试调用变量而不是脚本,

I also tried to call the variable instead of the script in both cases, I mean:

<?php
  $output = shell_exec("./test.sh");
  echo '<pre>';
  passthru($output);
  echo '</pre>';
?>

这是我的test.sh脚本:

This is my test.sh script:

#!/bin/bash
whoami
sleep 3
dmesg

推荐答案

使用以下内容:

<?php
ob_implicit_flush(true);
ob_end_flush();

$cmd = "bash /path/to/test.sh";

$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
);


$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());

if (is_resource($process)) {

    while ($s = fgets($pipes[1])) {
        print $s;

    }
}

?>

将test.sh更改为:

Change test.sh to:

#!/bin/bash
whoami
sleep 3
ls /

说明:

dmesg需要权限.您需要为此授予Web服务器的用户权限.在我的情况下,apache2是通过www-data用户运行的.

dmesg requires permissions. You need to grant webserver's user permissions for that. In my case apache2 is being run via www-data user.

ob_implicit_flush(true):打开隐式刷新.隐式刷新将导致在每次输出调用之后执行刷新操作,因此不再需要显式调用flush().

ob_implicit_flush(true): Turns implicit flushing on. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

ob_end_flush():关闭输出缓冲,因此我们会立即看到结果.

ob_end_flush(): Turns off output buffering, so we see results immediately.

这篇关于从PHP执行的Bash脚本实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆