PHP Error Handling

I recently became extremely frustrated with certain host and the lack of features they offered on the Windows plan. I prefer Linux or FreeBSD but I couldn’t change the website server’s operating system. One feature I needed was a error log for PHP. After doing some research I decided to use my own error handle and write my own log file. Here is the function I added to my configuration script:

function my_errorhandler($errno, $errstr, $errfile, $errline) {
   /* Determine Error Type from the $errorno and defined constants */
   switch ($errno) {
   case E_WARNING:
      $errtype = "E_WARNING";
      break;

   case E_NOTICE:
      $errtype = "E_NOTICE";
      break;

   case E_USER_ERROR:
      $errtype = "E_USER_ERROR";
      break;

   case E_USER_WARNING:
      $errtype = "E_USER_WARNING";
      break;

   case E_USER_NOTICE:
      $errtype = "E_USER_NOTICE";
      break;

   case E_STRICT:
      $errtype = "E_STRICT";
      break;

   default:
      $errtype = "UNKNOWN ERRNO[".$errno."]";
      break;
   }
   /* Error Message with Date, Page URL, Error Type, Line Number and Message */
   $errormsg = date('Y-m-d H:i:s ').$_SERVER["REQUEST_URI"]." - "."<b>".$errtype.":</b> ".$errstr." in ".$errfile." on line ".$errline."n";

   /* Log Error message, must let error_log create the file. Change Path as needed. Make sure host is configured to not serve log files */
   error_log($errormsg,3,$_SERVER["APPL_PHYSICAL_PATH"].'myphplogerror_log.log');

   /* Don't execute PHP internal error handler */
   return true;
}

I think the comments make it self explanatory. NOTE: You need to give both read and write permissions on the directory were the log file is wrote.  Now at the beginning of my configuration script, that is included on all pages, I can add:

set_error_handler("my_errorhandler");
date_default_timezone_set('America/New_York');

Now all the errors and warnings get logged. Now I can check if other users are having any issues with the website and resolve them. You could even add a email option for for certain error types; in the switch just set $email true and add this line after error_log:

if($email) error_log($errormsg,1,"admin@example.com","From: admin@example.comn");

To the administrator portion of the website I added a page for viewing the log. I have also been able to add some tracking information so I know which of the users is having issues.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *