php shell_exec with realtime updating

断了今生、忘了曾经 提交于 2019-11-27 18:34:26

问题


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!


回答1:


if( ($fp = popen("your command", "r")) ) {
    while( !feof($fp) ){
        echo fread($fp, 1024);
        flush(); // you have to flush buffer
    }
    fclose($fp);
}



回答2:


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




回答3:


there is a dirty easy option

`yourcommand 1>&2`;

redirecting the stdout to the stderr.




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/8370628/php-shell-exec-with-realtime-updating

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