每次在我们的网站上抛出PHP错误时如何接收电子邮件

时间:2013-06-26 15:11:42

标签: php error-handling custom-error-handling

我意识到这可能是一个荒谬的问题,但有没有人知道如何设置我们的网站,以便每次在我们的网站上抛出PHP错误时向我们的管理员发送电子邮件?

3 个答案:

答案 0 :(得分:2)

使用错误处理程序。例如,来自:http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/

// Our custom error handler  
function nettuts_error_handler($number, $message, $file, $line, $vars)  

{  
    $email = " 
        <p>An error ($number) occurred on line  
        <strong>$line</strong> and in the <strong>file: $file.</strong>  
        <p> $message </p>";  

    $email .= "<pre>" . print_r($vars, 1) . "</pre>";  

    $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";  

    // Email the error to someone...  
    error_log($email, 1, 'you@youremail.com', $headers);  

    // Make sure that you decide how to respond to errors (on the user's side)  
    // Either echo an error message, or kill the entire project. Up to you...  
    // The code below ensures that we only "die" if the error was more than  
    // just a NOTICE.   
    if ( ($number !== E_NOTICE) && ($number < 2048) ) {  
        die("There was an error. Please try again later.");  
    }  
}  

// We should use our custom function to handle errors.  
set_error_handler('nettuts_error_handler'); 

答案 1 :(得分:1)

理论上,当你知道某些东西可能会破坏时,你应该使用try / catch构造,就像这样并添加一个简单的mail()命令[但设置mail()是另一个大话题,但让我们跳过这个详细]。

try { 
  // your actions that may fail
} catch (Exception $e) { 
  // the catch block happens only when your above stuff fails
  // when exactly things fail can be read here
  // http://php.net/manual/en/language.exceptions.php
  // getMessage() really get the human-readable error content  
  $message = $e->getMessage();       
  mail('caffeinated@example.com', 'My Subject', $message);
} 

答案 2 :(得分:0)

我想这很大程度上取决于你希望它有多复杂,但https://github.com/Seldaek/monolog应该能够做你想做的事。

但可能太过分了。