CakeFest 2024: The Official CakePHP Conference

header_register_callback

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

header_register_callbackヘッダ用の関数を登録する

説明

header_register_callback(callable $callback): bool

PHP が出力を送信しはじめるときにコールする関数を登録します。

callback が実行されるのは、 PHP がすべてのヘッダを送出し終えてからその他の出力を始めるまでの間です。 ここで、送信する前のヘッダを操作できます。

パラメータ

callback

ヘッダを送信する前にコールする関数。パラメータは受け取らず、戻り値も無視されます。

戻り値

成功した場合に true を、失敗した場合に false を返します。

例1 header_register_callback() の例

<?php

header
('Content-Type: text/plain');
header('X-Test: foo');

function
foo() {
foreach (
headers_list() as $header) {
if (
strpos($header, 'X-Powered-By:') !== false) {
header_remove('X-Powered-By');
}
header_remove('X-Test');
}
}

$result = header_register_callback('foo');
echo
"a";
?>

上の例の出力は、 たとえば以下のようになります。

Content-Type: text/plain

a

注意

header_register_callback() はヘッダを送出しようとするときに実行されるので、 この関数の中で何らかの出力をしてしまうと出力が壊れてしまいます。

注意:

ヘッダにアクセスできたりヘッダを出力したりするのは、 それに対応した SAPI を使っている場合のみです。

参考

  • headers_list() - 送信した (もしくは送信される予定の) レスポンスヘッダの一覧を返す
  • header_remove() - 以前に設定したHTTPヘッダを削除する
  • header() - 生の HTTP ヘッダを送信する
add a note

User Contributed Notes 1 note

up
12
matt@kafene
11 years ago
Note that this function only registers a single callback as of php 5.4. The most recent callback set is the one that will be executed, they will not be executed in order like with register_shutdown_function(), just overwritten.

Here is my test:

<?php

$i
= $j = 0;
header_register_callback(function() use(&$i){ $i+=2; });
header_register_callback(function() use(&$i){ $i+=3; });
register_shutdown_function(function() use(&$j){ $j+=2; });
register_shutdown_function(function() use(&$j){ $j+=3; });
register_shutdown_function(function() use(&$j){ var_dump($j); });
while(!
headers_sent()) { echo "<!-- ... flushing ... -->"; }
var_dump(headers_sent(), $i);
exit;

?>

Results:

headers_sent() - true
$i = 3
$j = 5
To Top