header() 是 PHP 向瀏覽器發送原始 HTTP 回應標頭的唯一介面。它必須在任何實際輸出(HTML、空白、echo、BOM)之前呼叫,否則觸發「Headers already sent」錯誤。本文系統整理語法、常用標頭、重導向模式、快取控制、檔案下載、安全標頭與輸出緩衝最佳實踐。
header(string $header, bool $replace = true, int $response_code = 0): void
$header:標頭字串,格式 Header-Name: value。$replace:true(預設)替換同名標頭;false 允許多值(如多個 Set-Cookie)。$response_code:強制設定 HTTP 狀態碼(PHP 4.3+)。<?php
// ❌ 錯誤:HTML 輸出在 header 之前
?>
<html>
<?php header('Location: /login.php'); ?>
// ✅ 正確:header 在最頂端
<?php
header('Location: /login.php');
exit; // 重要:重導向後終止腳本
?>
<html>...
<?php
// 檔案最開頭啟用輸出緩衝
ob_start();
// 現在可以在任何位置輸出 HTML、echo
echo "Some early output\n";
// 稍後決定重導向
if ($needRedirect) {
header('Location: /target.php');
ob_end_flush(); // 發送緩衝內容(重導向通常不需要輸出內容)
exit;
}
// 正常頁面結尾
ob_end_flush();
?>
<?php
// 302 Found(預設暫時重導向)
header('Location: https://example.com/new-page');
header('HTTP/1.1 302 Found'); // 明確狀態碼
// 301 Moved Permanently(SEO 傳遞權重)
header('Location: https://example.com/new-page', true, 301);
// 303 See Other(POST 後重導向 GET,防重複提交)
header('Location: /success.php', true, 303);
// 404 Not Found
header('HTTP/1.1 404 Not Found');
include '404.php';
exit;
// 500 Internal Server Error
header('HTTP/1.1 500 Internal Server Error');
exit;
?>
<?php
// 完全禁用快取(動態內容、API、敏感頁面)
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false); // HTTP/1.0 相容
header('Pragma: no-cache'); // HTTP/1.0
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
// 靜態資源長期快取(配合版本號/雜湊檔名)
// header('Cache-Control: public, max-age=31536000, immutable');
// 必須重新驗證(ETag/Last-Modified)
header('Cache-Control: no-cache, must-revalidate');
header('ETag: "' . md5($content) . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
?>
<?php
$filePath = '/var/www/files/report.pdf';
$fileName = 'monthly-report-' . date('Y-m') . '.pdf';
if (!is_file($filePath)) {
http_response_code(404);
exit('File not found');
}
$size = filesize($filePath);
$mime = mime_content_type($filePath) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . $size);
header('Accept-Ranges: bytes'); // 支援斷點續傳
// 大檔案分塊輸出,避免記憶體爆炸
$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
echo fread($handle, 8192);
flush(); // 發送至瀏覽器
}
fclose($handle);
exit;
?>
<?php
// 防點擊劫持
header('X-Frame-Options: DENY'); // 或 SAMEORIGIN
// 防 MIME 嗅探
header('X-Content-Type-Options: nosniff');
// XSS 保護(舊瀏覽器)
header('X-XSS-Protection: 1; mode=block');
// 內容安全策略(CSP)核心防禦
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none';");
// 強制 HTTPS(HSTS,需配合 HTTPS 部署)
// header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
// Referrer 政策
header('Referrer-Policy: strict-origin-when-cross-origin');
// 權限政策
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
?>
<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
if (in_array($origin, $allowedOrigins, true)) {
header("Access-Control-Allow-Origin: $origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400');
}
// 預檢請求快速回應
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
?>
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Cannot modify header information - headers already sent | header() 前有輸出(echo、HTML、空白、BOM、錯誤訊息) | 1. 檢查檔案開頭無 BOM/空白 2. 使用 ob_start() 3. 重構程式碼:先邏輯後輸出 |
| 重導向不生效 | 未呼叫 exit、狀態碼錯誤、Location 值非絕對 URL | 加上 exit、使用完整 URL、檢查 301/302/303 選擇 |
| 中文檔名下載亂碼 | RFC 5987 編碼缺失 | filename*=UTF-8'' . rawurlencode($filename) |
| 多次 header 覆蓋 | 預設 replace=true | 多值標頭用 header('Set-Cookie: ...', false) |
<?php
$filename = '報表_2024.pdf';
$encoded = rawurlencode($filename);
header("Content-Disposition: attachment; filename=\"$encoded\"; filename*=UTF-8''$encoded");
?>
<?php
ob_start(); // Level 1
echo "A";
ob_start(); // Level 2
echo "B";
$inner = ob_get_clean(); // 取得 "B",關閉 Level 2
echo "C";
$outer = ob_get_clean(); // 取得 "AC",關閉 Level 1
echo $outer . $inner; // ACB
?>
<?php
ob_start(function($buffer) {
// 壓縮、替換、記錄
return str_replace('[APP]', 'MyApp', $buffer);
});
echo "[APP] started";
ob_end_flush(); // 輸出: MyApp started
?>
ob_start(),框架通常自動處理。exit,防止後續程式碼執行。http_response_code() 設定狀態碼(PHP 5.4+),語意更清晰。\r, \n),防 HTTP 標頭注入。curl -I、瀏覽器 DevTools Network、securityheaders.com 掃描。header() 是 PHP 與 HTTP 協定溝通的橋樑。掌握「輸出前呼叫」、「標頭語意正確性」、「安全標頭部署」、「檔案下載分塊輸出」與「輸出緩衝控制」,能構建符合現代 Web 標準、安全且高效能的 PHP 應用。