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

PHP header() 函數常用標頭設定速查表

     編輯:PHP 綜合知識

前言

header() 是 PHP 中發送原始 HTTP 標頭的核心函數,必須在任何實際輸出之前呼叫。本文整理開發中最常用的標頭設定,涵蓋內容型別、狀態碼、重導向、快取控制、檔案下載、認證等場景,方便快速查閱。

內容型別

// 通用
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain');
header('Content-Type: application/json');
header('Content-Type: application/xml');
header('Content-Type: application/pdf');

// 靜態資源
header('Content-Type: text/css');
header('Content-Type: text/javascript');
header('Content-Type: image/jpeg');
header('Content-Type: image/png');
header('Content-Type: application/zip');
header('Content-Type: audio/mpeg');
header('Content-Type: application/x-shockwave-flash');

// RSS / Atom
header('Content-Type: application/rss+xml; charset=ISO-8859-1');
header('Content-Type: application/atom+xml');

HTTP 狀態碼與重導向

// 成功
header('HTTP/1.1 200 OK');

// 錯誤
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 401 Unauthorized');
header('HTTP/1.1 403 Forbidden');

// 永久/暫時重導向
header('HTTP/1.1 301 Moved Permanently');
header('HTTP/1.1 302 Found');
header('Location: https://example.com/new-page');

// 延遲重導向(10 秒後跳轉)
header('Refresh: 10; url=https://example.com/');
echo '您將在 10 秒後被重導向...';

快取控制

// 禁用快取(適用動態頁面、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');

// 啟用快取(靜態資源)
header('Cache-Control: public, max-age=31536000'); // 1 年
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');

檔案下載

$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);

其他實用標頭

// 最後修改時間(配合 304 Not Modified)
$time = time() - 60; // 或 filemtime($filename)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');

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

// 隱藏 PHP 版本資訊
header('X-Powered-By: Custom-Framework/1.0');

// HTTP 基本認證
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Restricted Area"');
echo '需要登入才能存取';

重要提醒

  • header() 必須在任何 echo、print、HTML 空白字元之前呼叫
  • 使用 headers_sent() 可檢查標頭是否已發送
  • 重導向後建議加上 exit() 避免後續程式碼執行
  • 中文檔名下載時需注意瀏覽器編碼差異,建議使用 rawurlencode() 處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved