You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP shell_exec()从cPanel虚拟主机向Github推送文件失败求助

解决PHP执行git push失败的问题

第一步:捕获完整错误信息

当前代码仅捕获标准输出,无法获取错误详情。修改代码将标准错误重定向至标准输出,以便排查具体问题:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 重定向stderr到stdout,获取所有执行输出
$push = shell_exec('git push -u origin master 2>&1');

if($push === null) {
  echo "Error executing git push command";
} else {
  echo "<pre>$push</pre>";
}

常见问题及解决方法

1. Git命令路径未找到

PHP的shell环境PATH可能未包含git执行路径,先在cPanel终端执行which git获取绝对路径(例如/usr/bin/git),再在代码中使用绝对路径调用:

$push = shell_exec('/usr/bin/git push -u origin master 2>&1');

2. 缺少Git凭据

终端手动输入的令牌凭据不会被PHP进程继承,需将仓库远程URL修改为包含个人令牌的形式,在cPanel终端执行:

git remote set-url origin https://<你的GitHub个人令牌>@github.com/<你的用户名>/<仓库名>.git

替换<你的GitHub个人令牌>、<你的用户名>和<仓库名>为实际信息,之后PHP执行git push时会自动用URL中的令牌完成验证。

3. 目录权限不足

确保PHP运行用户(通常为nobody或apache)对Git仓库目录有读写权限,在cPanel终端执行:

chown -R <你的cPanel用户名>:<你的cPanel用户名> /path/to/your/repo
chmod -R 755 /path/to/your/repo

替换<你的cPanel用户名>和/path/to/your/repo为实际信息。

4. HOME环境变量缺失

Git需要HOME变量定位凭据存储位置,PHP的shell环境可能未设置该变量,可在命令前指定:

$push = shell_exec('HOME=/home/<你的cPanel用户名> git push -u origin master 2>&1');

替换<你的cPanel用户名>为实际的cPanel主目录用户名。

内容的提问来源于stack exchange,提问作者stkuser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:55:57