【问题标题】:PHP Not Setting HTTP Status CodePHP 未设置 HTTP 状态码
【发布时间】: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。

标签: php apache http status


【解决方案1】:

header('Location:... 之后尝试setHeaderStatus(204, true);

通常header('Location:...' 会自动将标头状态更改为 301 或 302 以进行重定向。可能会覆盖您的设置。

【讨论】:

  • 更改为 header('Location: ...) 和 setHeaderStatus(204, true) 现在返回 200 OK,仍然不是 204
【解决方案2】:

解决了。

正如 PHP 手册所说:

“第二种特殊情况是“Location:”标头。它不仅将这个标头发送回浏览器,而且还会向浏览器返回一个REDIRECT(302)状态码,除非是201或3xx状态码已经设置好了。”

当我设置 204 代码时,它总是被 Location 标头覆盖为 302。

最终解决的是:

header('Location: ...', true, 204 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 2013-05-14
    • 2015-04-20
    • 2012-07-10
    • 2018-10-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多