Skip to content
Advertisement

php run command line and pipe std err to variable

I am trying to figure out how to run a command line program within php and output both stout and stderr to a variable. All the examples either output the command line directly to the screen, or only output stdout for example

$data =  shell_exec('ls -sdlfkjwer');

will output the following directly to the screen and not store anything in $data

ls: invalid option -- 'j'
Try 'ls --help' for more information.

And the following will store the output in $data

$data =  shell_exec('ls -la');

because it is going to std out since there is no error. So the question is how can I route the std error to a variable as well when running command line programs from php?

This question does not answer my question because I am trying to do the exact OPPOSITE. I am trying to get it to a variable. PHP – How to get Shell errors echoed out to screen

Thank you

Advertisement

Answer

ok I was able to find a solution. You need to set up a native process to configure the pipes.

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w") // stderr is a file to write to
);
$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('ls -lasdfsdfwefwekj', $descriptorspec, $pipes, $cwd, $env);


/*fwrite($pipes[0], '<?php print_r($_ENV); ?>');
*/
fclose($pipes[0]);

echo "stdout=".stream_get_contents($pipes[1]);
echo "stderr=".stream_get_contents($pipes[2]);

fclose($pipes[1]);
fclose($pipes[2]);

$return_value = proc_close($process);

echo "command returned $return_valuen";
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement