github私有库认证必须使用personal access token(pat),而非ssh密钥;php需通过https+pat方式调用git clone,且pat须勾选repo权限、通过环境变量传入并用escapeshellarg()安全拼接url。
GitHub私有库认证必须用 Personal Access Token,不是 SSH 密钥
PHP 本身不直接“读取”或“使用” SSH 私钥去拉 GitHub 私有库(比如 git clone [email protected]:user/repo.git),因为 PHP 进程通常没权限加载用户 ssh-agent 或读取 ~/.ssh/id_rsa。实际能走通的路径只有 HTTPS + Personal Access Token(PAT)——这是 GitHub 官方唯一支持的、可在脚本/服务端安全使用的认证方式。
常见错误是把本地 Git 配置里的 SSH 密钥直接塞进 PHP 的 exec("git clone ..."),结果报错:Permission denied (publickey) 或 fatal: Could not read from remote repository。
- GitHub 已弃用密码认证,
git clone https://user:[email protected]/...会失败 - PAT 必须勾选
repo权限(私有库需要repo:status、repo_deployment等子项也建议勾上) - 不要把 PAT 写死在代码里,务必通过环境变量传入,例如
$_ENV['GITHUB_TOKEN']
PHP 执行 git clone 时注入 token 的三种写法
核心原理:把 token 插入 HTTPS URL 中,让 Git 命令自身完成认证。URL 格式为 https://<token>@github.com/user/repo.git</token>。注意 token 是明文拼接,所以必须确保命令不被日志或 ps aux 泄露。
推荐用 escapeshellarg() 包裹 token 和路径,避免 shell 注入:
立即学习“PHP免费学习笔记(深入)”;