萬盛學電腦網

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

PHP header() 函式完整指南:HTTP 標頭控制、重導向、快取策略、檔案下載與安全防護

前言

header() 是 PHP 向瀏覽器發送原始 HTTP 回應標頭的唯一介面。它必須在任何實際輸出(HTML、空白、echo、BOM)之前呼叫,否則觸發「Headers already sent」錯誤。本文系統整理語法、常用標頭、重導向模式、快取控制、檔案下載、安全標頭與輸出緩衝最佳實踐。

一、語法與核心規則

1.1 函式簽名

header(string $header, bool $replace = true, int $response_code = 0): void
  • $header:標頭字串,格式 Header-Name: value。
  • $replace:true(預設)替換同名標頭;false 允許多值(如多個 Set-Cookie)。
  • $response_code:強制設定 HTTP 狀態碼(PHP 4.3+)。

1.2 必須在輸出前呼叫

<?php
// ❌ 錯誤:HTML 輸出在 header 之前
?>
<html>
<?php header('Location: /login.php'); ?>

// ✅ 正確:header 在最頂端
<?php
header('Location: /login.php');
exit; // 重要:重導向後終止腳本
?>
<html>...

1.3 輸出緩衝:解決「過早輸出」

<?php
// 檔案最開頭啟用輸出緩衝
ob_start();

// 現在可以在任何位置輸出 HTML、echo
echo "Some early output\n";

// 稍後決定重導向
if ($needRedirect) {
    header('Location: /target.php');
    ob_end_flush(); // 發送緩衝內容(重導向通常不需要輸出內容)
    exit;
}

// 正常頁面結尾
ob_end_flush();
?>

二、常用標頭分類速查

2.1 重導向與狀態碼

<?php
// 302 Found(預設暫時重導向)
header('Location: https://example.com/new-page');
header('HTTP/1.1 302 Found'); // 明確狀態碼

// 301 Moved Permanently(SEO 傳遞權重)
header('Location: https://example.com/new-page', true, 301);

// 303 See Other(POST 後重導向 GET,防重複提交)
header('Location: /success.php', true, 303);

// 404 Not Found
header('HTTP/1.1 404 Not Found');
include '404.php';
exit;

// 500 Internal Server Error
header('HTTP/1.1 500 Internal Server Error');
exit;
?>

2.2 快取控制

<?php
// 完全禁用快取(動態內容、API、敏感頁面)
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false); // HTTP/1.0 相容
header('Pragma: no-cache'); // HTTP/1.0
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間

// 靜態資源長期快取(配合版本號/雜湊檔名)
// header('Cache-Control: public, max-age=31536000, immutable');

// 必須重新驗證(ETag/Last-Modified)
header('Cache-Control: no-cache, must-revalidate');
header('ETag: "' . md5($content) . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
?>

2.3 檔案下載:Content-Disposition

<?php
$filePath = '/var/www/files/report.pdf';
$fileName = 'monthly-report-' . date('Y-m') . '.pdf';

if (!is_file($filePath)) {
    http_response_code(404);
    exit('File not found');
}

$size = filesize($filePath);
$mime = mime_content_type($filePath) ?: 'application/octet-stream';

header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . $size);
header('Accept-Ranges: bytes'); // 支援斷點續傳

// 大檔案分塊輸出,避免記憶體爆炸
$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
    echo fread($handle, 8192);
    flush(); // 發送至瀏覽器
}
fclose($handle);
exit;
?>

2.4 安全標頭(現代 Web 必備)

<?php
// 防點擊劫持
header('X-Frame-Options: DENY'); // 或 SAMEORIGIN

// 防 MIME 嗅探
header('X-Content-Type-Options: nosniff');

// XSS 保護(舊瀏覽器)
header('X-XSS-Protection: 1; mode=block');

// 內容安全策略(CSP)核心防禦
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none';");

// 強制 HTTPS(HSTS,需配合 HTTPS 部署)
// header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');

// Referrer 政策
header('Referrer-Policy: strict-origin-when-cross-origin');

// 權限政策
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
?>

2.5 CORS 跨域資源共享

<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];

if (in_array($origin, $allowedOrigins, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    header('Access-Control-Max-Age: 86400');
}

// 預檢請求快速回應
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
?>

三、常見錯誤與除錯

錯誤原因解決
Cannot modify header information - headers already sentheader() 前有輸出(echo、HTML、空白、BOM、錯誤訊息)1. 檢查檔案開頭無 BOM/空白 2. 使用 ob_start() 3. 重構程式碼:先邏輯後輸出
重導向不生效未呼叫 exit、狀態碼錯誤、Location 值非絕對 URL加上 exit、使用完整 URL、檢查 301/302/303 選擇
中文檔名下載亂碼RFC 5987 編碼缺失filename*=UTF-8'' . rawurlencode($filename)
多次 header 覆蓋預設 replace=true多值標頭用 header('Set-Cookie: ...', false)

3.1 中文檔名完整解決方案

<?php
$filename = '報表_2024.pdf';
$encoded = rawurlencode($filename);
header("Content-Disposition: attachment; filename=\"$encoded\"; filename*=UTF-8''$encoded");
?>

四、輸出緩衝進階控制

4.1 巢狀緩衝

<?php
ob_start(); // Level 1
echo "A";
ob_start(); // Level 2
echo "B";
$inner = ob_get_clean(); // 取得 "B",關閉 Level 2
echo "C";
$outer = ob_get_clean(); // 取得 "AC",關閉 Level 1
echo $outer . $inner; // ACB
?>

4.2 緩衝回調:自動處理輸出

<?php
ob_start(function($buffer) {
    // 壓縮、替換、記錄
    return str_replace('[APP]', 'MyApp', $buffer);
});
echo "[APP] started";
ob_end_flush(); // 輸出: MyApp started
?>

五、最佳實踐清單

  1. 入口檔案最頂端 ob_start(),框架通常自動處理。
  2. 重導向後立即 exit,防止後續程式碼執行。
  3. 統一使用 http_response_code() 設定狀態碼(PHP 5.4+),語意更清晰。
  4. 所有使用者輸入進標頭值必須過濾換行符(\r, \n),防 HTTP 標頭注入。
  5. 安全標頭集中管理:中介軟體/過濾器統一加入 CSP、HSTS、X-Frame-Options 等。
  6. 測試工具:curl -I、瀏覽器 DevTools Network、securityheaders.com 掃描。

結語

header() 是 PHP 與 HTTP 協定溝通的橋樑。掌握「輸出前呼叫」、「標頭語意正確性」、「安全標頭部署」、「檔案下載分塊輸出」與「輸出緩衝控制」,能構建符合現代 Web 標準、安全且高效能的 PHP 應用。

copyright © 萬盛學電腦網 all rights reserved