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

PHP header() 函數完整語法與實戰應用大全

     編輯:PHP 相關知識

語法定義

void header(string $string [, bool $replace = true [, int $http_response_code ]])

向客戶端發送原始 HTTP Header。絕對要在任何實際輸出(HTML、空白行、echo 等)之前呼叫,否則會觸發 "Headers already sent" 警告。

參數說明

  • $string:Header 字串(必填)
  • $replace:是否替換同類型 Header,預設 true;false 允許同類型多值
  • $http_response_code:強制指定 HTTP 狀態碼(PHP 4.3+)

常見實戰場景與程式碼範例

1. 發送 HTTP 狀態碼

header('HTTP/1.1 200 OK');
header('HTTP/1.1 301 Moved Permanently');
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 404 Not Found');
header('HTTP/1.1 500 Internal Server Error');

常用狀態碼分類:

  • 2xx 成功(200)
  • 3xx 重導向(301 永久、302 暫時、304 快取)
  • 4xx 用戶端錯誤(401 未授權、403 禁止、404 找不到)
  • 5xx 伺服器錯誤(500)

2. 頁面重導向

// 立即跳轉
header('Location: https://example.com/');
exit; // 建議配合 exit 防止後續代碼執行

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

3. 控制瀏覽器快取

// 強制不快取(適用動態頁面、API)
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // 過去時間
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

// 允許快取 5 秒(適用半靜態資源)
header('Cache-Control: max-age=5, public');

Cache-Control 指令速查:

指令說明
public所有內容可被快取(含 Proxy)
private僅客戶端私有快取
no-cache每次請求必須向伺服器驗證
no-store不快取任何內容(含暫存檔)
must-revalidate過期後必須回源驗證
max-age=秒數快取有效期(優先於 Expires)

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

// 範例:下載 PDF
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
header('Content-Length: ' . filesize('report.pdf'));
readfile('report.pdf'); // 直接輸出檔案內容
exit;

通用二進位下載 Header:

header('Content-Type: application/octet-stream');
header('Accept-Ranges: bytes');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
readfile($file);

5. 利用 Last-Modified / ETag 實現條件式請求(304)

$lastModified = filemtime($file);
$etag = md5_file($file);

header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lastModified).' GMT');
header('ETag: "'.$etag.'"');

$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false;
$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH']) : false;

if (($ifModifiedSince && $ifModifiedSince >= $lastModified) || ($ifNoneMatch && $ifNoneMatch === $etag)) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}

// 正常輸出內容...

最佳實踐提醒

  1. 所有 header() 呼叫前不可有任何輸出(含 BOM、空白行)。
  2. 重導向後務必 exit; 避免後續邏輯執行。
  3. 下載大檔案時建議啟用 Content-Length 並分塊輸出,避免記憶體耗盡。
  4. API 回應統一加上 Cache-Control: no-store 防止敏感資料被 Proxy 快取。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved