views:

306

answers:

3

Is there say way to universally tell php to redirect to a certain page on any fatal errors?

Say i have a site with many different files, and i want to hide problems (while still logging them) and send the user to the same error page, no matter what the error is or what page they are on.

Lets just pretend for sake of argument that i dont want to see the errors, and the pages are being continuously edited and updated by robots who cause errors every 23rd or 51st page edit.

Im looking for something that perhaps involves the php.ini file, or htaccess, something that i can do site wide.

+5  A: 

See set_error_handler:

set_error_handler — Sets a user-defined error handler function

Rudimentary example:

<?php

function errorHandler($n, $m, $f, $l) {
    header('Location: http://example.com/error.php');
}

set_error_handler('errorHandler');
...
?>
karim79
OP still needs to include this in every file - exactly what he's trying to avoid.
stereofrog
+3  A: 

You can change the default 500 error page in Apache with the 'ErrorDocument' directive:

ErrorDocument 500 /500.html

This redirects a 500 Internal Server error to 500.html. You can also use a PHP page there and mail the referring page.

To catch the errors you can log those to an error.log file. Use the following two directives in your php.ini file:

error_log = /var/log/httpd/error_php  
log_errors = On

Don't forget to restart Apache.

TheGrandWazoo
php (running as a module at least) doesn't return status to pache, so the ErrorDocument thing won't work.
stereofrog
+4  A: 

First, change your php.ini to suppress error messages and to enable logging:

 display_errors=Off
 log_errors=On
 error_log=whatever/path

Write an error handler (unlike set_error_handler, this one also catches fatals)

register_shutdown_function('errorHandler');
function errorHandler() {
   $err = error_get_last();
   if($err)
     include "error_page.php"; // your custom error page
}

Put this code in a file and tell php to include it on every requrest (see auto_prepend_file @ http://php.net/manual/en/ini.core.php)

stereofrog
Ref: http://stackoverflow.com/questions/2171055/register-shutdown-function-registered-function-cannot-include-files-if-terminatThis code would not work if you encounter a syntax parse error. The include would bring your script to silently fail, leaving not much of any traces.If anyone has input on this, I'm all ears.
Marc Trudel