dora0817 2016-08-16 05:43
浏览 246
已采纳

从PHP执行GIT命令并获取错误消息

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.

  • 写回答

2条回答 默认 最新

  • dqdl6469 2016-08-17 23:22
    关注

    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: ..
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启