簡體   English   中英

PHP未設置HTTP狀態代碼

[英]PHP Not Setting HTTP Status Code

我需要以狀態代碼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設置的狀態代碼嗎?

提前致謝。

嘗試setHeaderStatus(204, true); header('Location:...之后header('Location:...

通常header('Location:...'會自動將標題狀態更改為301或302進行重定向。可能會覆蓋您的設置。

解決了。

如PHP手冊所述:

“第二個特殊情況是“ Location:”標頭。它不僅將此標頭發送回瀏覽器,而且還向瀏覽器返回REDIRECT(302)狀態碼,除非已經輸入201或3xx狀態碼。組。”

當我設置204代碼時,它總是被Location標頭覆蓋為302。

最終解決的是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM