許多開發者誤以為 header('Location: ...'); 會立即終止腳本執行。實際上,PHP 會繼續執行後續代碼,直到自然結束或遇到 exit/die。這可能導致非預期的副作用(如重複寫入日誌、發送郵件、資料庫異動)。
<?php
header('Location: https://example.com');
// exit; // 若註解掉這行
// 這行仍會執行!
file_put_contents(__DIR__ . '/log.txt', '重導向後仍執行了', FILE_APPEND);
?>
瀏覽器會跳轉,但 log.txt 確實會被寫入。
| 情境 | 建議 | 理由 |
|---|---|---|
| 重導向 (301/302/303/307) | 必須 加 exit; | 防止後續邏輯執行造成資料不一致、安全洩漏、效能浪費 |
| 輸出 JSON/API 回應 | 建議加 | 確保無額外輸出干擾 JSON 解析 |
| 404/403/500 狀態碼 | 視情況 | 若後續還有輸出錯誤頁面模板,可不加;若僅設定狀態碼則加上 |
| 檔案下載 | 建議加 | 避免 HTML/空白字元混入二進位檔案 |
<?php
// 301 永久重導 (SEO 友善)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://new-domain.com/path');
exit;
// 302 暫時重導 (預設)
header('Location: /login.php');
exit;
// 404 找不到
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found'); // 兼容 FastCGI
// 可選:輸出自訂 404 頁面
include '404.html';
exit;
// 304 未修改 (快取驗證)
header('HTTP/1.1 304 Not Modified');
exit;
// 觸發瀏覽器基本認證對話框
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Admin Panel"');
echo '認證失敗';
exit;
?>
<?php
function redirect(string $url, int $status = 302): never {
// 防止標頭注入
$url = str_replace(["\n", "\r"], '', $url);
// 依狀態碼發送對應標頭
if ($status === 301) {
header('HTTP/1.1 301 Moved Permanently');
} elseif ($status === 302) {
header('HTTP/1.1 302 Found');
} elseif ($status === 303) {
header('HTTP/1.1 303 See Other');
}
header("Location: {$url}");
exit; // 關鍵:立即終止
}
// 使用
redirect('/dashboard');
redirect('https://api.example.com/v2', 301);
?>
結論: 除非你確定且有意讓重導向後的代碼繼續執行(極少見),永遠在 header Location 後加上 exit;。這是防禦性程式設計的基本功。