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.
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.
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.
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?
On the php page for set_error_handler() you can find a comment by smp at ncoastsoft dot com posted on 08-Sep-2003 10:28 which exlpains how to even catch fatal errors (which you can normally not catch with a custom error handler. I changed the code for you needs:
This shold catch the fatal error of the non existing function. It than returns a 500 and stops the execution of the rest of the script.