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?
Create a custom error handler (set_error_handler
) and call header("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.
<?php
$x = y();
?>
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:
<?php
$buffer = 'blah';
$x = y(); // will trigger 500 error
echo $buffer;
?>
One possible way (dodgy, untested) would be to set the default response to 500, if everything executes successfully set the response to 200
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).
not sure if this is helpful, but posting anyway http://php.net/manual/en/function.register-shutdown-function.php