header() 必須在**任何實際輸出之前**呼叫(PHP 4+ 可用輸出緩衝解決)。本文彙整最常用的標頭定義,供快速查閱複製。
header('HTTP/1.1 200 OK');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 301 Moved Permanently'); // 永久重導向
header('HTTP/1.1 304 Not Modified'); // 快取驗證
header('Location: https://example.com/'); // 立即跳轉
header('Refresh: 10; url=https://example.com/'); // 10 秒後跳轉
// HTML 替代:
| 檔案類型 | header() 設定 |
|---|---|
| HTML (UTF-8) | header('Content-Type: text/html; charset=utf-8'); |
| 純文字 | header('Content-Type: text/plain'); |
| CSS | header('Content-Type: text/css'); |
| JavaScript | header('Content-Type: text/javascript'); |
| JSON | header('Content-Type: application/json'); |
| XML | header('Content-Type: text/xml'); 或 application/xml |
| RSS | header('Content-Type: application/rss+xml; charset=ISO-8859-1'); |
| Atom | header('Content-Type: application/atom+xml'); |
header('Content-Type: application/pdf'); | |
| ZIP | header('Content-Type: application/zip'); |
| JPEG | header('Content-Type: image/jpeg'); |
| PNG | header('Content-Type: image/png'); |
| GIF | header('Content-Type: image/gif'); |
| 音頻 MP3 | header('Content-Type: audio/mpeg'); |
| Flash | header('Content-Type: application/x-shockwave-flash'); |
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('example.zip'));
readfile('example.zip');
header('Content-Disposition: attachment; filename="report.xlsx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize('report.xlsx'));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('report.xlsx');
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Pragma: no-cache'); // HTTP/1.0 相容
$time = time() - 60; // 或 filemtime($file)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('ETag: "' . md5_file($file) . '"');
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Restricted Area"');
echo '取消或輸入錯誤帳密將顯示此訊息';
header('X-Powered-By: PHP/8.2'); // 隱藏/修改版本資訊
header('Content-Language: zh-TW'); // 文件語言
header('Content-Length: 1234'); // 內容長度
header('X-Frame-Options: DENY'); // 防點擊劫持
header('X-Content-Type-Options: nosniff'); // 禁用 MIME 嗅探
header('Referrer-Policy: strict-origin-when-cross-origin');
header() 必須在 echo、print、HTML 空白、BOM 之前ob_start() 緩衝或調整程式碼順序exit; 避免後續程式碼執行Content-Length 讓瀏覽器顯示進度收藏此速查表,開發 API、檔案下載、快取控制、認證流程時即查即用。