简体   繁体   English

PHP未设置HTTP状态代码

[英]PHP Not Setting HTTP Status Code

I need to respond to a HEAD request with status code 204. 我需要以状态代码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);
    }
}

Testing this with cURL: 使用cURL进行测试:

curl -i --noproxy 127.0.0.1 -X HEAD http://localhost/test.php

results in: 结果是:

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

So it seems Apache overrides the status code set by PHP? 如此看来,Apache会覆盖PHP设置的状态代码吗?

Thanks in advance. 提前致谢。

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

Normally header('Location:...' will automatic change header status to 301 or 302 to redirect. May be it override your setting. 通常header('Location:...'会自动将标题状态更改为301或302进行重定向。可能会覆盖您的设置。

Solved. 解决了。

As the PHP manual says: 如PHP手册所述:

"The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set." “第二个特殊情况是“ Location:”标头。它不仅将此标头发送回浏览器,而且还向浏览器返回REDIRECT(302)状态码,除非已经输入201或3xx状态码。组。”

As I set the 204 code, it was always overridden by the Location header to 302. 当我设置204代码时,它总是被Location标头覆盖为302。

What finally solves it is: 最终解决的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM