Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an HTTP 500 code on any error, no matter what

Tags:

http

php

response

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, and403(Forbidden) or500` 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 500s, 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?

like image 218
Jake Avatar asked Jun 16 '10 11:06

Jake


People also ask

What results in an HTTP 500 error?

The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request. This error is usually returned by the server when no other error code is suitable.

Which error log would you check first when you encounter an HTTP 500 error?

If there is an internal error, the first step is to view the log files. For Linux servers, the collection of error messages should be found at /var/log/httpd/error_log. It makes sense to reload the website to reproduce the HTTP error 500 code and observe how the log file is being created.


2 Answers

Simply send the status code as a response header():

header('HTTP/1.1 500 Internal Server Error'); 

Remember that when sending this there must not be any output before it. That means no echo calls and no HTML or whitespace.

like image 179
BoltClock Avatar answered Sep 20 '22 13:09

BoltClock


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.

like image 34
Jake Avatar answered Sep 21 '22 13:09

Jake