請注意,它不會返回狀態標頭
<?php
header('HTTP/1.1 301 Moved Permanently', true, 301);
header('foo: bar');
header('a: b');
header('colon less example');
print_r(headers_list());
?>
陣列
(
[0] => X-Powered-By: PHP/5.4.7
[1] => foo: bar
[2] => a: b
)
(PHP 5, PHP 7, PHP 8)
headers_list — 返回已傳送(或準備傳送)的回應標頭清單
此函式沒有參數。
返回標頭的數值索引陣列。
範例 #1 使用 headers_list() 的範例
<?php
/* setcookie() 會自行加入一個回應標頭 */
setcookie('foo', 'bar');
/* 定義一個自訂回應標頭
大多數客戶端會忽略這個標頭 */
header("Example-Test: foo");
/* 在我們的回應中指定純文字內容 */
header('Content-Type: text/plain; charset=UTF-8');
/* 將要發送哪些標頭? */
var_dump(headers_list());
?>
上述範例將輸出類似以下內容
array(3) { [0]=> string(19) "Set-Cookie: foo=bar" [1]=> string(17) "Example-Test: foo" [2]=> string(39) "Content-Type: text/plain; charset=UTF-8" }
注意:
只有在使用支援標頭的 SAPI 時,才能存取和輸出標頭。
請注意,它不會返回狀態標頭
<?php
header('HTTP/1.1 301 Moved Permanently', true, 301);
header('foo: bar');
header('a: b');
header('colon less example');
print_r(headers_list());
?>
陣列
(
[0] => X-Powered-By: PHP/5.4.7
[1] => foo: bar
[2] => a: b
)
當您從命令列執行 PHP 時,此函式將無法運作。它將始終返回一個空陣列。這在使用 PHPUnit 或 Codeception 測試您的專案時可能會造成問題。
要解決此問題,請安裝 xdebug 擴充功能,並在 cli 上使用 `xdebug_get_headers`。
<?php
$headers = php_sapi_name() === 'cli' ? xdebug_get_headers() : headers_list();
?>