简体   繁体   中英

php output system() in real time

I'm trying to make a system call and have each line sent to the browser in real time

echo('<pre>');
system('ping -c 10 www.google.com');
echo('</pre>);

This works when I call it from the command line (each line of the ping is output one at a time). However it does not work when I try to open with a browser (firefox or chrome).

I am almost certain this has something to do with the output buffering enforced by the browser. They will not display new data unless it is above a cetrain threshold. Solutions to these kind of problems typically involve outputting a bunch of blank characters, ie str_repeat(' ',1024*64) . Can you think of any way to get the browser to display the output in real time?

You can not do it this way. your php request is running once and retrun one response.

Also the result of system function is shown at the end of the execution of your command. What you see in your command line is only the logs of command it self not your php code.

I suggest to use a kind of long polling technologies or soquet-io to establish a continues / real time communication with your server.

<?php
// WARNING : this define depends from web browser
//           Google Chrome     => 1024
//           Mozilla Firefox   => 2048 (not sure)
//           Internet Explorer => Much more ... but works :)
define ("NUMBER_BYTE_PADDERS", "1024" );

ob_implicit_flush(1);
print padder ("first message") . "<br />";

sleep (5);
print padder ("second message after 5 seconds") . "<br />";

sleep (10);
print padder ("third message after 15 seconds") . "<br />";


function padder ($msg) {
    for ($i=0 ; $i < NUMBER_BYTE_PADDERS ; $i++) {
        $msg .= ' ';
    }
    return $msg;
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM