header() 必須在任何輸出之前調用(含空白、BOM、echo、HTML)。
原理:HTTP 回應 = 狀態行 + 回應頭 + 空行 + 回應體。header() 寫入回應頭,一旦輸出回應體,頭部鎖定無法修改。
解決方案:ob_start() 開啟輸出緩衝,或確保 <?php 為檔案第一字元、無結尾 ?>。
| 代碼 | 含義 | 典型用途 | 範例 |
|---|---|---|---|
| 200 | OK | 正常回應 | header('HTTP/1.1 200 OK'); |
| 301 | Moved Permanently | 永久重定向(SEO 權重傳遞) | header('HTTP/1.1 301 Moved Permanently'); header('Location: /new-url'); |
| 302 | Found | 臨時重定向 | header('Location: /temp-url'); (預設 302) |
| 304 | Not Modified | 快取驗證 | header('HTTP/1.1 304 Not Modified'); |
| 401 | Unauthorized | 需認證(觸發瀏覽器登入框) | header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="Login"'); |
| 403 | Forbidden | 禁止存取 | header('HTTP/1.1 403 Forbidden'); |
| 404 | Not Found | 資源不存在 | header('HTTP/1.1 404 Not Found'); |
| 500 | Internal Server Error | 伺服器錯誤 | header('HTTP/1.1 500 Internal Server Error'); |
| 503 | Service Unavailable | 維護中 | header('HTTP/1.1 503 Service Unavailable'); header('Retry-After: 3600'); |
<?php
// 1. 簡單重定向(302)
header('Location: https://example.com/new-page');
exit;
// 2. 永久重定向(301,SEO 必須)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://example.com/new-page');
exit;
// 3. 延遲重定向(3 秒後跳轉)
header('Refresh: 3; url=https://example.com/');
echo '3 秒後跳轉...';
// 4. 保留查詢字串重定向
$qs = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
header("Location: /new-path{$qs}", true, 301);
exit;
?>
<?php
$file = '/path/to/report.xlsx';
$filename = '月報表_2024.xlsx';
if (!is_file($file)) {
header('HTTP/1.1 404 Not Found');
exit('File not found');
}
// 1. 通用二進制流
header('Content-Type: application/octet-stream');
// 2. 強制下載而非開啟
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
// 3. 檔案大小(支援斷點續傳)
header('Content-Length: ' . filesize($file));
// 4. 快取控制
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Pragma: public'); // HTTP/1.0 相容
// 5. 輸出檔案(大檔案用 readfile 避免記憶體爆炸)
readfile($file);
exit;
?>
| 副檔名 | Content-Type |
|---|---|
| application/pdf | |
| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| .zip | application/zip |
| .jpg/.jpeg | image/jpeg |
| .png | image/png |
| .csv | text/csv |
| .json | application/json |
<?php
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Pragma: no-cache'); // HTTP/1.0 相容
?>
<?php
// 快取 1 小時
header('Cache-Control: public, max-age=3600');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
// 條件請求支援(ETag/Last-Modified)
$etag = md5_file($file);
header('ETag: "' . $etag . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT');
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === '"' . $etag . '"') {
header('HTTP/1.1 304 Not Modified');
exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
header('HTTP/1.1 304 Not Modified');
exit;
}
?>
<?php
// HTML 頁面
header('Content-Type: text/html; charset=UTF-8');
// JSON API
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);
// XML
header('Content-Type: application/xml; charset=UTF-8');
// 純文本
header('Content-Type: text/plain; charset=UTF-8');
// 圖片輸出
header('Content-Type: image/jpeg');
imagejpeg($im);
// 多媒體
header('Content-Type: audio/mpeg'); // MP3
header('Content-Type: video/mp4'); // MP4
header('Content-Type: application/x-shockwave-flash'); // SWF
?>
<?php
// 隱藏 PHP 版本
header('X-Powered-By: Custom/1.0');
// 安全頭(現代標準)
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Content-Security-Policy: default-src \'self\'; script-src \'self\' \'unsafe-inline\'; style-src \'self\' \'unsafe-inline\'');
// CORS
header('Access-Control-Allow-Origin: https://app.example.com');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
?>
ob_start() 緩衝輸出headers_sent($file, $line) 定位輸出位置exit 終止腳本Location 頭(後者覆蓋前者)rawurlencode() 編碼檔名filename*=UTF-8''%E6%96%87%E4%BB%B6.pdfheader() 是 PHP 操作 HTTP 協定的核心介面。掌握:狀態碼語義、重定向類型、下載頭部組合、快取控制策略、Content-Type 對照、安全頭部配置。鐵律:零輸出前調用、重定向後 exit、中文檔名編碼、大檔案用 readfile。現代框架(Laravel/Symfony)封裝為 Response 物件,原理相同,建議直接使用框架抽象層。