PHP: Run a command and capture STDOUT and STDERR separately
I need to run a shell command in PHP and capture STDOUT and STDERR separately. This function lets you run a command and returns a hash with the various components and outputs.
function run_cmd($cmd) {
$start = hrtime(true);
$cmd = escapeshellcmd($cmd);
$process = proc_open($cmd, [
1 => ['pipe', 'w'], // STDOUT
2 => ['pipe', 'w'], // STDERR
], $pipes);
if (!is_resource($process)) { return []; }
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exit = proc_close($process);
$ret = [
'exit_code' => $exit,
'stdout' => trim($stdout),
'stderr' => trim($stderr),
'cmd' => $cmd,
'exec_ms' => (hrtime(true) - $start) / 1000000,
];
return $ret;
}