header() 是 PHP 傳送原始 HTTP 標頭的核心函式,必須在任何實際輸出(HTML、空白、echo)之前呼叫。本文彙整最常見的實戰場景,附上可直接複製的程式碼片段。
<?php
// 正常回應(預設)
header('HTTP/1.1 200 OK');
// 404 找不到
header('HTTP/1.1 404 Not Found');
// 301 永久移動(SEO 必用,搭配 Location)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://new-domain.com/');
// 304 未修改(配合快取驗證)
header('HTTP/1.1 304 Not Modified');
// 401 需驗證(Basic Auth)
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
echo '認證失敗或取消登入';
?>
<?php
// 立即重導向
header('Location: https://example.com/');
exit; // 最佳實務:重導向後立即結腳本
// 延遲 10 秒跳轉(等同 HTML meta refresh)
header('Refresh: 10; url=https://example.com/');
echo '10 秒後自動跳轉...';
?>
<?php
// 禁止快取(動態頁面、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'); // HTTP/1.0 相容
// 啟用快取(靜態資源)
$time = time() - 60; // 或 filemtime($filename)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('Cache-Control: public, max-age=3600'); // 快取 1 小時
?>
<?php
$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); // 高效輸出檔案內容
exit;
?>
<?php
header('Content-Type: text/html; charset=utf-8'); // HTML
header('Content-Type: application/json; charset=utf-8'); // JSON API
header('Content-Type: image/jpeg'); // 圖片
header('Content-Type: application/pdf'); // PDF
header('Content-Type: audio/mpeg'); // MP3
header('Content-Type: application/x-shockwave-flash'); // SWF
?>
<?php
// 覆蓋 X-Powered-By(隱藏 PHP 版本)
header('X-Powered-By: Custom/1.0');
// 多語言內容
header('Content-Language: zh-TW');
?>
echo、HTML 空白、BOM 都會導致 Cannot modify header information 錯誤。filename*=UTF-8''%E6%AA%94%E6%A1%88.zip,兼容舊版 IE 需額外處理。