萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 配置 error_log 郵件發送錯誤通知:Windows 環境完整設定

嚴重錯誤發生時即時郵件通知管理員,配合 error_log() 第 2 參數設為 1(郵件模式)實現。本文說明 Windows 下 sendmail 配置與程式碼範例。

php.ini 郵件相關設定

[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 完整簽名

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; // 繼續標準處理
});

常見問題排查

  • 郵件未送達:檢查 SMTP 伺服器設定、防火牆 25/587/465 埠、sendmail 路徑正確性
  • 垃圾郵件箱:設定 SPF/DKIM/DMARC、使用可信 SMTP 服務(SendGrid、Mailgun、Amazon SES)
  • 編碼問題:郵件標頭加入 Content-Type: text/plain; charset=utf-8
  • 頻率限制:避免錯誤風暴狂發郵件,加入節流機制(如每分鐘最多 1 封)

生產環境建議

  • 改用專用郵件庫(PHPMailer、Symfony Mailer)支援 SMTP 驗證、SSL/TLS、HTML 郵件
  • 整合監控系統(Sentry、Datadog、Prometheus Alertmanager)替代單純郵件通知
  • 錯誤分級:僅 E_USER_ERROR、E_ERROR 等級發郵件,WARNING/NOTICE 寫入檔案/系統日誌

郵件通知是最後一道防線,配合完善的日誌與監控體系,才能確保關鍵異常第一時間被發現。

copyright © 萬盛學電腦網 all rights reserved