1.配置github仓库Webhooks

01.jpg

2.php 配置

宝塔禁用函数去掉execshell_exec,重启php

3.新建git-webhook.php文件:

<?php
//git webhook 自动部署脚本
$requestBody = file_get_contents("php://input");    //接收数据
if (empty($requestBody)) {              //判断数据是不是空
    die('send fail');
}
$content = json_decode($requestBody, true);     //数据转换
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master') {
    $res = shell_exec('cd /www/wwwroot/surge/ && rm -rf YuMing/ && git clone https://github.com/yangyzp/YuMing.git');           //PHP函数执行git命令
    $res_log = '-------------------------'.PHP_EOL;
    $res_log .= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push'.$res;
    file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//将每次拉取信息追加写入到日志里
}
  • 其中 “cd /www/wwwroot/surge/ && rm -rf YuMing/ && git clone https://github.com/yangyzp/YuMing.git” 依次为:进入指定目录 → 删除目录下指定文件夹 → 拉取git(按需修改)

或者

<?php
//git webhook 自动部署脚本
$requestBody = file_get_contents("php://input");    //接收数据
if (empty($requestBody)) {              //判断数据是不是空
    die('send fail');
}
$content = json_decode($requestBody, true);     //数据转换
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master') {
    $res = shell_exec('cd /www/wwwroot/YuMing/YuMing/ && git pull');           //PHP函数执行git命令
    $res_log = '-------------------------'.PHP_EOL;
    $res_log .= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push'.$res;
    file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//将每次拉取信息追加写入到日志里
}

.gitcd目录在同一目录

<?php
//git webhook 自动部署脚本
$requestBody = file_get_contents("php://input");    //接收数据
if (empty($requestBody)) {              //判断数据是不是空
    die('send fail');
}
$content = json_decode($requestBody, true);     //数据转换
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master') {
    $res = shell_exec('cd /www/wwwroot/YuMing/YuMing/ && git reset --hard && git pull');           //PHP函数执行git命令
    $res_log = '-------------------------'.PHP_EOL;
    $res_log .= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push'.$res;
    file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//将每次拉取信息追加写入到日志里
}

4.如设置了nginx规则,需要把git规则删掉

Snipaste_2022-09-04_19-55-32.png

最后修改:2022 年 10 月 11 日
如果觉得我的文章对你有用,请随意赞赏