萬盛學電腦網

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

PHP header() 函數完整指南:常用 HTTP 標頭設定與實戰技巧

前言

header() 是 PHP 中控制 HTTP 回應標頭的核心函數,掌握其用法對於實作 API、檔案下載、快取控制、重導向等功能至關重要。本文彙整最常見的使用場景,並說明關鍵注意事項,幫助開發者避開常見陷阱。

基本語法與核心原則

header(string $header, bool $replace = true, int $response_code = 0): void

鐵律: 必須在任何實際輸出(HTML、空白字元、echo、print 等)之前呼叫,否則會觸發 Cannot modify header information - headers already sent 警告。

分類速查表

1. 內容類型與編碼宣告

<?php
// 基礎編碼宣告(建議放在腳本最頂端)
header('Content-Type: text/html; charset=utf-8');

// 常見 MIME 類型
header('Content-Type: application/json');           // JSON API
header('Content-Type: application/xml');            // XML
header('Content-Type: text/css');                   // CSS
header('Content-Type: application/javascript');     // JS
header('Content-Type: image/jpeg');                 // JPEG 圖片
header('Content-Type: application/pdf');            // PDF
header('Content-Type: application/octet-stream');   // 通用二進位下載

2. HTTP 狀態碼控制

<?php
header('HTTP/1.1 200 OK');              // 成功(預設)
header('HTTP/1.1 404 Not Found');       // 找不到資源
header('HTTP/1.1 301 Moved Permanently'); // 永久重導向(SEO 友善)
header('HTTP/1.1 302 Found');           // 暫時重導向
header('HTTP/1.1 304 Not Modified');    // 未修改(配合快取)
header('HTTP/1.1 401 Unauthorized');    // 需驗證
header('HTTP/1.1 403 Forbidden');       // 拒絕存取
header('HTTP/1.1 500 Internal Server Error'); // 伺服器錯誤

3. 重導向與延遲跳轉

<?php
// 立即重導向(絕對 URL)
header('Location: https://example.com/new-page.php');
exit; // 關鍵:防止後續程式碼繼續執行

// 延遲 5 秒跳轉
header('Refresh: 5; url=https://example.com/');
echo '5 秒後自動跳轉...';

4. 檔案下載標頭組合

<?php
$filename = 'report-2024.xlsx';
$filepath = '/var/www/files/' . $filename;

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . filesize($filepath));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($filepath);
exit;

5. 快取控制策略

<?php
// 完全禁用快取(適用於動態 API、敏感頁面)
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 相容

// 允許快取 1 小時(適用於靜態資源)
header('Cache-Control: public, max-age=3600');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');

6. 最後修改時間與 ETag(條件式請求)

<?php
$last_modified = filemtime($filepath);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $last_modified) . ' GMT');
header('ETag: "' . md5_file($filepath) . '"');

// 檢查客戶端快取
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $client_time = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
    if ($client_time >= $last_modified) {
        header('HTTP/1.1 304 Not Modified');
        exit;
    }
}

7. 安全性相關標頭

<?php
// 防止點擊劫持
header('X-Frame-Options: DENY');
// 或允許同源嵌入:header('X-Frame-Options: SAMEORIGIN');

// 啟用 XSS 過濾
header('X-XSS-Protection: 1; mode=block');

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

// 內容安全政策(CSP)範例
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com;");

// 隱藏 PHP 版本資訊
header('X-Powered-By: '); // 移除預設標頭

8. CORS 跨域資源共享

<?php
// 允許特定來源
header('Access-Control-Allow-Origin: https://app.example.com');
// 或允許所有(開發階段):header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // 預檢請求快取 24 小時

// 處理 OPTIONS 預檢請求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

常見錯誤與除錯技巧

  1. 輸出前有空白字元:檢查 <?php 前是否有換行或空格,建議省略結尾 ?>。
  2. BOM 標記:以 UTF-8 without BOM 儲存檔案。
  3. 多次設定同一標頭:預設 $replace = true 會覆蓋,若需多值(如多個 Set-Cookie)請設 false。
  4. 重導向後未 exit:導致後續邏輯仍執行,浪費資源或洩露資料。

進階技巧:標頭封裝函數

<?php
function set_json_response($data, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-cache, must-revalidate');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// 使用範例
set_json_response(['status' => 'success', 'data' => $user_list]);

總結

header() 是 PHP 與 HTTP 協定溝通的橋樑。熟練掌握內容類型、狀態碼、快取、安全、CORS 等標頭設定,能讓你精確控制瀏覽器行為、優化效能、強化安全性。記住「輸出前設定、重導向後退出」兩大鐵律,即可避開 90% 的標頭相關問題。

copyright © 萬盛學電腦網 all rights reserved