嚴重錯誤發生時即時郵件通知管理員,配合 error_log() 第 2 參數設為 1(郵件模式)實現。本文說明 Windows 下 sendmail 配置與程式碼範例。
[mail function]
SMTP = smtp.yourprovider.com
smtp_port = 25
sendmail_from = admin@yourdomain.com
; Windows 需指定 sendmail 程式路徑(如使用 sendmail.exe 或 msmtp)
sendmail_path = "G:\sendmail\sendmail.exe -t"
注意:Windows 內建無 sendmail,需安裝第三方工具(如 msmtp、sendmail for Windows)並指定路徑。
<?php
ini_set('display_errors', 0);
ini_set('log_errors', 'on');
error_reporting(-1);
// 參數 1 表示以郵件發送
error_log(
'當前系統被攻擊,產生了致命錯誤',
1, // message_type = 1 (email)
'admin@yourdomain.com', // 收件人
'From: monitor@yourdomain.com' . "\r\n" .
'X-Priority: 1' // 額外標頭:高優先級
);
error_log(string $message, int $type = 0, string $destination = '', string $headers = ''): bool
| type | 行為 | destination |
|---|---|---|
| 0 | 系統日誌(php.ini error_log 指定) | 忽略 |
| 1 | 發送郵件 | 收件人 Email |
| 3 | 寫入檔案 | 檔案路徑 |
| 4 | 直接發送給 SAPI 日誌處理器 | 忽略 |
set_error_handler(function($severity, $message, $file, $line) {
if ($severity & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)) {
$msg = "[$severity] $message in $file:$line";
error_log($msg, 1, 'admin@yourdomain.com', 'From: monitor@yourdomain.com');
}
return false; // 繼續標準處理
});
Content-Type: text/plain; charset=utf-8E_USER_ERROR、E_ERROR 等級發郵件,WARNING/NOTICE 寫入檔案/系統日誌郵件通知是最後一道防線,配合完善的日誌與監控體系,才能確保關鍵異常第一時間被發現。