Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching all errors and redirecting to page with php

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.

like image 394
mrpatg Avatar asked Nov 22 '09 11:11

mrpatg


3 Answers

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');
...
?>
like image 76
karim79 Avatar answered Nov 03 '22 01:11

karim79


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.

like image 39
TheGrandWazoo Avatar answered Nov 03 '22 01:11

TheGrandWazoo


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)

like image 41
user187291 Avatar answered Nov 02 '22 23:11

user187291