【发布时间】:2014-02-20 07:51:33
【问题描述】:
我需要使用状态码 204 响应 HEAD 请求。
<?php
if($_SERVER['REQUEST_METHOD']=='HEAD') {
ob_clean();
setHeaderStatus(204, true);
// other headers
header('X-Other-123: 123');
header('Location: '.sprintf('%s://%s%s', $_SERVER['REQUEST_SCHEME'],
$_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']));
header('Date: '.date('r'));
header('Content-Type: text/html', true);
header('Content-Length: 0', true);
flush();
die;
}
$messages = array( // {{{
// ...
204 => '204 No Content',
// ...
);
function setHeaderStatus($status, $replace = true)
{
Global $messages;
if (headers_sent() === true)
return;
if (strpos(PHP_SAPI, 'cgi') === 0) {
header('Status: '.$messages[$status], $replace);
} else {
header($_SERVER["SERVER_PROTOCOL"].' '.$messages[$status], $replace);
}
}
用 cURL 测试这个:
curl -i --noproxy 127.0.0.1 -X HEAD http://localhost/test.php
结果:
HTTP/1.1 302 Found
Date: Thu, 20 Feb 2014 07:46:27 GMT
Server: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.19
X-Powered-By: PHP/5.4.19
X-Other-123: 123
Location: http://localhost/test.php
Content-Type: text/html
看来 Apache 覆盖了 PHP 设置的状态码?
提前致谢。
【问题讨论】:
-
请删除冲洗和死亡
-
删除 flush and die 不会改变响应代码 - 仍然 302 Found。