如何在PHP中发送状态码,而不需要维护一组状态名称? [英] How to send a status code in PHP, without maintaining an array of status names?

查看:136
本文介绍了如何在PHP中发送状态码,而不需要维护一组状态名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是从PHP发送一个 404 状态码 - 但是采用通用的方式。无论是 Router :: statusCode(404)还是 Router :: statusCode(403)都可以工作,有效的HTTP状态码。



我知道,您可以指定一个状态码作为第三个参数 。可悲的是,这只有在指定字符串时才有效。因此,调用 header('',false,404)不会 工作。此外,我知道,可以通过标头调用发送状态码,状态栏为:标头('HTTP / 1.1 404 Not Found')



但要做到这一点,我必须保留一组理由短语( Not Found )为所有状态代码( 404 )。我不喜欢这个想法,因为它以某种方式重复了PHP自己已经做了什么(对于第三个参数)。



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

解决方案

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



只需执行 http_response_code(404)



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



如果您想设置原因词组,请尝试:

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


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.

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.

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')

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).

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

解决方案

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

Simply do http_response_code(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中发送状态码,而不需要维护一组状态名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