Get results from php exec () while the command is still working?

When I run exec from PHP like this:

 $result = exec('command'); 

The results of this will be saved in $result . But in my current case, my team may take several minutes and display the results as it runs. Is there any way to get a way out during its operation? I know that the passthru method outputs the results for the browser, but I really want it directly.

+4
source share
5 answers

You should take a look at proc_open

After the output stream is not blocked (with stream_set_blocking ), you can read it whenever you want, without blocking your PHP code.

-Edit- If you use

 $result = exec('command > /path/to/file &'); 

It will work in the background and you can read the output in / path / to / file

+5
source

Perhaps this is not the best way to do this (but worked for me):

 <?php $cmd = "ping 127.0.0.1 -c 5"; //example command $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "a") ); $pipes = array(); $process = proc_open($cmd, $descriptorspec, $pipes, null, null); echo "Start process:\n"; $str = ""; if(is_resource($process)) { do { $curStr = fgets($pipes[1]); //will wait for a end of line echo $curStr; $str .= $curStr; $arr = proc_get_status($process); }while($arr['running']); }else{ echo "Unable to start process\n"; } fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process); echo "\n\n\nDone\n"; echo "Result is:\n----\n".$str."\n----\n"; ?> 
+4
source

specify the second argument

 exec('command', $result); 

If an output argument is present, then the specified array will be filled with each line of output from the command. Trailing space, such as \ n, is not included in this array. Note that if the array already contains some elements, exec () will add to the end of the array. If you do not want the function to add elements, call unset () in the array before passing it to exec ().

+3
source

You may be able to achieve what you need using passthru() in conjunction with output buffering . Not sure, however.

0
source

For whoever he helped, I used Eddie's answer and changed it for my own purposes (outputting a MySQL dump file without flooding the server RAM)

 $dumpCommand = "mysqldump --skip-lock-tables -u $dbuser -p$dbpasswd $dbname"; $dumpFileName = 'backup_'.$dbname.'-'.date('Ymd-Hi').'.sql'; $descriptorSpec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "a") ); $pipes = array(); $process = proc_open($dumpCommand, $descriptorSpec, $pipes, null, null); if(!is_resource($process)) { die('Unable to start process'); } header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$dumpFileName.'"'); do { echo fgets($pipes[1]); // Will wait for EOL $arrStatus = proc_get_status($process); } while($arrStatus['running']); fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process); 
0
source

All Articles