无论如何,如何在任何错误上返回HTTP 500代码 [英] How to return an HTTP 500 code on any error, no matter what
问题描述
我正在用PHP编写一个身份验证脚本,被称为API,只有在它批准请求的情况下才需要返回200 ,并且
403 (禁止)或
500`否则。
I'm writing an authentication script in PHP, to be called as an API, that needs to return 200only in the case that it approves the request, and
403(Forbidden) or
500` otherwise.
我遇到的问题是php返回 200
如果出现错误,请将错误输出为html。我怎样才能确保php将返回HTTP 500
代码,除非我显式返回HTTP 200
或HTTP 403
我自己?换句话说,我想将任何和所有警告或错误条件转换为 500
s,没有异常,因此默认情况是拒绝身份验证请求,异常是使用 200
代码批准它。
The problem I'm running into is that php returns 200
in the case of error conditions, outputting the error as html instead. How can I make absolutely sure that php will return an HTTP 500
code unless I explicitly return the HTTP 200
or HTTP 403
myself? In other words, I want to turn any and all warning or error conditions into 500
s, no exceptions, so that the default case is rejecting the authentication request, and the exception is approving it with a 200
code.
我已经摆弄 set_error_handler()
和 error_reporting()
,但到目前为止还没有运气。例如,如果代码在发送HTTP响应代码之前输出了某些内容,PHP自然会报告您在输出任何内容后无法修改标头信息。但是,这被PHP报告为 200
响应代码,其中html解释了该问题。我甚至需要将这种东西变成 500
代码。
I've fiddled with set_error_handler()
and error_reporting()
, but so far no luck. For example, if the code outputs something before I send the HTTP response code, PHP naturally reports that you can't modify header information after outputting anything. However, this is reported by PHP as a 200
response code with html explaining the problem. I need even this kind of thing to be turned into a 500
code.
这可能在PHP中有用吗?或者我是否需要在更高级别执行此操作,例如以某种方式使用 mod_rewrite
?如果是这样,任何想法我怎么设置它?
Is this possible in PHP? Or do I need to do this at a higher level like using mod_rewrite
somehow? If that's the case, any idea how I'd set that up?
推荐答案
我检查了用于header()的PHP文档,它比我做的更简单 - 如果第二个参数为true ,它将取代类似的标题。默认值为true。所以正确的行为是标题('HTTP / 1.1 403 Forbidden');
,然后执行身份验证逻辑,然后如果它进行身份验证,请执行标头( 'HTTP / 1.1 200 OK')
。它将取代403响应,并保证403是默认值。
I checked the PHP docs for header(), and it's simpler than I was making it - if the second parameter is true, it will replace a similar header. the default is true. So the correct behavior is header ('HTTP/1.1 403 Forbidden');
, then do the authentication logic, then if it authenticates, do header ('HTTP/1.1 200 OK')
. It will replace the 403 response, and will guarantee that 403 is the default.
这篇关于无论如何,如何在任何错误上返回HTTP 500代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!