首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

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

     編輯:PHP 綜合知識

前言

header() 是 PHP 傳送原始 HTTP 標頭的核心函式,必須在任何實際輸出(HTML、空白、echo)之前呼叫。本文彙整最常見的實戰場景,附上可直接複製的程式碼片段。

1. HTTP 狀態碼控制

<?php
// 正常回應(預設)
header('HTTP/1.1 200 OK');

// 404 找不到
header('HTTP/1.1 404 Not Found');

// 301 永久移動(SEO 必用,搭配 Location)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://new-domain.com/');

// 304 未修改(配合快取驗證)
header('HTTP/1.1 304 Not Modified');

// 401 需驗證(Basic Auth)
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
echo '認證失敗或取消登入';
?>

2. 重導向與延遲跳轉

<?php
// 立即重導向
header('Location: https://example.com/');
exit; // 最佳實務:重導向後立即結腳本

// 延遲 10 秒跳轉(等同 HTML meta refresh)
header('Refresh: 10; url=https://example.com/');
echo '10 秒後自動跳轉...';
?>

3. 快取控制

<?php
// 禁止快取(動態頁面、API 介面必加)
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Pragma: no-cache'); // HTTP/1.0 相容

// 啟用快取(靜態資源)
$time = time() - 60; // 或 filemtime($filename)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('Cache-Control: public, max-age=3600'); // 快取 1 小時
?>

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

<?php
$file = 'example.zip';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
readfile($file); // 高效輸出檔案內容
exit;
?>

5. 內容型別與編碼

<?php
header('Content-Type: text/html; charset=utf-8');  // HTML
header('Content-Type: application/json; charset=utf-8'); // JSON API
header('Content-Type: image/jpeg');                // 圖片
header('Content-Type: application/pdf');           // PDF
header('Content-Type: audio/mpeg');                // MP3
header('Content-Type: application/x-shockwave-flash'); // SWF
?>

6. 自訂標頭與隱藏資訊

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

// 多語言內容
header('Content-Language: zh-TW');
?>

⚠️ 常見陷阱

  • 輸出前呼叫:任何 echo、HTML 空白、BOM 都會導致 Cannot modify header information 錯誤。
  • 重導向後未 exit:腳本會繼續執行,浪費資源且可能輸出干擾內容。
  • 中文檔名下載:需依 RFC 5987 編碼:filename*=UTF-8''%E6%AA%94%E6%A1%88.zip,兼容舊版 IE 需額外處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved