gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:42 26 4
gpt4 key购买 nike

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

$result = `git tag`

返回可用标签列表。

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

$result = `git clone https://`

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

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

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

最佳答案

试试这个

/**
* 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),
];
}

然后测试

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

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

这会给你想要的东西

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

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

关于php - 从 PHP 执行 GIT 命令并返回错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38967368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com