# PHPWebHook **Repository Path**: qq505032809/PHPWebHook ## Basic Information - **Project Name**: PHPWebHook - **Description**: 服务器Git代码同步钩子 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 8 - **Created**: 2022-11-06 - **Last Updated**: 2022-11-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 服务器Git代码同步钩子 > 项目地址: * 码云:[https://gitee.com/kotlindev/PHPWebHook](https://gitee.com/kotlindev/PHPWebHook) * GitHub:[https://github.com/kotlindev/PHPWebHook](https://github.com/kotlindev/PHPWebHook) ## 一、什么是自动部署钩子? 简单地说自动部署钩子就是实现代码同步的一个程序,程序会在特定的情况会被触发,比如开发者将代码推送到git服务器时。本文使用PHP语言来编写一个能实现PHP项目自动部署的程序。 ## 二、目标需求 本文使用的是[码云](https://gitee.com)作为示例,在我们的业务服务器上部署钩子程序,当我们推送代码到[码云](https://gitee.com)仓库之后,使[码云](https://gitee.com)触发网络钩子功能,实现代码同步到业务服务器,达到项目自动部署的目的。首先需要实现代码同步功能即可,同时,代码同步到业务服务器之后,发送通知邮件给代码推送者。 ## 三、实现过程 ### 1.初始化项目 创建一个空的项目目录,在目录之下使用composer安装一个phpmailer邮件发送依赖库,composer指令如下: ```shell script composer require phpmailer/phpmailer ``` ### 2.定义邮件发送者对象 在项目根目录创建MailSender.php文件,首先在头部引入在1中安装的phpmailer依赖,如下: ```php CharSet = 'UTF-8'; //Server settings $mailSender->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mailSender->isSMTP(); // Send using SMTP $mailSender->Host = $this->smtp_host; // Set the SMTP server to send through $mailSender->SMTPAuth = true; // Enable SMTP authentication $mailSender->Username = $this->smtp_username; // SMTP username $mailSender->Password = $this->smtp_password; // SMTP password $mailSender->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted $mailSender->Port = $this->smtp_port; // TCP port to connect to //Recipients $mailSender->setFrom($this->smtp_username, $this->smtp_from); foreach ($addresses as $index => $address) { $mailSender->addAddress($address); // Name is optional } // Content $mailSender->isHTML(true); // Set email format to HTML $mailSender->Subject = $subject; $mailSender->Body = $body; //返回邮件对象 return $mailSender; } ``` ### 3.定义钩子 创建钩子入口文件index.php,并引入MailSender.php文件,如下代码: ```php &1'; $res = shell_exec($command); ``` 在以上代码中,先使用cd命令进入服务器上的项目目录,这里要注意,项目后缀路径必须和git服务器上的项目路径是一致的。再使用git pull命令拉取代码,使用2>&1指令会返回git执行结果。最后使用shell_exec执行命令并使用$res变量来接收执行结果。 最后,定义通知邮件发送内容,代码如下: ```php // 发送邮件 $addresses = [ $body['sender']['email'],// 将邮件发送给发送者 $body['repository']['owner']['email']// 将邮件发送给仓库所有者 ]; // 去除重复的内容 $addresses = array_unique($addresses); try { // 更新说明 $title = '部署成功通知'; // 构造邮件内容 $message = $body['head_commit']['message'];// 提交信息 $datetime = date('Y-m-d H:i:s', $body['timestamp'] / 1000);// 时间 $pusher = $body['pusher']['name'];// 提交人 $name = $body['project']['name'];// 项目名 $path = $body['project']['path'];// 路径 $content = <<
描述:$message
时间:$datetime
提交人:$pusher
项目名称:$name
项目路径:$path