catching all errors and redirecting to page with p

2019-04-05 09:10发布

问题:

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.

回答1:

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.



回答2:

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');
...
?>


回答3:

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)