HTTP 狀態碼
header('HTTP/1.1 200 OK');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 301 Moved Permanently');
重導向
header('Location: https://example.com/');
header('Refresh: 10; url=https://example.com/'); // 10 秒後跳轉
echo 'You will be redirected in 10 seconds';
自訂標頭
header('X-Powered-By: PHP/7.4');
header('Content-language: en');
快取控制
$time = time() - 60;
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('HTTP/1.1 304 Not Modified'); // 告知瀏覽器使用快取
// 禁用快取
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('Content-Length: 1234');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
readfile('example.zip');
常見 Content-Type 對照表
| 類型 | header() 設定 |
| HTML (UTF-8) | header('Content-Type: text/html; charset=utf-8'); |
| HTML (ISO-8859-1) | header('Content-Type: text/html; charset=iso-8859-1'); |
| 純文字 | header('Content-Type: text/plain'); |
| JSON | header('Content-Type: application/json'); |
| XML | header('Content-Type: text/xml'); |
| CSS | header('Content-Type: text/css'); |
| JavaScript | header('Content-Type: text/javascript'); |
| JPEG | header('Content-Type: image/jpeg'); |
| PNG | header('Content-Type: image/png'); |
| GIF | header('Content-Type: image/gif'); |
| PDF | header('Content-Type: application/pdf'); |
| ZIP | header('Content-Type: application/zip'); |
| 音訊 (MP3) | header('Content-Type: audio/mpeg'); |
| Flash | header('Content-Type: application/x-shockwave-flash'); |
| Atom | header('Content-Type: application/atom+xml'); |
| RSS | header('Content-Type: application/rss+xml; charset=ISO-8859-1'); |
HTTP 基礎認證
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
echo 'Text shown if user cancels or enters wrong credentials';