【问题标题】:Send an Error Message by E-Mail php通过电子邮件发送错误消息 php
【发布时间】:2018-08-10 13:44:19
【问题描述】:

如果我的 php 应用程序出现任何错误,我想收到一封邮件。我在https://www.w3schools.com/php/php_error.asp上找到了一个例子:

<?php
    //error handler function
function customError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Webmaster has been notified";
  error_log("Error: [$errno] $errstr",1,
  "uwe.nachname@gmail.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>=1) {
  trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>

这是有效的,但是当我为所有错误更改它时:

<?php
    error_reporting(E_ALL);
ini_set('display_errors', 'Off');
//error handler function
function customError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Webmaster has been notified";
  error_log("Error: [$errno] $errstr",1,
  "uwe.nachname@gmail.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_ALL);
  echo 'now the error: ';
  echo gibtsnicht();
?>

如果出现任何错误,我该怎么做才能收到邮件? 来自奥地利的感谢和问候 乌韦

【问题讨论】:

  • 有点不相关,但我发现您的代码有一个小问题。如果 $test 为 1 与您的消息相矛盾,if ($test&gt;=1) {trigger_error("Value must be 1 or below",E_USER_WARNING);} 仍将触发

标签: php error-handling


【解决方案1】:

问题是这不是触发错误,而是异常,因此必须捕获并处理异常。

<?php
function customException($ex) {
  echo "<b>Exception:</b> ".$ex->getMessage()." Line: ".$ex->getLine() ."<br>";
  error_log("Exception: " .$ex->getMessage()." File: ".$ex->getFile()." Line: ".$ex->getLine(),1,
  "uwe.nachname@gmail.com","From: webmaster@example.com");
  echo "Webmaster has been notified";
}

set_exception_handler("customException"); 
  echo 'now the exception: <br>';
  echo gibtsnicht();
?>

查看Exception

【讨论】:

  • 非常感谢。我是一名 PHP 初学者,因为我 69 岁,所以将我的应用程序从 ASP 转移到 PHP...
  • 只有一个问题:如何发送程序名和行号?
猜你喜欢
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
相关资源
最近更新 更多