views:

683

answers:

5

PHP fatals come back as 200, how can i make it return a 500

+2  A: 
header("HTTP/1.1 500 Internal Server Error");
Chris Jester-Young
+4  A: 

You can use php error handling

http://www.w3schools.com/php/php%5Ferror.asp

Xinus
+1  A: 

You would have to catch the thrown error using try/catch and then use that catch block to send a header() with the 500 error.

try {
    ...badcode...
    throw new Exception('error');

} catch (Exception $e) {

    header("Status: 500 Server Error");
    var_dump($e->getMessage());
}

If the fatal exception is not surrounded by try {} catch blocks then you must register a global handler and use register_shutdown_function() to check for an error at script end.

Xeoncross
That will catch exceptions, but it won't catch PHP Fatal errors, which are handled outside the scope of exceptions.
Alan Storm
Fatal/syntax errors can't be captured as far as i know, neither by errorhandling nor by exceptionhandling
ChrisR
@ChrisRamakers: I've read something about using output handlers to catch PHP fatal errors.
Alix Axel
depends, syntax errors are triggered at compile time thus the logic that handles output or exception handling simple never occurs because the page is simply not executed because i could not be compiled. But again, i'm not an absolute expert so i might not be aware of the output handlers you are talking about
ChrisR
Actually, you use `register_shutdown_function()` to catch E_FATAL errors.
Xeoncross
A: 

It is not possible to handle PHP E_ERROR in any way according to the PHP documentation: http://www.php.net/manual/en/function.set-error-handler.php

Nor is is possible to handle "E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" according to that link.

You CAN provide a handler for the other error, warning, and notices including E_USER_ERROR, but that's really not as useful as it sounds since this error only gets thrown intentionally by the programmer with trigger_error().

And of course you can catch any Exception (even the ones thrown by the native PHP functions).

I agree that this is a problem. Servers should NOT return 200 OK when application code crashes and burns.

Jonathan Hanson
A: 

I have used "set_exception_handler" to handle uncaught exceptions.

function handleException($ex) {
      error_log("Uncaught exception class=" . get_class($ex) . " message=" . $ex->getMessage() . " line=" . $ex->getLine());
      ob_end_clean(); # try to purge content sent so far
      header('HTTP/1.1 500 Internal Server Error');
      echo 'Internal error';
    }

set_exception_handler('handleException');