header() 是 PHP 控制 HTTP 回應標頭的核心函數,掌握它能實現重導向、檔案下載、快取控制、內容協商、安全防護等關鍵功能。本文系統整理常用標頭、正確使用姿勢、常見陷阱與安全最佳實踐。
echo/print、var_dump、錯誤訊息。建議啟用 output_buffering 或使用輸出緩衝 ob_start()。Content-Type 格式。Location: /path 在某些舊客戶端/代理可能失效,建議使用絕對 URL。false 參數可堆疊 (如多個 Set-Cookie):header('Set-Cookie: a=1', false); header('Set-Cookie: b=2', false);。<?php
// 成功
header('HTTP/1.1 200 OK'); // 預設,通常省略
header('HTTP/1.1 201 Created'); // 資源建立 (POST 回應)
header('HTTP/1.1 204 No Content'); // 成功但無內容回傳
// 重導向
header('HTTP/1.1 301 Moved Permanently'); // 永久移動 (SEO 傳遞權重)
header('Location: https://new.example.com/');
exit; // 重導向後務必 exit!
header('HTTP/1.1 302 Found'); // 暫時重導向 (預設)
header('Location: /login.php');
exit;
header('HTTP/1.1 304 Not Modified'); // 條件請求未修改 (配合 ETag/Last-Modified)
// 客戶端錯誤
header('HTTP/1.1 400 Bad Request'); // 請求格式錯誤
header('HTTP/1.1 401 Unauthorized'); // 未認證 (需 WWW-Authenticate)
header('HTTP/1.1 403 Forbidden'); // 已認證但無權限
header('HTTP/1.1 404 Not Found'); // 資源不存在
header('HTTP/1.1 422 Unprocessable Entity'); // 語義錯誤 (驗證失敗)
header('HTTP/1.1 429 Too Many Requests'); // 限流
// 伺服器錯誤
header('HTTP/1.1 500 Internal Server Error');
header('HTTP/1.1 503 Service Unavailable'); // 維護中
header('Retry-After: 3600'); // 建議重試秒數
<?php
// 標準內容類型
header('Content-Type: text/html; charset=utf-8'); // HTML
header('Content-Type: application/json; charset=utf-8'); // JSON API (標準)
header('Content-Type: application/xml; charset=utf-8'); // XML
header('Content-Type: text/plain; charset=utf-8'); // 純文字
header('Content-Type: text/css; charset=utf-8'); // CSS
header('Content-Type: application/javascript; charset=utf-8'); // JS
header('Content-Type: image/jpeg'); // JPEG
header('Content-Type: image/png'); // PNG
header('Content-Type: image/webp'); // WebP
header('Content-Type: image/svg+xml'); // SVG
header('Content-Type: application/pdf'); // PDF
header('Content-Type: application/zip'); // ZIP
header('Content-Type: application/octet-stream'); // 通用二進位下載
header('Content-Type: audio/mpeg'); // MP3
header('Content-Type: video/mp4'); // MP4
header('Content-Type: font/woff2'); // WOFF2 字體
// 字元編碼宣告 (HTML5 建議用 ,但 HTTP 標頭優先級更高)
header('Content-Type: text/html; charset=utf-8');
<?php
function downloadFile(string $filePath, string $downloadName = '', string $mime = ''): void {
if (!is_file($filePath) || !is_readable($filePath)) {
http_response_code(404);
exit('檔案不存在');
}
$downloadName = $downloadName ?: basename($filePath);
$mime = $mime ?: mime_content_type($filePath) ?: 'application/octet-stream';
$size = filesize($filePath);
// 清除輸出緩衝 (防止記憶體溢位)
if (ob_get_level()) ob_end_clean();
// 核心下載標頭
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $size);
header('Accept-Ranges: bytes'); // 支援斷點續傳
// 快取控制 (視需求)
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: no-cache'); // HTTP/1.0 相容
header('Expires: 0');
// 輸出檔案 (分塊讀取,避免大檔案記憶體爆炸)
$fp = fopen($filePath, 'rb');
while (!feof($fp)) {
echo fread($fp, 8192);
flush(); // 立即發送給客戶端
}
fclose($fp);
exit;
}
// 使用
downloadFile('/var/www/files/report.pdf', '2024_Q1_Report.pdf');
| 場景 | 標頭組合 |
|---|---|
| 完全禁止快取 (動態頁面、API、敏感資料) |
Cache-Control: no-store, no-cache, must-revalidate, max-age=0Pragma: no-cache (HTTP/1.0)Expires: 0
|
| 允許快取但每次驗證 (動態內容、需即時性) |
Cache-Control: no-cache, must-revalidateETag: "abc123" / Last-Modified: ...
|
| 公開快取 (靜態資源、CDN) |
Cache-Control: public, max-age=31536000, immutable (1 年,檔名含雜湊)Cache-Control: public, max-age=3600 (1 小時,一般靜態檔)
|
| 私有快取 (個人化內容、登入後頁面) |
Cache-Control: private, max-age=600 (10 分鐘,僅瀏覽器快取)
|
<?php
function sendWithCacheValidation(string $filePath, string $etag = ''): void {
$lastModified = filemtime($filePath);
$etag = $etag ?: md5_file($filePath);
$ifModifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? '';
$ifNoneMatch = $_SERVER['HTTP_IF_NONE_MATCH'] ?? '';
$modifiedSince = $ifModifiedSince ? strtotime($ifModifiedSince) : 0;
if (($ifNoneMatch && $ifNoneMatch === $etag) || ($modifiedSince && $lastModified <= $modifiedSince)) {
header('HTTP/1.1 304 Not Modified');
header('ETag: ' . $etag);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
exit;
}
header('ETag: ' . $etag);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
header('Cache-Control: public, max-age=3600, must-revalidate');
// 輸出檔案...
}
<?php
// 1. 防點擊劫持
header('X-Frame-Options: DENY'); // 或 SAMEORIGIN
// 2. 防 MIME 偵測
header('X-Content-Type-Options: nosniff');
// 3. XSS 保護 (舊瀏覽器)
header('X-XSS-Protection: 1; mode=block');
// 4. 內容安全政策 (CSP) - 核心防 XSS
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
// 5. HSTS (僅 HTTPS)
header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
// 6. Referrer Policy
header('Referrer-Policy: strict-origin-when-cross-origin');
// 7. Permissions Policy (Feature Policy)
header("Permissions-Policy: geolocation=(), microphone=(), camera=()");
// 8. 移除資訊洩漏標頭
header_remove('X-Powered-By');
header_remove('Server');
// Nginx/Apache 需在伺服器層設定 server_tokens off; / ServerTokens Prod;
<?php
// 延遲重導向 (HTML meta refresh 替代)
header('Refresh: 5; url=https://example.com/');
echo '5 秒後自動跳轉...';
// 語言協商
header('Content-Language: zh-TW');
header('Vary: Accept-Language'); // 告訴快取依 Accept-Language 區分
// CORS 跨域資源共享
header('Access-Control-Allow-Origin: https://app.example.com'); // 不要用 * 配合 credentials
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // 預檢快取 1 天
// 處理 OPTIONS 預檢請求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// Cookie 設定 (安全)
header('Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600');
前空白、include 檔案輸出、錯誤訊息輸出。解決:ob_start() 開啟輸出緩衝、修正編碼、調整程式碼順序。header('Location: ...') 後有 exit;;URL 使用絕對路徑;未輸出任何內容前送標頭。rawurlencode() 編碼檔名,或 RFC 5987 格式:filename*=UTF-8''%E6%AA%94%E6%A1%88.pdf。script-src, style-src 等指令,開發階段可用 Content-Security-Policy-Report-Only 僅回報不阻擋。<?php
// 開發環境:列出即將發送的標頭
function debugHeaders(): void {
$headers = headers_list();
echo ""; print_r($headers); echo "
";
}
// 或瀏覽器 DevTools → Network → Headers
// 或 curl -I https://example.com/
header() 是 HTTP 協定的直接介面,掌握它就是掌握了瀏覽器與伺服器溝通的主導權。從基本的重導向、下載,到進階的快取策略、安全標頭、CORS 設定,每個 Web 開發者都應熟練運用。建議將常用標頭組合封裝為 Response 類別或中介軟體,統一管理、減少錯誤!