php shell_exec with realtime updating

10,035

Solution 1

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

Solution 2

there is a dirty easy option

`yourcommand 1>&2`;

redirecting the stdout to the stderr.

Solution 3

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

Share:
10,035
EduAlm
Author by

EduAlm

Updated on June 17, 2022

Comments

  • EduAlm
    EduAlm almost 2 years

    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!

  • EduAlm
    EduAlm over 12 years
    How would I do it with passthru? Also, is there any disadvantage of using @GameBit's code if I don't need to do anything between flushes?
  • Paulo H.
    Paulo H. over 12 years
    You pass the same command as in the solution with popen, but the output from external program goes directly to output... If you know the difference between fopen and readfile, is practically the same thing, only with processes. First allow you read byte by byte and put into a variable, process the data, another simple read and write to output directly, without any action.
  • EduAlm
    EduAlm over 12 years
    Got it. Actually is easier to use. Obrigado! :D
  • dellsala
    dellsala over 9 years
    Why do you have to flush the buffer?