萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP header() 函式完整指南:重導向、快取控制、檔案下載、狀態碼

基本規則

header() 必須在任何輸出之前呼叫 (包括空白、BOM、echo、HTML)。否則觸發 Cannot modify header information - headers already sent 警告並失效。

三大標準 Header 類別 (HTTP/1.0 必含其一)

Header用途範例
Content-Type回應內容 MIME 類型header('Content-Type: application/json');
Location重導向header('Location: https://example.com');
StatusHTTP 狀態碼header('Status: 404 Not Found');

新版多重 MIME (Multipart) 可出現多次 Content-Type。

實戰範例集

1. 重導向 (302 Found)

header("Location: https://www.php.net");
exit;  // 重要:停止後續執行

2. 防快取:取得最新資料

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");  // 過去時間
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");  // HTTP/1.0 相容

3. 手動回傳 404

header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");
// 可選:輸出自訂 404 頁面內容
include '404.html';
exit;

4. 檔案下載 (強制另存新檔)

$file = '/path/to/file.pdf';
$filename = 'download.pdf';

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file);  // 高效輸出檔案內容
exit;

5. JSON API 回應

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status'=>'ok', 'data'=>$data]);
exit;

6. 圖片直接輸出

header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($imgPath));
readfile($imgPath);

進階技巧

HTTP/1.1 相對路徑重導向

RFC 7231 允許相對路徑,但建議用絕對 URL 避免相容性問題。

301 永久 vs 302 暫時

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://new.example.com/");
// SEO 權重傳遞、瀏覽器/搜尋引擎更新書籤/索引

header("HTTP/1.1 302 Found");  // 預設
header("Location: /temp-page");

Content-Disposition 細節

// 內嵌顯示 (瀏覽器嘗試直接開啟)
header('Content-Disposition: inline; filename="report.pdf"');

// 附件下載 (強制另存)
header('Content-Disposition: attachment; filename="report.pdf"');

// RFC 5987 編碼中文檔名
$encoded = rawurlencode($filename);
header("Content-Disposition: attachment; filename*=UTF-8''{$encoded}");

避免 headers already sent 的常見原因

  1. 檔案開頭有 BOM (UTF-8 with BOM) → 存檔為 UTF-8 without BOM
  2. 前有空白/換行
  3. include/require 的檔案尾部有關閉標籤 ?> 後的空白 → 純 PHP 檔案省略結束標籤
  4. 錯誤/警告輸出 → 設定 display_errors=Off 或 error_reporting(0)
  5. Session 自動啟動輸出 Cookie → session.cache_limiter = '' 或手動 session_start() 在最頂端

headers_sent() 檢測

if (headers_sent($file, $line)) {
    error_log("Headers already sent in $file:$line");
} else {
    header("Location: /login");
}

相關函數

  • headers_list():已發送/待發送 Header 列表
  • header_remove():移除已設定但未發送的 Header
  • http_response_code():設定/取得狀態碼 (PHP 5.4+)
copyright © 萬盛學電腦網 all rights reserved