ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

How to handle those pesky errors in PHP

(Page 2 out of 4)

Handling errors

Let's create a simple script which will throw various errors:


// Throws a notice
$a = $b;

// Throws a warning:
$f = fopen('bla');

// Throws a user notice:
trigger_error ('Something went wrong!'E_USER_NOTICE);

// Throws a user warning:
trigger_error ('Something went REALLY wrong!', E_USER_WARNING);

// Throws a user error:
trigger_error ('It\'s completely broken!', E_USER_ERROR);
?>

The above code throws various errors, and it also demonstrates use of the trigger_error() function which can be used to throw your own errors. More on this later in the article.

If you run the above code, you will get several standard ugly PHP errors, and this is something you definitely don't want to see on a live website. To handle these errors, you must set your own error handler, with the set_error_handler() function. The following code demonstrates a really simple error handler:

function handle_errors($errlevel, $errstr, $errfile='', $errline='', $errcontext='') {
        echo htmlentities($errstr) . "";
}

set_error_handler('handle_errors');

// Throws a notice
$a = $b;

// Throws a warning:
$f = fopen('bla');

// Throws a user notice:
trigger_error ('Something went wrong!'E_USER_NOTICE);

// Throws a user warning:
trigger_error ('Something went REALLY wrong!', E_USER_WARNING);

// Throws a user error:
trigger_error ('It\'s completely broken!', E_USER_ERROR);

?>

(View Live Demo)

As you can see in the above code, the error handler function has five arguments, with the last three being optional. The first argument defines the error level, which can be used to differentiate between different types of errors. The second argument is a description of the error, usually something like "Undefined variable: b" or "fopen() expects at least 2 parameters, 1 given". The third argument gives the filename in which the argument happened, and the fourth argument is used to get the line on which the error happened. The fifth argument, errcontext, gives an array of every variable that existed when the error occurred. You probably won't use that last argument much, but it could still be useful.

In the above example the error handler is still pretty useless, because it treats all the errors the same, even though an E_NOTICE is far less serious as an E_WARNING, but it's very easy to handle errors differently. The below example demonstrates this:

function handle_errors($errlevel, $errstr, $errfile='', $errline='', $errcontext='') {
        $errstr = htmlentities($errstr);

 switch ($errlevel) {
  case E_USER_ERROR:
   echo "My ERROR [$errlevel] $errstr\n";
   echo "  Fatal error in line $errline of file $errfile";
   echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
   echo "Aborting...\n";
   exit(1);
   break;
  case E_USER_WARNING:
  case E_WARNING:
   echo "My WARNING [$errlevel] $errstr\n";
   break;
  case E_USER_NOTICE:
  case E_NOTICE:
   echo "My NOTICE [$errlevel] $errstr\n";
   break;
  default:
   echo "Unkown error type: [$errlevel] $errstr\n";
   break;
  }
}

set_error_handler('handle_errors');

// Throws a notice
$a = $b;

// Throws a warning:
$f = fopen('bla');

// Throws a user notice:
trigger_error ('Something went wrong!'E_USER_NOTICE);

// Throws a user warning:
trigger_error ('Something went REALLY wrong!', E_USER_WARNING);

// Throws a user error:
trigger_error ('It\'s completely broken!', E_USER_ERROR);

?>

(View Live Demo)

The above example is able to handle each error level differently, and actually stops when an E_USER_ERROR is thrown. One thing you might notice in the above example is that it doesn't catch the E_ERROR level, only the E_USER_ERROR level. This is because it isn't possible to handle E_ERROR errors, or E_PARSE errors. But these fatal errors are unlikely to slip by your testing phase anyway.

Even though we're now using our own error handler, it's still pretty pointless, since we're still printing out the errors. The next step is to silently log the error, and only return something to the visitor when it's really serious. The below example does just that:

// Location of the error log file
define ('logfile', dirname(__FILE__) . '/logfile.txt');

function handle_errors($errlevel, $errstr, $errfile='', $errline='', $errcontext='') {
  $errstr = htmlentities($errstr);
  $error = '[' . date('d/m/Y H:i:s') . '] ';

 switch ($errlevel) {
  case E_USER_ERROR:
   $error .= "ERROR: ";

   echo 'Sorry, something unexpected happen, and it has been logged for further investigation. Please go back where you came from. Thank you for your understanding.';
   $die = true;
   break;
  case E_USER_WARNING:
  case E_WARNING:
   $error .= "WARNING: ";
   break;
  case E_USER_NOTICE:
  case E_NOTICE:
   $error .= "NOTICE: ";
   break;
  default:
   $error .= "UNKNOWN: ";
   break;
  }

  $error .= " $errstr in line $errline of file $errfile\n";

  // Log error
  $f = fopen(logfile, 'a');
  fwrite($f, $error);
  fclose($f);

  // Error -> stop script execution?
  if (isset($die) AND $die == true) {
          die();
  }
}

echo

set_error_handler('handle_errors');

// Throws a notice
$a = $b;

// Throws a warning:
$f = fopen('bla');

// Throws a user notice:
trigger_error ('Something went wrong!'E_USER_NOTICE);

// Throws a user warning:
trigger_error ('Something went REALLY wrong!', E_USER_WARNING);

// Throws a user error:
trigger_error ('It\'s completely broken!', E_USER_ERROR);

?>

(View Live Demo)

If you run the above code, the only thing that will be printed on the screen is the apology message and nothing more. Meanwhile, all the errors are being logged to the log file (defined at the top of the script), which you will have to check every 2 days or so.

That's it for error handling; let's move on to a PHP5 feature, called exceptions. If you don't have PHP5, or simply aren't interested, you can skip the next section.

« Previous: Introduction
Next: Handling Exceptions »



2 Responses to “How to handle those pesky errors in PHP”

  1. Gio Says:

    help

    can anyone teach me how to disable the refresh button because that is the cause of my errors

    hehhehehe
    thanks Master Programmers

  2. Kevin Says:

    Hi I would like to use your error code but i am having problems with defining the directory the line from the tutorial is: define (’logfile’, dirname(__FILE__) . ‘/logfile.txt’);

    I have changed this to: define (’logfile’, C:/log/logfile.txt(__FILE__) . ‘/logfile.txt’);

    It throws up a parse error, I am a newbie so any help would be appreciated.

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction
  2. Handling Errors
  3. Handling Exceptions
  4. Your Own Errors
Bookmark Article
Download Article
PDF
Download this article as a PDF file