IT Community - Software Programming, Web Development and Technical Support

Error Handling in PHP

This is a discussion on Error Handling in PHP within the PHP Programming forums, part of the Web Development category; Guys, Error Handling in PHP As with any programming language, when you code in PHP, it helps immensely if you ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 08-27-2007, 09:40 AM
sivaramakrishnan sivaramakrishnan is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 74
sivaramakrishnan is on a distinguished road
Post Error Handling in PHP

Guys,

Error Handling in PHP

As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.

Introduction

Getting started with PHP is quite easy. Armed with a good PHP editor, any beginner can create a simple database-driven web application with minor hassles. Moreover, given a little more time, an average developer can pick up a good understanding of object-oriented programming and start working with classes and objects. Definitely, this sounds like a good and exciting thing -- except for when, during the development of an application, one has to write error handling code.

Let’s be honest. For novice (and not so novice) programmers, coding error handling routines is boring stuff. Even when it’s something that you can’t hide from very often, error manipulation usually is limited to writing a few “die()/exit()” statements when connecting to a database server, and some additional checking lines for handling potential errors within program execution. From a realistic point of view, the things about error handling is that if you’re developing a web application which lacks decent error checking code (due to ignorance or laziness), sooner or later your application will fail ungracefully. The result of this will be possibly the occurrence of potentially harmful errors -- particularly in the area of security -- and the display of ugly messages, making the whole program look very unprofessional.

Since error handling is something that you should introduce (at least progressively) into your applications, in this article I’ll explore some of the most common error checking methods available in PHP, in order to make web applications much more robust and reliable. The end result of this experience will be an illustrative list of hands-on examples that utilize different error handling methods, ranging in from using simple “die()” statements, to manipulating errors within an object-oriented context, by utilizing exceptions.

Having drawn the general guidelines for this tutorial, it’s time to dive into the topic and turn error handling into an instructive journey. Let’s get started.

basic error handling with the “die()” statement

The first example that implements the basics of script-level error handling is based on the popular “die()” statement. For this reason, I’ll write a simple PHP class, which reads contents from a data file. In its basic incarnation, this class looks like this:

class FileReader{
var $file;
var $fileDir='fileDir/';
function FileReader($file){
$this->file=$file;
}
function getContent(){
return file_get_contents("{$this->fileDir}{$this->file}.php");
}
}



As I mentioned earlier, the above class implements a trivial file reader. Aside from the constructor, the class exposes only one public method, “getContent()”, which reads the content from a file passed in as an argument to the constructor. As you can see, the class has been coded with no error checking lines, so any object instantiated from it will cause a non-fatal error if the “$file” parameter doesn’t point to a valid file

Regards
sivaraman,
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 09-05-2007, 09:03 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Introduction
If you're a developer, I'm sure you've experienced an error message in PHP. In fact, you should be quite familiar with the standard error message format such as this one caused by a call to the header() function after output as started:

Warning: Cannot add header information - headers already sent by (output started at /home/zend.com/proc.inc:6) in /home/zend.com/www/modify_account.php on line 41

This is a fairly typical error message -- but did you know that this error message could be changed? In fact, not only can the format of the error message be changed, new features and logic (such as sending an e-mail when an error occurs) can also be developed. Today, we'll explore custom error handling in PHP, and how you can use it to standardize and simplify error handling from within your scripts.

The problem with standard error handling

Error handling in PHP is a fairly straightforward process. PHP will simply send to the browser (or standard output if executing a script from the command line):

* an error message containing relative information to the error such as the filename of the script, the specific line in the file that caused the error,
* a (sometimes) helpful message describing the nature of the error

Unfortunately when dealing with scripts that execute through a browser, PHP pays no consideration to any HTML that may have been in the process of outputting to the browser prior to the error. Because of this, error messages cause rather unpredictable and ugly output and HTML formatting when they occur.

Furthermore, if an error message happens to occur within a HTML comment (such as while outputting JavaScript code), the error message may be hidden and it may not be apparent immediately that an error even occurred. Today I'll construct a better way to handle errors, and show you how it can be used to provide better error reporting.

Custom error handling in PHP

In order to address the problem outlined above, as well as give the developer more flexibility in error handling, PHP supports the ability to route all error messages through a custom error handling function. Furthermore, PHP provides three error types specifically to be used for errors that your script generates during its execution.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-05-2007, 09:04 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Error types in PHP

PHP internally uses eight error types to classify errors that can occur during the execution of a script. PHP also provides three extra error types that can be used by the user to produce user-defined error messages. To begin, you'll look at the eight standard error types, and then the last three custom error types and how they can be used to deal with errors generated within your scripts.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-05-2007, 09:05 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Standard error types in PHP

As stated above, PHP uses a total of eight separate error types to categorize the errors that occur during the execution of the script. Some errors require the script to stop executing, while others serve as warnings while the script still continues to execute.

In order to properly construct an error handling function in PHP, these eight types of errors and their significance must be understood. Although in total there are eight separate error types, from an error-handling perspective many of them can be handled in the same way. In fact they are really the same error type generated by different aspects of PHP. When appropriate, you will be made aware of any similar error types and how the error should be treated in relation to other error types.

E_NOTICE

The E_NOTICE error type is a non-fatal error caused when PHP encounters something during the execution of the script (such as an attempt to reference an undefined variable) that may indicate an error within the script. This error by default in PHP is not reported, because it may be generated during the normal execution of a script.

E_WARNING

The E_WARNING error type is another non-fatal error caused by problems that the script itself should have prevented (such as passing invalid data types to an internal PHP function). Although these errors will not prevent the execution of the script, they are serious enough to be displayed to the user by default and should not be ignored by the developer.

E_ERROR

The E_ERROR is the first error type that is considered a "fatal" error. E_ERROR type errors indicate a problem that PHP could not recover from and are displayed by default. Furthermore, E_ERROR type errors must terminate execution of the script when encountered.

E_PARSE

The E_PARSE is generated by the PHP parser, and generally means that a syntax error in the script was encountered. This error must be considered fatal and the script must terminate if it occurs.

E_CORE_ERROR

The E_CORE_ERROR error type is identical to the E_ERROR type of error, except the core of PHP rather than a function within PHP generates it. Because of the similarities between E_CORE_ERROR and E_ERROR, it is safe to treat both error types with the same consideration.

E_CORE_WARNING

As with E_CORE_ERROR, E_CORE_WARNING error type's counterpart is the E_WARNING error type. Again, because of this similarity between the error types it is acceptable to treat both error types with the same consideration.

E_COMPILE_ERROR

The E_COMPILE_ERROR error type is generated by the Zend Engine, and should be considered no different than the E_ERROR or E_CORE_ERROR error types.

E_COMPILE_WARNING

E_COMPILE_WARNING, as with E_COMPILE_ERROR, is generated by the Zend Engine, and has counterparts in E_WARNING and E_CORE_WARNING. It should be considered in the same way as those types.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-05-2007, 09:06 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Custom error types in PHP

Along with the eight internal errors generated by PHP, PHP also provides three custom error types that your script can generate should your script warrants triggering an error. These error types are the only ones that are to be generated by the developers themselves from within their scripts. They are:

E_USER_NOTICE

The E_USER_NOTICE error is designed to reflect the same purpose as the E_NOTICE internal PHP error. It can be used to notify the user of potential problems in the script that are not of a fatal or perhaps even consequential nature. An example of a potential E_USER_NOTICE error would be type mismatches such as treating a string as an Integer when it may not be appropriate.

E_USER_WARNING

The E_USER_WARNING error is the user-defined version of its E_WARNING internal counterpart. It is designated for errors that prevent the script from continuing the execution of the script normally. An example of this is calling a function and passing a string parameter when an array was expected. This type of serious type mismatch (a string cannot be automatically be converted to an array by PHP) prevents the proper execution of the function, but is not incorrect by syntax and therefore should trigger the E_USER_WARNING error.

E_USER_ERROR

The E_USER_ERROR error is the most serious user-defined error message defined by PHP. Like the other two user-defined error messages E_USER_ERROR mirrors the internal error E_ERROR. This error should be triggered in the event the script encounters an execution-critical error requiring the halt of further code execution. An example would be a mathematical operation that would result in the attempted division by zero.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 09-05-2007, 09:07 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Creating a custom error handler

The process of creating a custom error handling function is fairly straightforward, as we mentioned earlier many of the internal errors within PHP can be safely combined without any harm. The theory of custom error handling involves creating a specialized function defined from within a PHP script that is called every time an error in PHP occurs.

This specialized function must accept a minimum of two parameters (the error number and the error description) but can accept up to five parameters (optionally accepting the file, line number, and context of in which the error occurred). Therefore, our formal definition of an error handler function would be:

Code:
function MyErrorHandler($errno, $errstr [,$errfile,

$errline, $errcontext]) {

}
Where the last three parameters $errfile, $errline and $errcontext can be excluded. The meaning of these parameters is as follows:

$errno - The integer value representing one of the defined PHP error constants

$errstr - A string containing an error message associated with the error number

$errfile - The filename of the script that caused the error

$errline - The line number in the $errfile where the error occurred

$errcontext - An array containing all of the variables that were in use when the error occurred and their values. For instance, an error occurring inside of a function will have a $errcontext that contains only a list of variable=>value pairs for variables within that function's scope.

With this in mind, the development of the error handling function should be apparent. In order to determine the type of error we are handling, simply compare $errno to the list of known error values and the act appropriately. But before you look at an actual example of a real error handling function, you need to know the error functions internally defined by PHP.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-05-2007, 09:08 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Internal error handling functions

PHP internally provides a set of functions that allows you to not only override the internal error handling procedures of PHP, but to trigger errors in PHP in the same way that PHP does so internally. I'll briefly introduce the primary functions in the family and their use below. For formal definitions of the following functions, consult the PHP manual regarding them.

Set_error_handler()

The set_error_handler() function is used to register a function as the method of handling errors within PHP, thereby overriding the internal error handling procedures in PHP.

Restore_error_handler()

This function is used to reregister the previous error handling function as the method of handling errors in PHP. The restored error handler will be the one used prior to the last set_error_handler() function and could be the internal PHP error handler or another user-defined function.

Error_reporting()

The error_reporting() function is used to define what errors will be processed by the error handling mechanism. Note that when developing custom error handling functions, the error_reporting() function will be called in the event of any error regardless of the settings of error_reporting(). It is the developer's responsibility to use the error_reporting() function within their script to determine of the error needs to be handled or not.

Error_log()

The error_log() function should be used any time the developer desires to log an error in PHP. Through the use of the error_log() function, errors can be logged to the standard log file(s), e-mailed to specific users, or transmitted to a remote debugging location (not availble in PHP4, and only if enabled in PHP3).

Trigger_error()

The trigger_error() function is used to send a error message to the error handler. Please note that trigger_error() can only send errors that are defined in the E_USER family of constants and cannot trigger errors such as E_ERROR or E_NOTICE.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 09-05-2007, 09:10 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

The script

Now that you have a complete understanding of all of the constants and functions associated with error handling in PHP, you are ready to create your own error handling function. Our error handling function supports a number of different methods of reporting errors to the user, and can easily be configured to use all of them. We will also make use of the error_reporting() function to determine if the error should be handled at all or not.

Part 1 -- Initialize variables

The first part of the script consists of initializing the variables necessary. This includes all configuration variables and flags.
Code:
<?php

function ErrorHandler($errno, $errstr, $errfile, $errline) {

   var $error_msg = " $errstr occured in $errfile on 
   $errline at ".date("D M j G:i:s T Y");
   var $email_addr = "joe@example.com";
   var $remote_dbg = "localhost";
   var $log_file = "":
      
   var $email = false;
   var $stdlog = true;
   var $remote = false;
   var $display = true;
   
   var $notify = false;
   var $halt_script = true;
As you can see, there are a number of variables that we initialize. The first three are used later as parameters for the error_log() function. They are:

Configuration variables

$error_msg - The standard format of the error message to be used

$email_addr - If e-mailing the error somewhere, mail it here

$remote_dbg - the address for PHP to connect to during remote debugging

$log_file - the log file to store the message in. If blank use the default system logger

Configuration flags

$email - Report errors via e-mail

$stdlog - Log errors to file using $log_file or default system logger

$remote - Log errors to PHP debugging connection

$display - echo the error to the user via stdout or the browser window

Internal use flags

$notify - Default to false. Used to determine if error should be reported to user (dependent on the error reporting level).

$halt_script - Default to true. Set to true for those errors that are to be considered "fatal" errors.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-05-2007, 09:10 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Part 2 -- Error-dependent processing

Once the error handler has been initialized, you need to determine the nature of the error that has occurred. At this point, you will need adjust the $notify and $halt_script flags as necessary, depending on the error and error reporting level.

Note that the $halt_script variable must be set as necessary, regardless if you are told to ignore the error (based on the error reporting level) in order to ensure the script terminates as expected. In the event you process the error, the script will designate a category string to be used later in $error_msg and set $notify to true on top of any changes made to $halt_script.

Code:
switch($errno) {
   
   case E_USER_NOTICE:
   case E_NOTICE:
   
      $halt_script = false;        
       $type = "Notice";
       break;
       
   case E_USER_WARNING:
   case E_COMPILE_WARNING:
   case E_CORE_WARNING:
   case E_WARNING:
   
      $halt_script = false;       
       $type = "Warning";
       break;
      
   case E_USER_ERROR:
       case E_COMPILE_ERROR:
   case E_CORE_ERROR:
   case E_ERROR:
      
       $type = "Fatal Error";
       break;
   
   case E_PARSE:
   
       $type = "Parse Error";
       break;
   
   default:
      
        $type = "Unknown Error";
       break;
  }
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-05-2007, 09:12 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Error Handling in PHP

Part 3 -- Notification and termination

The final step in the error handling function will be to notify the user of the error in the appropriate fashionas defined in Step 1 of the script. Notification will only occur if the error reporting level includes the type of error that occurred by checking the $notify variable that was created in Step 1 and changed (assuming we will display the error) in Step 2.

Finally, after any output has occurred, you finish your error handling function by halting the script if the type of error that occurs warrants it. All output except for displaying to stdout (or the browser) is done through the use of the error_log() function.

Code:
if($notify) {
   
       $error_msg = $type . $error_msg;
       
       if($email) error_log($error_msg, 1, $email_addr);
       if($remote) error_log($error_msg, ,2, $remote_dbg);
       if($display) echo $error_msg;
       if($stdlog) {
          if($log_file = "") {
             error_log($error_msg, 0);
          } else {
             error_log($error_msg, 3, $log_file);
          }
       }
       
   }
   
   if($halt_script) exit -1;
   
}
?>
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 09-05-2007, 09:14 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Default Re: Error Handling in PHP

