PHP Conference Japan 2024

header_remove

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

header_remove移除先前設定的標頭

說明

header_remove(?string $name = null): void

移除先前使用 header() 設定的 HTTP 標頭。

參數

name

要移除的標頭名稱。當設為 null 時,所有先前設定的標頭都會被移除。

注意事項此參數不區分大小寫。

回傳值

無回傳值。

更新日誌

版本 說明
8.0.0 name 現在可以為 null。

範例

範例 #1 移除特定標頭。

<?php
header
("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

上述範例的輸出會類似於

X-Bar: Baz

範例 #2 移除所有先前設定的標頭。

<?php
header
("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

上述範例的輸出會類似於


備註

警告

此函式會移除 PHP 設定的*所有*標頭,包括 cookies、session 和 X-Powered-By 標頭。

注意事項:

只有在使用支援標頭的 SAPI 時,才能存取和輸出標頭。

另請參閱

新增備註

使用者貢獻的備註 4 則備註

Saeed Khamseh
13 年前
如果您想移除關於 php 版本的標頭資訊 (x-powered-by),您可以使用

header_remove('x-powered-by');

或者,如果您沒有安裝 php 5.3,您可以使用 "header" 指令執行相同的操作

header('x-powered-by:');

不要忘記字串結尾的 ':' 字元!
匿名
9 年前
expose_php 只能在 php.ini 中設定!

這行不通
ini_set('expose_php',0);

有效
header_remove('x-powered-by');
luis dot angelino at laweb dot com dot br
6 個月前
如果您正在使用這個

#!/usr/local/bin/php

您可以在它的末尾新增 "-q",標頭將會被移除,因為 header_remove 不會移除 "Content-type"

#!/usr/local/bin/php -q
jake at qzdesign dot co dot uk
6 年前
當從命令列程序呼叫時,如果傳遞特定標頭以移除,此函式不會執行任何操作,但在呼叫時不帶參數以移除所有標頭時,它仍然可以正常運作。

因此,在單元測試或在其他測試工具中執行時,如果您正在測試的程式碼可能會呼叫 `header_remove()`,並且載入了 UOPZ 和 XDebug 擴充功能,您可以使用以下方法來更有效地測試是否設定了預期的標頭 [您可以透過檢查執行測試程式碼後 `xdebug_get_headers()` 返回的陣列來執行此操作,因為儘管標頭實際上已正常儲存在內部,`headers_list()` 仍然無法運作]

<?php
uopz_set_return
(
'header_remove',
function(
$name = null) {
if (
$name !== null) {
$pattern = '/^' . preg_quote($name, '/') . ':/i';
$headers = array_filter(
xdebug_get_headers(),
function(
$header) use($pattern) {
return !
preg_match($pattern, $header);
}
);
}
// 這可以移除所有標頭,但無法移除個別標頭。
header_remove();
if (
$name !== null) {
foreach (
$headers as $header) {
header($header);
}
}
},
true
);
?>
To Top