php shell_exec with realtime updating

前端 未结 5 741
予麋鹿
予麋鹿 2020-12-17 00:03

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

相关标签:
5条回答
  • 2020-12-17 00:35

    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);
    
    0 讨论(0)
  • 2020-12-17 00:36

    there is a dirty easy option

    `yourcommand 1>&2`;
    

    redirecting the stdout to the stderr.

    0 讨论(0)
  • 2020-12-17 00:46
    if( ($fp = popen("your command", "r")) ) {
        while( !feof($fp) ){
            echo fread($fp, 1024);
            flush(); // you have to flush buffer
        }
        fclose($fp);
    }
    
    0 讨论(0)
  • 2020-12-17 00:52

    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

    0 讨论(0)
  • 2020-12-17 01:02

    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();
    
    0 讨论(0)
提交回复
热议问题