Is there a way to configure PHP so that fatal errors are returned with response code 500 instead of 200?
----EXAMPLE----

<?php 

echo 'before bad code';

$abc = getAbc();
$abc->getSomeValue();

echo 'after bad code';

function getAbc(){
  return null;
}

----OUTPUT----
before bad code

---RESPONSE CODE----
HTTP/1.x 200 OK

---ERROR LOG----
PHP Fatal error: Call to a member function getSomeValue() on a non-object in /xxx/xxx/xxx/xxx/test.php on line 6

    You would have to buffer the output using ob_start(), this is not a recommended solution, as it means the whole page needs to be buffered, causing possible server issues.

    On a production server, you shouldn't be outputting the errors but logging them.

      There's no need for ob_start() (nor do I immediately see how that would be applicable); just register your own error handler ([man]set_error_handler/man) that not only outputs an error message but also uses the [man]header/man function to modify the response code.

        I don't think set_error_handler will work because many times when Fatal occurs, headers are already sent.

          mchimirev;10895378 wrote:

          I don't think set_error_handler will work because many times when Fatal occurs, headers are already sent.

          In that case, perhaps you would need to enable output buffering in combination with a custom error handler.

          In other words, you're probably going to consume more server resources just to add this functionality. Do you really need to change the HTTP status code if an error occurs?

            Changing the status code when an error occurs would be ideal. This way we can do things like a) check our site with a link checker, which reports 500s and 404s b) display a custom error page

              a) Why would you want to use a link checker to check for PHP errors? Why not open your PHP error log; if it's empty, no errors. If not, you have errors (and more; you have information about where the error is and the nature of the error itself).

              b) I still maintain that good coding / a custom error handler can handle errors gracefully, including a custom error page.

                Write a Reply...