从 PHP 执行 GIT 命令并返回错误消息

Smx*_*Cde 0 php linux git console

当我尝试执行一些合法的事情时 - 它有效,就像

$result = `git tag`
Run Code Online (Sandbox Code Playgroud)

返回给我可用标签的列表。

但是当我做一些应该返回错误的事情时,比如

$result = `git clone https://`
Run Code Online (Sandbox Code Playgroud)

它返回我NULL,但不是fatal: could not create work tree dir ''.: No such file or directory我在控制台中看到的消息。

如何运行命令并从 PHP 获取错误消息?

UPD:这不是问题“如何使用 PHP 克隆存储库”,而是“如果出现问题如何检索错误消息”,在我的示例中,“损坏的”存储库链接无关紧要。

Pav*_*vel 5

尝试这个

/**
 * 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),
    ];
}
Run Code Online (Sandbox Code Playgroud)

然后测试

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

Array
(
    [code] => 0
    [out] => git version 2.1.4
    [err] => 
)
Run Code Online (Sandbox Code Playgroud)

这会给你你想要的

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

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