萬盛學電腦網

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

PHP header() 常用標頭定義速查總表:狀態碼、Content-Type、快取、下載、重導向、認證

header() 必須在**任何輸出前**呼叫。本文整理最實用的標頭定義分類速查,可直接複製套用。

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/'); // 延遲跳轉

Content-Type 對照表

類型標頭
HTML UTF-8header('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');
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');
PNG/GIFheader('Content-Type: image/png'); / 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="file.zip"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.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');

快取驗證

$time = time() - 60;
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="Admin Area"');
echo '認證失敗顯示此訊息';

安全與其他實用標頭

header('X-Powered-By: Custom/1.0');           // 隱藏 PHP 版本
header('X-Frame-Options: DENY');              // 防 iframe 嵌入
header('X-Content-Type-Options: nosniff');    // 禁用 MIME 嗅探
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Content-Security-Policy: default-src \'self\';'); // CSP 基礎

重要提醒

  • 輸出前呼叫:ob_start() 可緩衝解決順序問題
  • 重導向後加 exit;
  • 下載檔案務必設 Content-Length
  • 中文檔名需 urlencode() 或 RFC 5987 編碼

收藏此表,API、下載、快取、安全標頭一查即得。

copyright © 萬盛學電腦網 all rights reserved