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 中发送状态代码,而不维护状态名称数组?
基础教程推荐
- Web 服务器如何处理请求? 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- php中的foreach复选框POST 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
