void header(string $string [, bool $replace = true [, int $http_response_code ]])
向客戶端發送原始 HTTP Header。絕對要在任何實際輸出(HTML、空白行、echo 等)之前呼叫,否則會觸發 "Headers already sent" 警告。
$string:Header 字串(必填)$replace:是否替換同類型 Header,預設 true;false 允許同類型多值$http_response_code:強制指定 HTTP 狀態碼(PHP 4.3+)header('HTTP/1.1 200 OK');
header('HTTP/1.1 301 Moved Permanently');
header('HTTP/1.1 302 Found');
header('HTTP/1.1 304 Not Modified');
header('HTTP/1.1 401 Unauthorized');
header('HTTP/1.1 403 Forbidden');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 500 Internal Server Error');
常用狀態碼分類:
// 立即跳轉
header('Location: https://example.com/');
exit; // 建議配合 exit 防止後續代碼執行
// 延遲跳轉(3 秒)
header('Refresh: 3; url=https://example.com/');
echo '3 秒後自動跳轉...';
// 強制不快取(適用動態頁面、API)
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// 允許快取 5 秒(適用半靜態資源)
header('Cache-Control: max-age=5, public');
Cache-Control 指令速查:
| 指令 | 說明 |
|---|---|
| public | 所有內容可被快取(含 Proxy) |
| private | 僅客戶端私有快取 |
| no-cache | 每次請求必須向伺服器驗證 |
| no-store | 不快取任何內容(含暫存檔) |
| must-revalidate | 過期後必須回源驗證 |
| max-age=秒數 | 快取有效期(優先於 Expires) |
// 範例:下載 PDF
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
header('Content-Length: ' . filesize('report.pdf'));
readfile('report.pdf'); // 直接輸出檔案內容
exit;
通用二進位下載 Header:
header('Content-Type: application/octet-stream');
header('Accept-Ranges: bytes');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
readfile($file);
$lastModified = filemtime($file);
$etag = md5_file($file);
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lastModified).' GMT');
header('ETag: "'.$etag.'"');
$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false;
$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH']) : false;
if (($ifModifiedSince && $ifModifiedSince >= $lastModified) || ($ifNoneMatch && $ifNoneMatch === $etag)) {
header('HTTP/1.1 304 Not Modified');
exit;
}
// 正常輸出內容...
header() 呼叫前不可有任何輸出(含 BOM、空白行)。exit; 避免後續邏輯執行。Content-Length 並分塊輸出,避免記憶體耗盡。Cache-Control: no-store 防止敏感資料被 Proxy 快取。