需求监测数据库某字段,当为2,发送异常邮件;
有单独的脚本来监测程序状态并更新数据库,再次不做赘述,只分享PHP监测数据并使用PHPMailer发送邮件;
主要文件 email.php
<?php
date_default_timezone_set('Asia/Shanghai');
ignore_user_abort(); //关闭浏览器后,继续执行php代码
set_time_limit(0); //程序执行时间无限制
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require "db_config.php";//数据库配置文件
require './src/Exception.php';
require './src/PHPMailer.php';
require './src/SMTP.php';
$sleep_time = 1800;//设置监测间隔
$array = array();
$switch = include 'switch.php';//控制开关
$setting = include 'setting.php';//控制设置(自定义配置)
while ($switch) {
$switch = include 'switch.php';
$msg = "";
$log = "";
$array = array();
$conn = new mysqli(xxx, xxx, xxx);
$sql = "你的sql";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$array[] = $row;
}
$conn->close();
foreach ($array as $arr) {
if (你的判断条件) {
if ($setting == 1) {//这里可以根据setting来设置了
$msg .= "拼接你要的信息(1)";
} else {
$msg .= "拼接你要的信息(2)";
}
}
}
$body = $msg . date('Y-m-d H:i:s');
if ($setting == 1) {
$body = "你的信息";
}
if ($msg != "" && $msg != null) {
$mail = new PHPMailer(true);
try {
//服务器配置
$mail->CharSet = "UTF-8";
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'xxx';
$mail->SMTPAuth = true;
$mail->Username = 'xxx';
$mail->Password = 'xxx';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->setFrom('xxx.com', 'xxx'); // 发件人
$mail->addAddress('xxx.com', 'Test'); // 收件人
$mail->isHTML(true);
$mail->Subject = '你的标题';
$mail->Body = $body;
$mail->AltBody = $msg . date('Y-m-d H:i:s');
$mail->send();
} catch (Exception $e) {
file_put_contents("log" . date("Y-m") . ".log", '邮件发送失败:' . $mail->ErrorInfo . ";", FILE_APPEND);//失败了的话输出个log
}
}
sleep($sleep_time);
if ($switch == 0) {
exit();
}
}
exit();
switch.php 控制开关
<?php
return 1;
?>
setting.php 配置项
<?php
return 1;//这里根据你的需求来设计就行
?>
完成后直接浏览器运行并关闭即可,此时便会持续在后台运行,直到你把switch 中改为0;