為強化帳號安全性,系統需偵測異地登入。當用戶從未記錄的 IP 位址登入時,要求透過電子郵件發送一次性驗證碼,驗證通過後記錄該 IP,後續同 IP 登入即可免驗證。本文記錄核心實作邏輯與 PHPMailer 整合步驟。
login_logs 表,比對當前 IP 是否存在有效記錄email_verifications 表(含過期時間 10 分鐘)login_logs(IP、User-Agent、時間)→ 簽發 Session/JWT建議使用 Composer 管理依賴:
composer require phpmailer/phpmailer
或手動下載 PHPMailer 解壓至專案目錄(如 vendor/phpmailer/)。
<?php
require_once __DIR__ . '/vendor/autoload.php'; // Composer 自動載入
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailService {
private $mailer;
public function __construct(array $config) {
$this->mailer = new PHPMailer(true);
$this->setup($config);
}
private function setup(array $config) {
$m = $this->mailer;
$m->isSMTP();
$m->Host = $config['host'];
$m->SMTPAuth = true;
$m->Username = $config['username'];
$m->Password = $config['password'];
$m->SMTPSecure = $config['encryption'] ?? 'tls'; // ssl/tls
$m->Port = $config['port'] ?? 587;
$m->CharSet = 'UTF-8';
$m->setFrom($config['from_email'], $config['from_name']);
}
/**
* 發送驗證碼郵件
* @param string $toEmail 收件者信箱
* @param string $code 驗證碼
* @return bool
*/
public function sendVerificationCode(string $toEmail, string $code): bool {
try {
$m = $this->mailer;
$m->clearAddresses();
$m->addAddress($toEmail);
$m->isHTML(true);
$m->Subject = '您的登入驗證碼';
$m->Body = $this->buildHtmlTemplate($code);
$m->AltBody = "您的驗證碼是:{$code},10 分鐘內有效。請勿洩露給他人。";
$m->send();
return true;
} catch (Exception $e) {
error_log("Mailer Error: " . $m->ErrorInfo);
return false;
}
}
private function buildHtmlTemplate(string $code): string {
return <<<HTML
<div style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
<h2 style="color: #2c3e50;">登入身分驗證</h2>
<p>偵測到新裝置登入,請使用下方驗證碼完成身分確認:</p>
<div style="background: #f8f9fa; border: 1px solid #dee2e6; padding: 20px; text-align: center; margin: 20px 0;">
<span style="font-size: 32px; font-weight: bold; letter-spacing: 4px; color: #e74c3c;">{$code}</span>
</div>
<p style="font-size: 14px; color: #6c757d;">此驗證碼 10 分鐘內有效,請勿轉發給他人。若非本人操作,請忽略此郵件。</p>
</div>
HTML;
}
}
<?php
session_start();
require_once 'MailService.php';
// 設定檔建議放在 config/mail.php 並排除版控
$mailConfig = [
'host' => 'smtp.gmail.com',
'username' => 'your_account@gmail.com',
'password' => 'app_specific_password', // Gmail 需使用應用程式密碼
'encryption' => 'tls',
'port' => 587,
'from_email' => 'noreply@yourdomain.com',
'from_name' => '系統通知',
];
$mailer = new MailService($mailConfig);
// 簡易示範流程
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$code = $_POST['verify_code'] ?? '';
// 1. 驗證帳密 (此處略過,假設通過)
$user = ['id' => 1, 'email' => 'user@example.com'];
// 2. 判斷是否需要驗證碼
$clientIp = $_SERVER['REMOTE_ADDR'];
$trustedIp = checkTrustedIp($user['id'], $clientIp); // 自行實作查詢 login_logs
if (!$trustedIp) {
if (empty($code)) {
// 首次嘗試:發送驗證碼
$verifyCode = random_int(100000, 999999);
saveVerificationCode($user['id'], $verifyCode, $clientIp); // 寫入 DB 含過期時間
$mailer->sendVerificationCode($user['email'], (string)$verifyCode);
echo json_encode(['need_verify' => true, 'msg' => '驗證碼已發送至信箱']);
exit;
} else {
// 二次提交:校驗碼
if (!verifyCode($user['id'], $code, $clientIp)) {
echo json_encode(['success' => false, 'msg' => '驗證碼錯誤或已過期']);
exit;
}
}
}
// 3. 登入成功,記錄 IP、簽發 Token
recordLoginIp($user['id'], $clientIp);
$_SESSION['user_id'] = $user['id'];
echo json_encode(['success' => true, 'redirect' => '/dashboard']);
}
// 輔助函數需自行實作資料庫操作
function checkTrustedIp(int $uid, string $ip): bool { /* ... */ }
function saveVerificationCode(int $uid, int $code, string $ip): void { /* ... */ }
function verifyCode(int $uid, string $code, string $ip): bool { /* ... */ }
function recordLoginIp(int $uid, string $ip): void { /* ... */ }
?>
hash('sha256', $code . $secret) 而非明文。透過上述架構,可快速建立一套安全且用戶體驗良好的異地登入驗證機制。