Dark Launch

PHP exec() + stderr, stdout, & return code

Run a command in php and get standard output (stdout), standard error (stderr), and the return code / return value.

PHP
function pipe_exec($cmd, $input='') {
    $proc = proc_open($cmd, array(array('pipe', 'r'),
                                  array('pipe', 'w'),
                                  array('pipe', 'w')), $pipes);
    fwrite($pipes[0], $input);
    fclose($pipes[0]);
 
    $stdout = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
 
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
 
    $return_code = (int)proc_close($proc);
 
    return array($return_code, $stdout, $stderr);
}
PHP
// Example usage.
list($return_code, $stdout, $stderr) = pipe_exec('ls');

Comments


  1. Thanks. Is there any way to both read stderr and allow it out as if it hasn't been interfered with?

  2. `tee' might be what you're looking for.

  3. "tee - read from standard input and write to standard output and files"

  4. Hi, thanks for this useful piece of code. Could you clarify under which license you're providing it (I'd suggest public domain, CC0, or BSD-2 clause), and if you are the original writer ? Thank you !

  5. @license, public domain.