萬盛學電腦網

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

PHP header() 函數完全指南:HTTP 狀態碼、重定向、下載、快取控制、Content-Type 實戰速查表

核心原則

header() 必須在任何輸出之前調用(含空白、BOM、echo、HTML)。
原理:HTTP 回應 = 狀態行 + 回應頭 + 空行 + 回應體。header() 寫入回應頭,一旦輸出回應體,頭部鎖定無法修改。

解決方案:ob_start() 開啟輸出緩衝,或確保 <?php 為檔案第一字元、無結尾 ?>。

HTTP 狀態碼速查表

代碼含義典型用途範例
200OK正常回應header('HTTP/1.1 200 OK');
301Moved Permanently永久重定向(SEO 權重傳遞)header('HTTP/1.1 301 Moved Permanently'); header('Location: /new-url');
302Found臨時重定向header('Location: /temp-url'); (預設 302)
304Not Modified快取驗證header('HTTP/1.1 304 Not Modified');
401Unauthorized需認證(觸發瀏覽器登入框)header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="Login"');
403Forbidden禁止存取header('HTTP/1.1 403 Forbidden');
404Not Found資源不存在header('HTTP/1.1 404 Not Found');
500Internal Server Error伺服器錯誤header('HTTP/1.1 500 Internal Server Error');
503Service Unavailable維護中header('HTTP/1.1 503 Service Unavailable'); header('Retry-After: 3600');

重定向模式

<?php
// 1. 簡單重定向(302)
header('Location: https://example.com/new-page');
exit;

// 2. 永久重定向(301,SEO 必須)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://example.com/new-page');
exit;

// 3. 延遲重定向(3 秒後跳轉)
header('Refresh: 3; url=https://example.com/');
echo '3 秒後跳轉...';

// 4. 保留查詢字串重定向
$qs = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
header("Location: /new-path{$qs}", true, 301);
exit;
?>

檔案下載標準模式

<?php
$file = '/path/to/report.xlsx';
$filename = '月報表_2024.xlsx';

if (!is_file($file)) {
    header('HTTP/1.1 404 Not Found');
    exit('File not found');
}

// 1. 通用二進制流
header('Content-Type: application/octet-stream');
// 2. 強制下載而非開啟
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
// 3. 檔案大小(支援斷點續傳)
header('Content-Length: ' . filesize($file));
// 4. 快取控制
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Pragma: public');  // HTTP/1.0 相容

// 5. 輸出檔案(大檔案用 readfile 避免記憶體爆炸)
readfile($file);
exit;
?>

Content-Type 常見對照

副檔名Content-Type
.pdfapplication/pdf
.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
.zipapplication/zip
.jpg/.jpegimage/jpeg
.pngimage/png
.csvtext/csv
.jsonapplication/json

快取控制策略

禁用快取(動態頁面、敏感資料)

<?php
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Pragma: no-cache'); // HTTP/1.0 相容
?>

啟用快取(靜態資源、API 回應)

<?php
// 快取 1 小時
header('Cache-Control: public, max-age=3600');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');

// 條件請求支援(ETag/Last-Modified)
$etag = md5_file($file);
header('ETag: "' . $etag . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT');

if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === '"' . $etag . '"') {
    header('HTTP/1.1 304 Not Modified');
    exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}
?>

內容類型與編碼

<?php
// HTML 頁面
header('Content-Type: text/html; charset=UTF-8');

// JSON API
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);

// XML
header('Content-Type: application/xml; charset=UTF-8');

// 純文本
header('Content-Type: text/plain; charset=UTF-8');

// 圖片輸出
header('Content-Type: image/jpeg');
imagejpeg($im);

// 多媒體
header('Content-Type: audio/mpeg');  // MP3
header('Content-Type: video/mp4');   // MP4
header('Content-Type: application/x-shockwave-flash'); // SWF
?>

自訂頭部與安全頭

<?php
// 隱藏 PHP 版本
header('X-Powered-By: Custom/1.0');

// 安全頭(現代標準)
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Content-Security-Policy: default-src \'self\'; script-src \'self\' \'unsafe-inline\'; style-src \'self\' \'unsafe-inline\'');

// CORS
header('Access-Control-Allow-Origin: https://app.example.com');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
?>

常見錯誤與除錯

  1. Cannot modify header information - headers already sent
    • 檢查檔案開頭是否有空白/BOM
    • 檢查 include/require 檔案是否有輸出
    • 使用 ob_start() 緩衝輸出
    • 使用 headers_sent($file, $line) 定位輸出位置
  2. Location 重定向不生效
    • 確保 exit 終止腳本
    • URL 必須為絕對路徑(RFC 7231),相對路徑視瀏覽器實作而定
    • 檢查是否有多個 Location 頭(後者覆蓋前者)
  3. 中文檔名下載亂碼
    • 使用 rawurlencode() 編碼檔名
    • 或採用 RFC 5987 格式:filename*=UTF-8''%E6%96%87%E4%BB%B6.pdf

總結

header() 是 PHP 操作 HTTP 協定的核心介面。掌握:狀態碼語義、重定向類型、下載頭部組合、快取控制策略、Content-Type 對照、安全頭部配置。鐵律:零輸出前調用、重定向後 exit、中文檔名編碼、大檔案用 readfile。現代框架(Laravel/Symfony)封裝為 Response 物件,原理相同,建議直接使用框架抽象層。

copyright © 萬盛學電腦網 all rights reserved