7

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
  • 813
  • 3
  • 11
  • 27

5 Answers5

17
if( ($fp = popen("your command", "r")) ) {
    while( !feof($fp) ){
        echo fread($fp, 1024);
        flush(); // you have to flush buffer
    }
    fclose($fp);
}
RolandasR
  • 3,030
  • 2
  • 25
  • 26
3

there is a dirty easy option

`yourcommand 1>&2`;

redirecting the stdout to the stderr.

useless
  • 1,876
  • 17
  • 18
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

Paulo H.
  • 1,228
  • 10
  • 15
  • 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? – EduAlm Dec 03 '11 at 21:18
  • 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. – Paulo H. Dec 03 '11 at 21:25
  • Got it. Actually is easier to use. Obrigado! :D – EduAlm Dec 03 '11 at 21:37
0

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

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();
raminious
  • 161
  • 1
  • 5