github webhook php,GitHub利用webhook实现push时项目自动部署

在网站根目录下放置 webhook.php 自动部署文件,然后GitHub服务器的对应项目的 webhooks 配置上该文件的网址(Payload URL)与 密钥(Secret),需启用php的shell_exec函数。

49805a724d47e51c1434e1bf4ef1cc3d.png

webhook.php 代码

$target = '/home/www/im'; // 生产环境web目录

//密钥

$secret = "123456";

$wwwUser = 'www';

$wwwGroup = 'www';

//日志文件地址

$fs = fopen('../storage/logs/gitHubAuto_hook.log', 'a');

//获取GitHub发送的内容

$json = file_get_contents('php://input');

$content = json_decode($json, true);

//github发送过来的签名

$signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];

if (!$signature) {

fclose($fs);

return http_response_code(404);

}

list($algo, $hash) = explode('=', $signature, 2);

//计算签名

$payloadHash = hash_hmac($algo, $json, $secret);

// 判断签名是否匹配

if ($hash === $payloadHash) {

$cmd = "cd $target && git pull";

$res = shell_exec($cmd);

$res_log .= 'Success:'.PHP_EOL;

$res_log .= $content['head_commit']['author']['name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . count($content['commits']) . '个commit:' . PHP_EOL;

$res_log .= $res.PHP_EOL;

$res_log .= '======================================================================='.PHP_EOL;

fwrite($fs, $res_log);

$fs and fclose($fs);

} else {

$res_log = 'Error:'.PHP_EOL;

$res_log .= $content['head_commit']['author']['name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . count($content['commits']) . '>个commit:' . PHP_EOL;

$res_log .= '密钥不正确不能pull'.PHP_EOL;

$res_log .= '======================================================================='.PHP_EOL;

fwrite($fs, $res_log);

$fs and fclose($fs);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值