PHP 8.1.28 Released!

header_register_callback

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

header_register_callback调用一个 header 函数

说明

header_register_callback(callable $callback): bool

注册一个函数,在 PHP 开始发送输出时调用。

PHP 准备好所有响应头,在发送内容之前执行 callback,创建了一个发送响应头的操作窗口。

参数

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支持时得到处理和输出。

参见

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