SmxCde SmxCde - 3 months ago 12
Git Question

Execute GIT command from PHP and get error message back

When I try to execute something legitimate - it works, like

$result = `git tag`


returns me a list of available tags.

But when I do something that should return error, like

$result = `git clone https://`


it returns me
NULL
, but not message
fatal: could not create work tree dir ''.: No such file or directory
that I would see in the console.

How can I run a command and get error message from PHP?

UPD: It is not question "how to clone repo with using PHP", it is "How to retreive error message if something goes wrong" Does not matter what, in my example - "broken" repository link.

Answer

Try this

/**
 * Executes a command and reurns an array with exit code, stdout and stderr content
 * @param string $cmd - Command to execute
 * @param string|null $workdir - Default working directory
 * @return string[] - Array with keys: 'code' - exit code, 'out' - stdout, 'err' - stderr
 */
function execute($cmd, $workdir = null) {

    if (is_null($workdir)) {
        $workdir = __DIR__;
    }

    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin
       1 => array("pipe", "w"),  // stdout
       2 => array("pipe", "w"),  // stderr
    );

    $process = proc_open($cmd, $descriptorspec, $pipes, $workdir, null);

    $stdout = stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);

    return [
        'code' => proc_close($process),
        'out' => trim($stdout),
        'err' => trim($stderr),
    ];
}

And then test

$res = execute('git --version')

Array
(
    [code] => 0
    [out] => git version 2.1.4
    [err] => 
)

This will give you what you want

$res = execute('git clone http://...')

Array
(
    [code] => 128
    [out] => 
    [err] => Cloning into '...'...
             fatal: unable to access 'http://.../': Could not resolve host: ..
)