How to send a status code in PHP, without maintaining an array of status names?(如何在 PHP 中发送状态代码,而不维护状态名称数组?)
问题描述
我想要做的就是从 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');
这篇关于如何在 PHP 中发送状态代码,而不维护状态名称数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中发送状态代码,而不维护状态名称数组?


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01