首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Zend 認證考試:PHP 電子郵件處理題庫解析

     編輯:PHP 相關知識

考試範疇與核心知識點

Zend PHP 認證考試中,電子郵件處理主要涵蓋:

  • PHP mail() 函式進階用法與限制
  • MIME 標準、多部分郵件結構 (multipart/alternative, multipart/mixed)
  • 郵件標頭注入防範與安全性
  • SMTP 協議基礎與 PHPMailer/SwiftMailer 等函式庫應用
  • 編碼處理:Base64、Quoted-Printable、UTF-8 主旨與內文
  • 附件處理、內嵌圖片、HTML 郵件範本
  • 退信處理、郵件佇列、非同步發送架構

經典考題解析

題目 1:mail() 函式的額外標頭參數正確用法

<?php
// 錯誤:直接串接使用者輸入,標頭注入風險
$headers = "From: $_POST[email]\r\n";
mail($to, $subject, $body, $headers);

// 正確:驗證並清理輸入
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if ($email) {
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    mail($to, $subject, $body, $headers);
}
?>

解析:mail() 第 4 參數直接插入標頭,未過濾換行符會導致標頭注入攻擊。必須驗證 Email 格式,移除 \r\n。

題目 2:發送 HTML 郵件並附加純文字替代內容

<?php
$boundary = md5(time());
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n";

$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
$message .= "純文字內容給不支援 HTML 的郵件客戶端\r\n\r\n";
$message .= "--$boundary\r\n";
$message .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
$message .= "<html><body><h1>HTML 內容</h1></body></html>\r\n\r\n";
$message .= "--$boundary--";

mail($to, '=?UTF-8?B?' . base64_encode('主旨') . '?=', $message, $headers);
?>

解析:multipart/alternative 讓客戶端自動選擇最佳顯示格式。主旨需 RFC 2047 編碼 (Base64 或 Quoted-Printable)。

題目 3:為什麼生產環境建議使用 PHPMailer 而非 mail()?

答案要點:

  1. mail() 依賴本地 MTA (sendmail/postfix),配置複雜、可靠性低
  2. 無內建 SMTP 認證、SSL/TLS、佇列、重試機制
  3. MIME 組裝手動易錯,PHPMailer 封裝完整、支援 DKIM/SPF
  4. 大量發送需佇列化,mail() 同步阻塞嚴重影響效能

實務最佳實踐

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'user@example.com';
    $mail->Password = 'secret';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;
    
    $mail->setFrom('noreply@example.com', '系統通知');
    $mail->addAddress('user@domain.com');
    $mail->Subject = 'UTF-8 主旨測試';
    $mail->Body = '<h1>HTML 內容</h1>';
    $mail->AltBody = '純文字替代內容';
    $mail->CharSet = 'UTF-8';
    
    $mail->send();
} catch (Exception $e) {
    error_log("郵件發送失敗: {$mail->ErrorInfo}");
}
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved