I have a web service site that is restful enabled, so other websites/ajax script can make a call to the site to get/set data. However, whenever the web service site somehow returns a PHP fatal error, the HTTP status that is returned is 200 instead of 500. Is there a way to fix it so that whenever a fatal error occurs, returns 500 instead of 200? Or, if it is not possible, how can I change my client to recognize the fatal error returned by the webservice?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
PHP does send a HTTP 500 on a Fatal error.
Let me cite a comment in this PHP bug-report (a xdebug bug prevents this behavior):
You can catch fatal errors with a shutdown function and error_get_last:
I would think that you'd want to catch and fix all Fatal errors before deploying the application, since many of them are code errors, missing includes, non-existent objects, which are all development errors. Even out-of-memory errors can be minimized against with coding techniques that are memory frugal (one of the biggest wins is using unbuffered queries and processing the data and emitting output as the resultset is returned, instead of throwing around huge arrays).
I developed a way to catch all error types in PHP (almost all)! I have no sure about E_CORE_ERROR ( I think it will not work for that error)! But, for other fatal errors (E_ERROR, E_PARSE, E_COMPILE...) works fine using only one error handler function! There's my solution:
Put this following code on your main file (index.php):
I hope this helps many people!
One possible way would be to set the default response to 500, if everything executes successfully set the response to 200:
Create a custom error handler (
set_error_handler
) and callheader("HTTP/1.0 500 Service not available");
.Edit:
Per the first comment to my answer, you cannot trap true fatal errors. However, PHP will default to setting a 500 error code on fatal errors if output buffering is disabled and errors are not displayed to the screen.
The above code will return a 500 error code if nothing has been sent to the screen.
So if you want this kind of error to set the proper code, do your own buffering: