'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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source