【问题标题】:Execute git commit from php file in current directory从当前目录中的 php 文件执行 git commit
【发布时间】:2012-07-18 20:11:22
【问题描述】:

我尝试执行这段代码,但它什么也没做。 但是当在 shell_exec 中输入“git show --summary”时,它会返回 git 状态。

if($_GET['action']=='add'){
    $output = shell_exec('git add *');
    echo "Add:<pre>$output</pre>";
}
if($_GET['action']=='commit'){
    $output = shell_exec('git commit -m "'.$_POST["txt"].'" ');
    echo "Commit:<pre>$output</pre>";

}

是否可以从 php 提交 git,以及如何提交?

【问题讨论】:

  • 我假设您使用的是 apache?您的 apache 用户运行在什么特权级别? Git 涉及写入隐藏的.git 文件夹。如果没有适当的写入权限,它将失败。

标签: php linux git apache shell


【解决方案1】:

如果命令失败,shell_exec 将返回NULL。这几乎肯定会发生……问题是为什么。您将无法使用shell_exec 找到答案。

我建议您改用 exec,这样您至少可以弄清楚调用的状态以及出了什么问题。

http://www.php.net/manual/en/function.exec.php

这将允许您设置一些变量,这些变量将填充系统内部操作系统调用的返回值。

$shell_output = array();
$status = NULL;

if($_GET['action']=='add'){
    $output = shell_exec('git add *',$shell_output,$status);
    print_r($shell_output)
    print_r($status);
}
if($_GET['action']=='commit'){
    $output = shell_exec('git commit -m "'.$_POST["txt"].'" ',$shell_output,$status);
    print_r($shell_output)
    print_r($status);
}

我猜你的权限有问题。 git 中的commit 需要对该目录的“.git”文件夹的写入权限。

另外,请确保您在正确的目录中操作!运行 PHP 实例的 apache 用户可能已经或可能尚未 cded 到 repo 所在的正确文件夹。您可能需要在命令中添加cd path_to_repo &amp;&amp; git commit 才能首先移动到正确的目录。我会先用绝对路径来调试它。

还有一点建议...如果您尝试设置基于 PHP 的 git 客户端,您将不得不处理大量失败案例,其中一个在这段代码中很明显。 . 在没有新文件被修改时尝试提交。如果您需要关注这些案例,我建议您查看社区解决方案:

Is there a good php git client with http support?

【讨论】:

  • 我不是在构建客户端,我需要快速添加/提交一个文件夹的方法。我每天都用命令行来做。
【解决方案2】:

我建议您在 git commit 中添加姓名和电子邮件:

$output = shell_exec('git -c user.name="www-data" -c user.email="no-replay@example.org" commit -m "'.$_POST["txt"].'" ', $shell_output, $status);

错误可以在服务器错误文件中找到,例如:/var/log/apache2/error.log

cat /var/log/apache2/error.log

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 2015-09-12
    • 2014-05-06
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多