header() 必須在**任何輸出前**呼叫。本文整理最實用的標頭定義分類速查,可直接複製套用。
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/'); // 延遲跳轉
| 類型 | 標頭 |
|---|---|
| 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'); |
| 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/GIF | header('Content-Type: image/png'); / 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="file.zip"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.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');
$time = time() - 60;
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="Admin Area"');
echo '認證失敗顯示此訊息';
header('X-Powered-By: Custom/1.0'); // 隱藏 PHP 版本
header('X-Frame-Options: DENY'); // 防 iframe 嵌入
header('X-Content-Type-Options: nosniff'); // 禁用 MIME 嗅探
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Content-Security-Policy: default-src \'self\';'); // CSP 基礎
ob_start() 可緩衝解決順序問題exit;Content-Lengthurlencode() 或 RFC 5987 編碼收藏此表,API、下載、快取、安全標頭一查即得。