通过电子邮件php发送错误消息

时间:2018-08-10 13:44:19

标签: php error-handling

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

// Allocates a hidden console window for this process. This console can be
// inherited by child console processes, preventing them from creating a
// visible console. Returns false if the attempt fails.
bool AllocHiddenConsole()
{
  TCHAR command[] = _T("cmd.exe");
  STARTUPINFO startupInfo{};
  PROCESS_INFORMATION processInfo{};
  startupInfo.cb = sizeof(startupInfo);
  startupInfo.dwFlags = STARTF_USESHOWWINDOW;
  startupInfo.wShowWindow = SW_HIDE;

  if (!CreateProcess(NULL, command, NULL, NULL, FALSE,
    CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo))
  {
    return false;
  }

  bool attached = false;
  for (int i = 0; i < 1000; i++)
  {
    if (AttachConsole(processInfo.dwProcessId))
    {
      attached = true;
      break;
    }
    Sleep(10);
  }

  TerminateProcess(processInfo.hProcess, 0);
  CloseHandle(processInfo.hProcess);
  CloseHandle(processInfo.hThread);

  return attached;
}

这是可行的,但是当我为所有错误更改它时,则不行:

<?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);
}
?>

如果出现任何错误,我该怎么办? 奥地利的感谢和问候 乌韦

1 个答案:

答案 0 :(得分:0)

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

<?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