Bash script live output executed from PHP

廉价感情. 提交于 2019-12-02 02:47:23

Use the following:

<?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;

    }
}

?>

Change test.sh to:

#!/bin/bash
whoami
sleep 3
ls /

Explanation:

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): 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(): Turns off output buffering, so we see results immediately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!