php shell_exec with realtime updating

2019-01-24 13:25发布

I have this shell program that I want to execute by php. The problem is that it can potentially take a long time, and as of that I need it to have real-time updating to the user's browser.

I read that I may need to use popen() to do that, but I am sort of (ok, I really am :P) a PHP noob and can't figure out how I may be able to do it.

Would appreciate any help!

5条回答
我命由我不由天
2楼-- · 2019-01-24 13:30
if( ($fp = popen("your command", "r")) ) {
    while( !feof($fp) ){
        echo fread($fp, 1024);
        flush(); // you have to flush buffer
    }
    fclose($fp);
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-24 13:37

there are two possible behaviors:

  1. Non Block, where you need to do something else between flushs (@GameBit show how to do it).

  2. With Block, where you wait until the called command finish, in this case look passthru function

查看更多
成全新的幸福
4楼-- · 2019-01-24 13:41

I used this solution. It works fine for me.

$commandString = "myexe";

# Uncomment this line if you want to execute the command in background on Windows
# $commandString = "start /b $commandString";

$exec = popen($commandString, "r");

# echo "Async Code Test";

while($output = fgets($exec, 2048))
{
    echo "$output <br>\n";
    ob_flush();
    flush();
}

pclose($exec);
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-24 13:43

try this code (tested on Windows machine + wamp server)

        header('Content-Encoding: none;');

        set_time_limit(0);

        $handle = popen("<<< Your Shell Command >>>", "r");

        if (ob_get_level() == 0) 
            ob_start();

        while(!feof($handle)) {

            $buffer = fgets($handle);
            $buffer = trim(htmlspecialchars($buffer));

            echo $buffer . "<br />";
            echo str_pad('', 4096);    

            ob_flush();
            flush();
            sleep(1);
        }

        pclose($handle);
        ob_end_flush();
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-24 13:48

there is a dirty easy option

`yourcommand 1>&2`;

redirecting the stdout to the stderr.

查看更多
登录 后发表回答