Skip to content

PHP: Call a command and get the return code and outputΒΆ

Eventhough PHP supports starting commands in the background and wait for the result, the return code often is not passed correctly.

As a workaround you may use a shell command to pass the return code to a dedicated file descriptor which is then read by PHP.

<?php
$command = 'some-command-to-execute';

$descriptors = [
    0 => ['pipe', 'r'],   // stdin
    1 => ['pipe', 'w'],   // stdout
    2 => ['pipe', 'w'],   // stderr
    3 => ['pipe', 'w'],   // file descriptor for exit code
];
$process = proc_open($command.'; echo $? 2>&1 >&3', $descriptors, $pipes);
if (is_resource($process)) {
    while ($output = fgets($pipes[1])) {
        $shellOutput .= $output;
    }
}
if (!feof($pipes[3])) {
    $shellResult = (int) rtrim(fgets($pipes[3], 5), "\n");
}
fclose($pipes[3]);
proc_close($process);

// $shellOutput will contain the output of stdout and stderr
// $shellResult will not contain the return code