HTTP響應頭包含快取控制、內容類型、Cookie設定等關鍵元數據。PHP提供headers_list()函數獲取即將發送給客戶端的所有Header,適用於調試、測試、安全審計等場景。
headers_list(): array
// 返回數字索引數組,每個元素為完整Header字符串,如 "Content-Type: text/html; charset=utf-8"
header("Expires: Sat, 12 Dec 1989 05:30:00 GMT");
echo "This is some output.
";
echo "Headers sent are:
";
$headers = headers_list();
foreach ($headers as $header) {
echo "- $header
";
}
echo "
";
function set_header_once($header) {
$existing = headers_list();
if (!in_array($header, $existing)) {
header($header);
}
}
$security_headers = [
'X-Content-Type-Options: nosniff',
'X-Frame-Options: DENY',
'Content-Security-Policy: default-src \'self\'',
'Strict-Transport-Security: max-age=31536000',
];
$sent = headers_list();
foreach ($security_headers as $h) {
if (!in_array($h, $sent)) {
error_log("Missing security header: $h");
}
}
// PHPUnit風格
$this->assertContains('Content-Type: application/json', headers_list());
Date、Server等Header(由Web服務器添加)。headers_sent()判斷是否仍可修改Header。善用headers_list()能顯著提升API調試效率與安全合規檢查自動化程度。