PHP: Get http status code that own script just sent out via shutdown function
I have a shutdown function that checks to see if a redirect was just issued. From headers_list() I can get the headers sent and see the location header. My question is how would I figure out what http_response_code was used in the header() function. Headers list doesn't have the response code.
Example code to play around with. I don't use redirects in the example code, otherwise it would loop. Main thing is I would like to detect a 301 vs any other kind of redirect. This would be inside drupal (via drupal_goto using hook_exit); but the example code below shows the issue. I have no way of knowing what status number was passed to the browser via header().
<?php
register_shutdown_function('test');
if (mt_rand(0, 1)) {
header('X-test: junk 1', TRUE, 201);
}
else {
header('X-test: junk 0', TRUE, 202);
}
exit();
function test() {
if ($location = test_heade开发者_如何学Pythonrs_contain('X-test: ')) {
// Would like to check the status code that was sent out
echo $location . '<br>';
$list = headers_list();
$txt = str_replace(' ', ' ', nl2br(htmlentities(print_r($list, TRUE))));
echo $txt;
}
}
function test_headers_contain($text) {
if (function_exists('headers_list')) {
$list = headers_list();
if (empty($list)) {
return FALSE;
}
foreach ($list as $header) {
$info = stristr($header, $text);
if ($info !== FALSE) {
return $info;
}
}
}
return FALSE;
}
?>
This code outputs this
X-test: junk 1
Array
(
[0] => X-Powered-By: PHP/5.2.10
[1] => X-test: junk 1
)
Revision 302033 added the function http_response_code
in response to just the sort of issue you describe, but I'm not certain when it will be included in a release. It's not in 5.3.4. If you have access, you could build a patched version of PHP with this function added. If not, you could request it of whoever on your host does have access.
精彩评论