header() 是 PHP 中發送原始 HTTP 標頭的核心函數,必須在任何實際輸出之前呼叫。本文整理開發中最常用的標頭設定,涵蓋內容型別、狀態碼、重導向、快取控制、檔案下載、認證等場景,方便快速查閱。
// 通用
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain');
header('Content-Type: application/json');
header('Content-Type: application/xml');
header('Content-Type: application/pdf');
// 靜態資源
header('Content-Type: text/css');
header('Content-Type: text/javascript');
header('Content-Type: image/jpeg');
header('Content-Type: image/png');
header('Content-Type: application/zip');
header('Content-Type: audio/mpeg');
header('Content-Type: application/x-shockwave-flash');
// RSS / Atom
header('Content-Type: application/rss+xml; charset=ISO-8859-1');
header('Content-Type: application/atom+xml');
// 成功
header('HTTP/1.1 200 OK');
// 錯誤
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 401 Unauthorized');
header('HTTP/1.1 403 Forbidden');
// 永久/暫時重導向
header('HTTP/1.1 301 Moved Permanently');
header('HTTP/1.1 302 Found');
header('Location: https://example.com/new-page');
// 延遲重導向(10 秒後跳轉)
header('Refresh: 10; url=https://example.com/');
echo '您將在 10 秒後被重導向...';
// 禁用快取(適用動態頁面、API)
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');
// 啟用快取(靜態資源)
header('Cache-Control: public, max-age=31536000'); // 1 年
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
$file = 'example.zip';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
readfile($file);
// 最後修改時間(配合 304 Not Modified)
$time = time() - 60; // 或 filemtime($filename)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
// 內容語言
header('Content-Language: zh-TW');
// 隱藏 PHP 版本資訊
header('X-Powered-By: Custom-Framework/1.0');
// HTTP 基本認證
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Restricted Area"');
echo '需要登入才能存取';
header() 必須在任何 echo、print、HTML 空白字元之前呼叫headers_sent() 可檢查標頭是否已發送exit() 避免後續程式碼執行rawurlencode() 處理