Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get php to return 500 upon encountering a fatal exception?

PHP fatal errors come back as status code 200 to the HTTP client. How can I make it return a status code 500 (Internal server error)?

like image 574
Mike Avatar asked Oct 12 '09 17:10

Mike


People also ask

Is 500 a fatal error?

The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.


2 Answers

header("HTTP/1.1 500 Internal Server Error"); 
like image 112
Chris Jester-Young Avatar answered Sep 24 '22 00:09

Chris Jester-Young


This is exactly the problem I had yesterday and I found solution as follows:

1) first of all, you need to catch PHP fatal errors, which is error type E_ERROR. when this error occurs, script will be stored the error and terminate execution. you can get the stored error by calling function error_get_last().

2) before script terminated, a callback function register_shutdown_function() will always be called. so you need to register a error handler by this function to do what you want, in this case, return header 500 and a customized internal error page (optional).

function my_error_handler() {   $last_error = error_get_last();   if ($last_error && $last_error['type']==E_ERROR)       {         header("HTTP/1.1 500 Internal Server Error");         echo '...';//html for 500 page       } } register_shutdown_function('my_error_handler'); 

Note: if you want to catch custom error type, which start with E_USER*, you can use function set_error_handler() to register error handler and trigger error by function trigger_error, however, this error handler can not handle E_ERROR error type. see explanation on php.net about error handler

like image 31
fuyi Avatar answered Sep 20 '22 00:09

fuyi