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.

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);
}
// Example usage.
list($return_code, $stdout, $stderr) = pipe_exec('ls');
View this page on GitHub.
Posted .

5 comments

  1. anonymous –

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

  2. anonymous –

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

  3. anonymous –

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

  4. anonymous –

    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. anonymous –

    @license, public domain.

Leave a Reply