PHP: How to send HTTP response code?

后端 未结 9 1854
无人共我
无人共我 2020-11-22 06:05

I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.

How can I do this in PHP?

相关标签:
9条回答
  • 2020-11-22 06:07

    If you are here because of Wordpress giving 404's when loading the environment, this should fix the problem:

    define('WP_USE_THEMES', false);
    require('../wp-blog-header.php');
    status_header( 200 );
    //$wp_query->is_404=false; // if necessary
    

    The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:

    define('WP_USE_THEMES', false);
    require('../wp-blog-header.php');
    header("HTTP/1.1 200 OK");
    header("Status: 200 All rosy");
    
    0 讨论(0)
  • 2020-11-22 06:10

    With the header function. There is an example in the section on the first parameter it takes.

    0 讨论(0)
  • 2020-11-22 06:12

    I just found this question and thought it needs a more comprehensive answer:

    As of PHP 5.4 there are three methods to accomplish this:

    Assembling the response code on your own (PHP >= 4.0)

    The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

    header("HTTP/1.1 200 OK");
    

    However, this requires special treatment for (Fast)CGI PHP:

    $sapi_type = php_sapi_name();
    if (substr($sapi_type, 0, 3) == 'cgi')
        header("Status: 404 Not Found");
    else
        header("HTTP/1.1 404 Not Found");
    

    Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

    Note: php_sapi_name() requires PHP 4.0.1

    3rd argument to header function (PHP >= 4.3)

    There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

    Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

    header(':', true, 404);
    header('X-PHP-Response-Code: 404', true, 404);
    

    I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

    http_response_code function (PHP >= 5.4)

    The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

    http_response_code(404);
    

    That's all.

    Compatibility

    Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...

    // For 4.3.0 <= PHP <= 5.4.0
    if (!function_exists('http_response_code'))
    {
        function http_response_code($newcode = NULL)
        {
            static $code = 200;
            if($newcode !== NULL)
            {
                header('X-PHP-Response-Code: '.$newcode, true, $newcode);
                if(!headers_sent())
                    $code = $newcode;
            }       
            return $code;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:13

    If your version of PHP does not include this function:

    <?php
    
    function http_response_code($code = NULL) {
            if ($code !== NULL) {
                switch ($code) {
                    case 100: $text = 'Continue';
                        break;
                    case 101: $text = 'Switching Protocols';
                        break;
                    case 200: $text = 'OK';
                        break;
                    case 201: $text = 'Created';
                        break;
                    case 202: $text = 'Accepted';
                        break;
                    case 203: $text = 'Non-Authoritative Information';
                        break;
                    case 204: $text = 'No Content';
                        break;
                    case 205: $text = 'Reset Content';
                        break;
                    case 206: $text = 'Partial Content';
                        break;
                    case 300: $text = 'Multiple Choices';
                        break;
                    case 301: $text = 'Moved Permanently';
                        break;
                    case 302: $text = 'Moved Temporarily';
                        break;
                    case 303: $text = 'See Other';
                        break;
                    case 304: $text = 'Not Modified';
                        break;
                    case 305: $text = 'Use Proxy';
                        break;
                    case 400: $text = 'Bad Request';
                        break;
                    case 401: $text = 'Unauthorized';
                        break;
                    case 402: $text = 'Payment Required';
                        break;
                    case 403: $text = 'Forbidden';
                        break;
                    case 404: $text = 'Not Found';
                        break;
                    case 405: $text = 'Method Not Allowed';
                        break;
                    case 406: $text = 'Not Acceptable';
                        break;
                    case 407: $text = 'Proxy Authentication Required';
                        break;
                    case 408: $text = 'Request Time-out';
                        break;
                    case 409: $text = 'Conflict';
                        break;
                    case 410: $text = 'Gone';
                        break;
                    case 411: $text = 'Length Required';
                        break;
                    case 412: $text = 'Precondition Failed';
                        break;
                    case 413: $text = 'Request Entity Too Large';
                        break;
                    case 414: $text = 'Request-URI Too Large';
                        break;
                    case 415: $text = 'Unsupported Media Type';
                        break;
                    case 500: $text = 'Internal Server Error';
                        break;
                    case 501: $text = 'Not Implemented';
                        break;
                    case 502: $text = 'Bad Gateway';
                        break;
                    case 503: $text = 'Service Unavailable';
                        break;
                    case 504: $text = 'Gateway Time-out';
                        break;
                    case 505: $text = 'HTTP Version not supported';
                        break;
                    default:
                        exit('Unknown http status code "' . htmlentities($code) . '"');
                        break;
                }
                $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
                header($protocol . ' ' . $code . ' ' . $text);
                $GLOBALS['http_response_code'] = $code;
            } else {
                $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
            }
            return $code;
        }
    
    0 讨论(0)
  • 2020-11-22 06:16

    since PHP 5.4 you can use http_response_code() for get and set header status code.

    here an example:

    <?php
    
    // Get the current response code and set a new one
    var_dump(http_response_code(404));
    
    // Get the new response code
    var_dump(http_response_code());
    ?>
    

    here is the document of this function in php.net:

    http_response_code

    0 讨论(0)
  • 2020-11-22 06:23
    header("HTTP/1.1 200 OK");
    http_response_code(201);
    header("Status: 200 All rosy");
    

    http_response_code(200); not work because test alert 404 https://developers.google.com/speed/pagespeed/insights/

    0 讨论(0)
提交回复
热议问题