I'm trying to get Apache to redirect to a friendly static page on fatal PHP errors, something I thought would be quite easy to do...

I have a .htaccess file which has the folllowing:

ErrorDocument 404 /404.php
ErrorDocument 500 /500.php

Within each 404.php & 500.php file I just echo some text, e.g. "hello 404"

Testing the 404 I get the desired result. However, when testing the 500 error I just get a blank page.

I have a script called cause500.php which basically has:

ini_set('display_errors', 0);
myFunctionThatDoesntExist();

I can see that a response code of 500 is being returned (using Live HTTP headers), although Apache isn't handling it via the .htaccess file??!!

I'm using WAMPP, but I also test the same setup on a shared linux host and get the same thing happening.

Any help on this will be greatly appreciated.

Dave

    I'm not sure, but I suspect that it's because the error code header is being generated and sent by php after apache has passed it.

      OK, so my next question...

      How do you guys manage fatal errors gracefully?

        well, I try not to incur any, to start with 🙂 but yeah, noone's perfect, so failing that, it's just basically better error handling. Check out trigger_error() (to replace die()) and set_error_handler() for overall handling
        using them will make your code a lot more graceful than default.

        You should be able to use set_error_handler to create a handler that will header redirect to your custom 404 page as one quick solution.
        If you use standardised output buffering throughout your site (ob_start(), etc) then you can also use it to clear out the buffer and replace the 404/500/whatever page directly to them without any redirect.

          Thanks for your suggestions CoderDan. I had looked into the set_error_handler, which I will use, Although it is the Fatal errors I am more concerned about.

          The output buffering I will look into. I'm using smarty at the moment, so will need to look into how smarty is utilising it.

          I am surprised that PHP, being that it's been around for a while, doesn't handle fatal errors in a better way?!

          Dave

            Write a Reply...