萬盛學電腦網

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

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

header() 基本語法

void header(string $header, bool $replace = true, int $http_response_code = 0)
參數說明
$headerHTTP 標頭字串(必填)
$replace是否替換同類型標頭(預設 true)
$http_response_code強制指定 HTTP 回應碼(PHP 4.3+)

核心應用場景

1. 頁面重導向

<?php
// 絕對 URL(推薦)
header('Location: https://example.com/page.php');
exit();  // 必須 exit,防止後續代碼執行

// 相對路徑(HTTP/1.1 要求絕對 URL,但瀏覽器普遍支援相對)
header('Location: /login.php');
exit();

注意:`header('Location: ...')` 前不能有任何輸出(含空白、BOM、echo)。

2. 設定 HTTP 狀態碼

<?php
// 404 Not Found
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");  // FastCGI 相容

// 301 永久移動(SEO 友善)
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://new-domain.com/page.php");

// 503 服務暫時不可用(維護模式)
header("HTTP/1.1 503 Service Unavailable");
header("Retry-After: 3600");  // 1 小時後重試
echo '系統維護中,請稍後再試。';
exit();

3. 快取控制

<?php
// 禁止快取(動態內容、API 回應)
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP/1.1
header("Pragma: no-cache");                                     // HTTP/1.0 相容
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");               // 過去時間

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

4. 檔案下載(強制下載而非瀏覽器開啟)

<?php
$file = '/path/to/secret/report.pdf';
$filename = 'monthly_report_2024.pdf';

if (!file_exists($file)) {
    header("HTTP/1.1 404 Not Found");
    exit('檔案不存在');
}

header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Length: " . filesize($file));
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

readfile($file);  // 高效輸出檔案內容,不佔用 PHP 記憶體
exit();

5. JSON API 回應

<?php
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');  // 安全:防 MIME 嗅探

echo json_encode(['status' => 'ok', 'data' => $data], JSON_UNESCAPED_UNICODE);

6. CORS 跨域授權

<?php
// 允許特定域名
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');
header('Access-Control-Max-Age: 86400');  // 預檢快取 24 小時

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

常見錯誤與最佳實踐

錯誤原因解決
Headers already sentheader() 前有輸出(echo、空白、BOM)確保 header() 在最頂端,檔案存為 UTF-8 無 BOM
重導向失效忘記 exit(),後續代碼繼續執行header() 後立即 exit()
中文檔名亂碼Content-Disposition 編碼問題用 RFC 5987 格式:`filename*=UTF-8''` + urlencode()
大檔案下載記憶體爆炸用 file_get_contents() 載入整個檔案用 readfile() 或分塊 fread() 輸出

中文檔名下載完整相容寫法

function download_file($filepath, $filename) {
    if (!file_exists($filepath)) return false;
    
    $encoded = rawurlencode($filename);
    $disposition = "attachment; filename=\"$encoded\"; filename*=UTF-8''$encoded";
    
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: $disposition");
    header("Content-Length: " . filesize($filepath));
    header("Cache-Control: no-cache, must-revalidate");
    
    $handle = fopen($filepath, 'rb');
    while (!feof($handle)) {
        echo fread($handle, 8192);
        flush();  // 即時輸出,低記憶體
    }
    fclose($handle);
    exit();
}
copyright © 萬盛學電腦網 all rights reserved