PHP Error Handling

This is one of a (hopefully) continuing series of posts on programming, mostly PHP/MySQL and a bit of JavaScript. It’s mostly for my own use – since this is not a widely-read blog. But it may be useful for anyone that stumbles into this place.

This short post is about error handling in PHP. You’ll find lots of other info on error handling, how to do it, what it is, etc. But here’s the code that I use. It’s simple, and will catch production-type errors, where you don’t want people to see the error on your nice web site.

I’m not going to explain every line of the code, you can ask the googles if you need help on anything. But this works for me. If there is a severe error, one that would cause cryptic error message on the web site, this will catch the error and redirect the user back to your main page. It will also email error information to you. It’s very simplistic, but it will get the job done. Add information unique to your site as you need.

Simple Error Handling
  1. // simple error trapping. Change the email address as needed for your site.
  2. // Copyright 2017 by Rick Hellewell and ( LLC) and All Rights Reserved.</code>
  3. // Shared via CCO license.
  4. set_error_handler("myErrorHandler");
  5. function myErrorHandler($errno, $errstr, $errfile, $errline) {
  6. switch ($errno) {
  7. case E_NOTICE :
  8. case E_USER_NOTICE :
  9. $errors = "Notice" ;
  10. return ;
  11. break ;
  12. case E_WARNING :
  13. case E_USER_WARNING :
  14. $errors = "Warning" ;
  15. break ;
  16. case E_ERROR :
  17. case E_USER_ERROR :
  18. $errors = "Fatal Error" ;
  19. break ;
  20. default :
  21. $errors = "Unknown" ;
  22. break ;
  23. }
  24. $xmsg = sprintf("PHP %s: %s in %s on line %d", $errors, $errstr, $errfile, $errline);
  25. xerror_log( $xmsg) ;
  26. mail(', 'Web Site Program Error', $xmsg);
  27. header("Location: index.php") ;
  28. die() ;
  29. return true ;
  30. }

And that’s it. Add it to your ‘includes’ page (the code included on all parts of your site), after setting your email address, and changing the Subject in the mail() command.

Leave a Reply

Name and email are required. Your email address will not be published.