phpday 2027 - Call for Papers

header_register_callback

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

header_register_callback — Call a header function

Description

function header_register_callback(callable $callback): true

Registers a function that will be called when PHP starts sending output.

The callback is executed just after PHP prepares all headers to be sent, and before any other output is sent, creating a window to manipulate the outgoing headers before being sent.

Warning

Callbacks are not stacked. Subsequent calls to header_register_callback() will silently de-register any existing callback, regardless of where it was set. Be aware that dependencies may overwrite the callback. Troubleshooting this scenario can be difficult.

Parameters

callback

Function called just before the headers are sent. It gets no parameters and the return value is ignored.

Return Values

Always returns true.

Changelog

Version Description
8.6.0 Now has a return type of true instead of bool.

Examples

Example #1 header_register_callback() example

<?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";
?>

The above example will output something similar to:

Content-Type: text/plain

a

Notes

header_register_callback() is executed just as the headers are about to be sent out, so any output from this function can break output.

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

User Contributed Notes 1 note

up
12
matt@kafene
13 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
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top