如何在PHP中发送状态代码,而不维护状态名称数组?

Nik*_*kiC 32 php header http-status-codes

我想要做的就是404从PHP 发送状态代码 - 但是以通用的方式.双方Router::statusCode(404)Router::statusCode(403)应工作,以及任何其他有效的HTTP状态代码.

我知道,您可以将状态代码指定为第三个参数header.可悲的是,这只有在你指定一个时才有用string.因此,呼吁header('', false, 404)没有工作.

此外,我知道,可以通过header状态行的呼叫发送状态代码:header('HTTP/1.1 404 Not Found')

但要做到这一点,我必须Not Found为所有状态代码(404)维护一系列原因短语().我不喜欢这个想法,因为它在某种程度上是PHP已经完成的重复(对于第三个header参数).

所以,我的问题是:有没有简单而干净的方式在PHP中发送状态代码?

hec*_*rct 76

在PHP> = 5.4.0中有一个新功能 http_response_code

简单地做http_response_code(404).

如果你有一个较低的PHP版本尝试header(' ', true, 404);(注意字符串中的空格).

如果你想设置原因短语,请尝试:

header('HTTP/ 433 Reason Phrase As You Wish');
Run Code Online (Sandbox Code Playgroud)


Mar*_*c B 26

代码的实际文本无关紧要.你可以做到

header('The goggles, they do nawtink!', true, 404);
Run Code Online (Sandbox Code Playgroud)

并且它仍然被浏览器视为404 - 这是重要的代码.

  • 您是否真的建议将其作为设置状态代码的有效且简洁的方法? (5认同)
  • 不,只要状态代码存在,只是一种表达标题文本无关紧要的愚蠢方式. (3认同)
  • +1,因为它是真的,因为这样的评论肯定会让任何未来的开发人员明白:) @ircmaxell - 嘿,这是PHP! (3认同)
  • 当然,不要说完全不同的东西,例如404的"拒绝访问",但"未找到"只是一个简单的建议默认值.如果你愿意的话,你可以把500页诗歌归结为同样的东西. (2认同)
  • @nikic:PHP将传递它,它取决于网络服务器(Apache等)扔掉它或不... (2认同)

Mik*_*e B 16

Zend Framework有一个打包的解决方案 Zend_Http_Response

Zend_Http_Response::$messages 包含:

/**
 * List of all known HTTP response codes - used by responseCodeAsText() to
 * translate numeric codes to messages.
 *
 * @var array
 */
protected static $messages = array(
    // Informational 1xx
    100 => 'Continue',
    101 => 'Switching Protocols',

    // Success 2xx
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',

    // Redirection 3xx
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',  // 1.1
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    // 306 is deprecated but reserved
    307 => 'Temporary Redirect',

    // Client Error 4xx
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',

    // Server Error 5xx
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
    509 => 'Bandwidth Limit Exceeded'
);
Run Code Online (Sandbox Code Playgroud)

即使您没有使用zend-framework,您也可以将其打破以供个人使用.