Blog Post RSS ?

Blogs » PHP » User Errors in PHP
 

User Errors in PHP

by Thomas Rutter

The trigger_error function in PHP allows you to generate a PHP error on demand. If you haven’t used this function before, you may be asking, “Why would you want to generate an error?” Well, it is a much more flexible solution than using exit or die to display your error message.

Often, while editing legacy PHP code, I come across error handling for situations such as database connect errors:

$dbconn = mysql_pconnect($myhost, $myuser, $mypass); if (!$dbconn) exit(mysql_error());

Or, the lazier version:

$dbconn = mysql_pconnect($myhost, $myuser, $mypass) or die('yikes');

The problem with this approach, which uses exit (or its alias, die), is that it doesn’t give PHP a chance to use its own error handling method. It will always terminate the script and print its little error message to the screen.

So, for example, you won’t be able to turn the error messages on or off with the php.ini directive display_errors, you won’t be able to log the error to your error log with log_errors, and you won’t be able to use your own custom error handler function.

Why is this a bad idea? Well, on a live server it is sometimes a security risk (and an embarrassment) if your error messages are displayed to the public. From the PHP manual:

Note: You’re strongly advised to use error logging in place of error displaying on production web sites.

However, when you use trigger_error, the error will be processed according to PHP’s error handling routines.

$dbconn = mysql_pconnect($myhost, $myuser, $mypass); if (!$dbconn) trigger_error('Database connection failure', E_USER_ERROR);

Here, I used E_USER_ERROR to indicate a fatal run-time error. Other error level constants can be used to trigger warnings or notices.

On a test server, you can turn display_errors on and the error, complete with line number and source file, will be displayed on screen. On a live server, you can turn it off, and instead enable log_errors and the error message, complete with line number and source file, will be output to your error log.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. 11 Expert Tips For Enhancing The User Login Process It seems simple, but a lot can go wrong when...
  2. Introducing php-tracer-weaver php-tracer-weaver is a tool for automatically generating docblock comments, with...
  3. Interactive CLI password prompt in PHP Just a quick tip, since I spent a good hour...
  4. How to Install PHP 5.3 on Windows PHP 5.3 is the most significant update since version 5.0....
  5. Are PHP Namespaces Really So Bad? Namespaces have caused a divide amongst developers who either love...

This post has 13 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...