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

2022-01-11 00:00:00 header php http-status-codes

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

All I want to do, is send a 404 status code from PHP - but in a generic fashion. Both Router::statusCode(404) and Router::statusCode(403) should work, as well as any other valid HTTP status code.

我知道,您可以将状态代码指定为 header.遗憾的是,这仅在您指定 string 时才有效.因此调用 header('', false, 404) not 工作.

I do know, that you can specify a status code as third parameter to header. Sadly this only works if you specify a string. Thus calling header('', false, 404) does not work.

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

Furthermore I know, that one can send a status code via a header call with a status line: header('HTTP/1.1 404 Not Found')

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

But to do this I have to maintain an array of reason phrases (Not Found) for all status codes (404). I don't like the idea of this, as it somehow is a duplication of what PHP already does itself (for the third header parameter).

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

So, my question is: Is there any simple and clean way to send a status code in PHP?

推荐答案

在 PHP >= 5.4.0 中有一个新的函数 http_response_code

There is a new function for this in PHP >= 5.4.0 http_response_code

只需执行 http_response_code(404).

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

If you have a lower PHP version try header(' ', true, 404); (note the whitespace in the string).

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

If you want to set the reason phrase as well try:

header('HTTP/ 433 Reason Phrase As You Wish');

相关文章