PHP:如何发送 HTTP 响应代码?

新手上路,请多包涵

我有一个 PHP 脚本需要使用 HTTP 响应代码(状态代码)做出响应,例如 HTTP 200 OK,或者一些 4XX 或 5XX 代码。

我怎样才能在 PHP 中做到这一点?

原文由 Paulo Coghi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 873
2 个回答

我刚刚发现了这个问题,并认为它需要一个更全面的答案:

PHP 5.4 开始,有三种方法可以实现这一点:

自己组装响应代码(PHP >= 4.0)

header() 函数有一个特殊的用例,可以检测 HTTP 响应行并让您用自定义响应行替换它

header("HTTP/1.1 200 OK");

但是,这需要对(快速)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");

注意: 根据 HTTP RFC原因短语 可以是任何自定义字符串(符合标准),但为了客户端兼容性,我 建议在其中放置随机字符串。

注意: php_sapi_name() 需要 PHP 4.0.1

头函数的第三个参数 (PHP >= 4.3)

使用第一个变体时显然存在一些问题。我认为最大的原因是它部分由 PHP 或 Web 服务器解析,并且文档记录不佳。

从 4.3 开始, header 函数有第三个参数,可以让您轻松地设置响应代码,但使用它需要第一个参数是非空字符串。这里有两个选项:

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

我推荐第二个。第一个 确实 适用于我测试过的所有浏览器,但一些小型浏览器或网络爬虫可能会遇到仅包含冒号的标题行的问题。头字段名称在第 2 位。变体当然没有以任何方式标准化并且可以修改,我只是选择了一个有希望的描述性名称。

http_response_code 函数 (PHP >= 5.4)

http_response_code() 函数是在 PHP 5.4 中引入的,它使事情变得容易 多了

 http_response_code(404);

就这样。

兼容性

当我需要低于 5.4 的兼容性但想要“新”功能 http_response_code 功能时,这是我编写的一个功能。我相信 PHP 4.3 的向后兼容性绰绰有余,但你永远不知道……

 // 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;
    }
}

原文由 dualed 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您的 PHP 版本不包含此功能:

 <?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;
    }

原文由 Abdo-Host 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题