How does one output the contents of a shell script executed from php in realtime?
Say I call scriptA from scriptB; how can I output the results of A before the script is finished?
Script A:
<?php
for ($i = 0; $i < 10000; $i++) {
echo $i;
sleep(1);
}
Script B:
<?php
exec('php /path/to/scriptA.php', $output);
foreach ($output as $line) {
// This will only output when script A completes.
echo $line . "
";
}
The answer is surprisingly complicated. Rather than use exec
you'll want to look at proc_open
.
This worked for me:
<?php
ob_implicit_flush();
$command = "php /path/to/scriptA";
$descriptors = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$pipes = [];
$process = proc_open($command, $descriptors, $pipes, dirname(__SCRIPT__), []);
if (is_resource($process)) {
$char = '';
while (($char = fgetc($pipes[1])) !== false) {
echo $char;
flush();
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
}