Home » Php » How to capture multi-line output for commands issued with PHP exec?

How to capture multi-line output for commands issued with PHP exec?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to execute system commands in PHP and capture the output of those commands where that output covers multiple lines. I am using exec(), but it seems like it only returns a value for commands that generate output on a single line.

For example, if I run date at the command line I get:

 Wed May 15 15:07:32 EST 2013

As expected, if I run this command from PHP as an exec using this…

exec("date",  $exec_results);

…then the value of $exec_results becomes…

Array ( [0] => Wed May 15 15:07:32 EST 2013 )

However, when I run time from the command line I get this…

real 0m0.000s
user 0m0.000s
sys  0m0.000s

…but when I do it from PHP with this…

exec("time",  $exec_results);

… the value of $exec_results is empty:

Array( )

I don’t actually need to run date or time in my application but these are just examples of how the single line vs. multi-line output on the command line seems to change what gets back to PHP.

The documents say:

If the output argument is present, then the specified array will be filled with every line of output from the command.

So why is the $exec_results array not being filled with all the lines seen when the time command is run in the command line?

Notes – I have run the command line entries as the apache user to rule out privileges.

How to&Answers:

This should work for you

ob_start();
passthru("ls -la");
$dat = ob_get_clean();

Answer:

I changed my post for the working solution:

Use the ‘script’ command of unix to get the result.
you will surely have to remove “extra lines” of the temporary log file.

exec('script -c "time" /tmp/yourfile.txt');
$result = file('/tmp/yourfile.txt');
var_dump($result);

You should always put a full path to your temporary file, anywhere you put it

that’s it !

Answer:

So here’s the full list:

  • system() => Execute an external program and displays the output.
  • passthru() => Same than system, but casts the output in binary “as is” from the shell to the PHP output (typically the HTTP response).
  • exec() => Captures the output and only the last line of the output into a string.
  • shell_exec() => Same than exec, but capturing full output, not only the last line.

So, my preference: Always use shell_exec() and then do with the full-string whatever you want.

How to test

$ php -a
Interactive mode enabled

php > echo( shell_exec( "echo hello; echo bye" ) );
hello
bye
php >

https://www.php.net/manual/en/function.shell-exec.php