Using the error handler in your script

The error handler can be used to process all of the errors PHP triggers internally during the processing of your script. But it can also be used to handle errors that you trigger (that may not necessarily be errors in the script itself, but rather errors that occur due to incorrect function of the script) through the use of the trigger_error() function we described earlier in the article. The syntax for the trigger_error() function is as follows...
Code:
    trigger_error(<error string>, [error code])
...where <error string> represents a string describing the error and [error code] is the integer value describing the type of error that occurred (such as E_USER_ERROR). If no error code is provided, E_USER_NOTICE is assumed as the default error code value.

Note: trigger_error() will only accept E_USER error codes. It is not possible to trigger internal PHP errors (such as E_PARSER) through this or any other function in the PHP language.

Clean error output

When you were introduced to the problems associated with the standard PHP error handler, one of the examples provided referred to an error potentially happening within a JavaScript code segment or HTML Comment that would result in the error not being displayed in the browser. Now that we have a custom error handling function in place, eliminating this problem is quite simple.

By using output buffering in your script, you can guarantee that only your error message (or HTML file, for that matter) will appear when an error is triggered. This can simply be done through the use of the ob_end_clean() function. When output buffering is turned on, no output will be sent to the browser until the script execution is complete or the script is specifically told to output the buffer.

Just as the script can force PHP to output the buffer, it can also be told to erase it though the use of the ob_end_clean() function mentioned earlier. By placing a call to ob_end_clean() prior to any output by your error function, you can ensure that the output that is sent to the browser is either only an error, or the proper content -- but never both.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 09-18-2007, 09:54 AM
Sabari Sabari is offline
D-Web Genius
 
Join Date: Jul 2007
Posts: 1,008
Sabari is on a distinguished road
Default Re: Error Handling in PHP

i don't know what is meant by SCALAR VALUE, Actually i got this RUN-time warnings "Cannot use a scalar value as an array" Error in Error Log file, how can know and fix this error, please advice, immediate reply will be appritiatable..
__________________
Thanks & Regards
Sabari...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 09-21-2007, 05:01 AM
Sabari Sabari is offline
D-Web Genius
 
Join Date: Jul 2007
Posts: 1,008
Sabari is on a distinguished road
Default Re: Error Handling in PHP

any one answer for this above question, i'm searching lot of sites but didn't get, please help me how to fix this error.
__________________
Thanks & Regards
Sabari...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 09-21-2007, 05:03 AM
Sabari Sabari is offline
D-Web Genius
 
Join Date: Jul 2007
Posts: 1,008
Sabari is on a distinguished road
Default Re: Error Handling in PHP

for example i got this message in Error log,

Sep-19-2007,1:27:35PM /web/mem_home.php /web/mem_signin.php 2 443 RUN-time warnings : Cannot use a scalar value as an array

also i don't know which line this error occur?
__________________
Thanks & Regards
Sabari...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Error Handling in Triggers Murali Database Support 1 09-20-2007 07:09 AM
How can I do error handling in php? itbarota PHP Programming 1 09-12-2007 03:56 AM
How can I do error handling in php? itbarota PHP Programming 0 09-12-2007 12:39 AM
Describe error handling in the FRD? devarajan.v Testing Tools 1 07-27-2007 06:19 AM
Error Handling vigneshgets Software Testing 0 05-18-2007 03:36 AM


All times are GMT -7. The time now is 07:04 PM.


Copyright ©2004 - 2007, DiscussWeb. All Rights Reserved.

SEO by vBSEO 3.0.0