萬盛學電腦網

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

PHP header() 常見 Content-Type、HTTP 狀態碼、快取控制、下載與重導向完整速查表

header() 必須在**任何實際輸出之前**呼叫(PHP 4+ 可用輸出緩衝解決)。本文彙整最常用的標頭定義,供快速查閱複製。

HTTP 狀態碼

header('HTTP/1.1 200 OK');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 301 Moved Permanently'); // 永久重導向
header('HTTP/1.1 304 Not Modified');     // 快取驗證

重導向與延遲跳轉

header('Location: https://example.com/');           // 立即跳轉
header('Refresh: 10; url=https://example.com/');    // 10 秒後跳轉
// HTML 替代:

Content-Type 對照表

檔案類型header() 設定
HTML (UTF-8)header('Content-Type: text/html; charset=utf-8');
純文字header('Content-Type: text/plain');
CSSheader('Content-Type: text/css');
JavaScriptheader('Content-Type: text/javascript');
JSONheader('Content-Type: application/json');
XMLheader('Content-Type: text/xml'); 或 application/xml
RSSheader('Content-Type: application/rss+xml; charset=ISO-8859-1');
Atomheader('Content-Type: application/atom+xml');
PDFheader('Content-Type: application/pdf');
ZIPheader('Content-Type: application/zip');
JPEGheader('Content-Type: image/jpeg');
PNGheader('Content-Type: image/png');
GIFheader('Content-Type: image/gif');
音頻 MP3header('Content-Type: audio/mpeg');
Flashheader('Content-Type: application/x-shockwave-flash');

檔案下載強制彈出儲存對話框

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('example.zip'));
readfile('example.zip');

Excel 下載(新版 .xlsx)

header('Content-Disposition: attachment; filename="report.xlsx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize('report.xlsx'));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('report.xlsx');

禁用快取(防止瀏覽器/代理快取動態內容)

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 相容

Last-Modified / ETag 快取驗證

$time = time() - 60; // 或 filemtime($file)
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('ETag: "' . md5_file($file) . '"');

HTTP 基本認證對話框

header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Restricted Area"');
echo '取消或輸入錯誤帳密將顯示此訊息';

其他實用標頭

header('X-Powered-By: PHP/8.2');        // 隱藏/修改版本資訊
header('Content-Language: zh-TW');      // 文件語言
header('Content-Length: 1234');         // 內容長度
header('X-Frame-Options: DENY');        // 防點擊劫持
header('X-Content-Type-Options: nosniff'); // 禁用 MIME 嗅探
header('Referrer-Policy: strict-origin-when-cross-origin');

重要提醒

  • 所有 header() 必須在 echo、print、HTML 空白、BOM 之前
  • 若已有輸出,啟用 ob_start() 緩衝或調整程式碼順序
  • 重導向後建議加 exit; 避免後續程式碼執行
  • 檔案下載務必設定 Content-Length 讓瀏覽器顯示進度

收藏此速查表,開發 API、檔案下載、快取控制、認證流程時即查即用。

copyright © 萬盛學電腦網 all rights reserved