Results 1 to 6 of 6

Thread: Reporting and handling errors in PHP

  1. #1
    Join Date
    Sep 2005
    Posts
    1,306

    Reporting and handling errors in PHP

    When developing a PHP project, whether it’s a simple website or a much larger web application, it’s always a good idea to take into account the potential appearance of errors in your PHP code. An error occurs whenever PHP tries to execute an instruction which either results in an impossible outcome, or otherwise prevents the script from executing in the manner intended by the programmer.

    Errors range from simple fatal errors, where program execution is halted at the point of the fault - usually a syntax error or a call to a function that doesn’t exist - to more complex errors where the cause of the problem isn’t immediately clear, and an indepth review of the code must be carried out to pinpoint the flaw.


    Undefined Variables


    Dealing with errors in a proper way is very important when developing PHP code.The default behavior of PHP when encountering an error is to output a very simple line of text, which looks very ugly which no one will wan tot have it.

    Code:
    echo ($welcome_world);
    Here, we are trying to access a variable $welcome_world which has not been defined. The resulting output will be a screen with the following text

    Notice: Undefined variable: hello_world in C:\local\myphp.php on line 5

    Note: You might not see this appear on screen right away. PHP sometimes is not fully set up to display all errors as they happen. To change PHP’s default behavior, we need to add some of the lines before the echo statement.

    Code:
    error_reporting(E_ALL|E_STRICT);
    ini_set("display_errors", TRUE);
    Line 1 tells PHP to report all errors whereas Line 2 sets a PHP configuration variable which instructs PHP to always display errors.

    One way to get around this error message cropping up in the first place is to make sure you’ve properly defined the variable before you use it. And if you’re uncertain whether or not the variable is defined, you can always place checks before calling it, like so


    Code:
    //the isset function checks if a given variable is defined or not
    if(isset($hello_world){
      echo $hello_world;
    } else {
      echo "The variable 'hello world' couldn't be located";
    }

    But that’s not practical when you have to do the same checks for every variable, and the error message displayed still makes it all too clear to other people something has gone wrong.

  2. #2
    Join Date
    Sep 2005
    Posts
    1,306

    Re: Reporting and handling errors in PHP

    Customizing Error Handling

    Over here we have a very common instance of an error message when something goes wrong

    Code:
    Fatal error: Call to undefined function hello_world() in C:localmyphp.php on line 1

    The error displayed above isn’t not so pretty to look. In fact, if a anyone sees that on your site they will think whats in first place, and would probably be discouraged from exploring the site any more, even if the error wasn’t a fatal error, and they could still browse.

    A good way to is to use a custom error handler, which allows you to intercept PHP’s error commands, and replace them with your own, nicely formatted ones, even hiding them away completely from visitors, and displaying them only to yourself.


    Code:
    function custom_error_function($level, $message, $file, $line, $context){

    Creating a Custom error handler is very simple as creating a new function with some of the agrumenst which are listed below:-

    1. Error level (required) : This specifies the specific level of error reported, useful for determining how serious a fault is
    2. Error message (required) : This variable holds the error message generated by PHP
    3. Error file (optional) : This tells the function which file the error occured in
    4. Error line (optional) : This tells the function which line of the file the error occured on
    5. Error context (optional) : This holds an array containing all variables in use at the time the fault occurred


    The specific error levels generated by an error are outlined below.


    Lets try creating our own customised error function, to try and make the default error message a little bit friendlier to look at


    Code:
    function customError($level, $message){
      //note that the final three arguments are optional
      echo "An error has occured! The error level is $level and the message was '$message'<br/>";
      echo "Please get in touch with the site administrator at admin@email.com to notify them of this fault";
    }

    The function above is not yet completed, but when set to be the default error handler for PHP, as the following code will do, it will prints out a much friendlier error message, and lets the user know of a course of action they can take to get the problem solved.

    Code:
    //this function will set the custom error handler to our function above
    set_error_handler("customError");
    //now, let's try triggering that error again...
    echo ($hello_world); /* our undefined variable */

  3. #3
    kattam Guest

    Re: Reporting and handling errors in PHP

    Logging Errors

    Logging erros normally includes shielding the website visitors from the full effects of the error, while giving yourself as much information as possible about the problem so you can set about fixing it in a timely manner.

    Error logging in PHP is a very helpful tool which can be use to record messages about errors that have occured in your website. This way, you don’t have to rely on your site visitors notifying you when things go wrong.

    error_log()

    Let’s modify our custom error handler function from the previous section to use a useful function of PHP, error_log() , normally this function usually takes three variables, and a fourth when we are sending error logs via email.

    • Error message : The message to send to the log
    • Message type :
    • 0 - Use PHP’s system logger to record the message
    • 1 - Send the message via email to the address specified in the next argument 3 -Write the error to the file specified in the next argument
    • Message destination : When message type is set to 1 or 3, this is either the email address, or the local file to be written to.
    • Custom headers : When message type is set to 1 (send via email) this variable holds the custom mail headers used by mail() - see the tutorial on PHP and email



    Code:
    function customError($level, $message, $file, $line)
    { 
      //here we'll append the error to the local file error.log
      error_log("Error level $level occured : '$message'",3, "error.log");
      //now that we've safely recorded the error, we don't need to rely on the visitor
      //to inform us of any faults
    }
    set_error_handler("customError");
    //let's trigger the error again...
    echo($hello_world);

    Now, we won’t see anything appear on screen, but the error will be recorded within the error.log file. Here, if we look on the first line of that file, we will see

    Code:
    Error level 8 occured : 'Undefined variable: welcome_world'

    Selective error handling

    With this we can modify the behaviour of our custom error handler to deal with the errors more effectively


    Code:
    function customError($level, $message, $file, $line)
    { 
      if($level >= E_USER_ERROR)
        error_log("Error level $level occured : '$message'",3, "error.log");
    }

    Now, this function will ignore all errors less serious than E_USER_ERROR and log only those errors which pose a risk to the application. We can test this by use of the trigger_error() function, which will generate a user-triggered error.

    Code:
    trigger_error("User generated error");
    It will cause the following line to appear in error.log

    Code:
    Error level 1024 occured : 'User generated error'
    Fatal errors : Unfortunately, PHP doesn’t allow fatal errors to be handled with custom error handlers - the assumption here being that a fatal error will pretty much have killed your script anyway, with no hope of recovery. Fatal errors can be created by calling functions that don’t exist, for example

    Code:
    welcome_world();

  4. #4
    Join Date
    Sep 2005
    Posts
    1,306

    Re: Reporting and handling errors in PHP

    Errors for Debugging purpose

    Sometimes it’s useful to be able to see basic errors, especially while you’re developing your site. Nothing provides quite as many headaches as a problem that seems to have no obvious cause and having error messages popping up all over the place,the best way is to specify “who you are” to your website while you’re developing it, so that the site can distinguish between yourself, the developer, and a member of the public.


    Debug using your IP address

    The first way involves your unique IP address, which is stored in the $_SERVER variable on the webserver, and can be accessed simply inside your script.

    First, grab your IP address from a good site. Once you’ve got that you can make some simple adjustments to your error handling function like so

    Code:
    function customError($level, $message, $file, $line)
    { 
      if($_SERVER['REMOTE_ADDR'] == "164.25.66.42"){
        echo "An error occurred ($level) : '$message'";
      } else {
        if($level >= E_USER_ERROR) {
          //write critical errors to the log for normal users
          error_log("nError level $level occured : '$message'",3, "error.log");
        }
      }
    }
    set_error_handler("customError");
    //let's trigger the error again.
    echo $hello_world;
    Over here the variable $_SERVER['REMOTE_ADDR'] holds the IP address of the visiting computer and if it matches the value you’ve entered, then an error is displayed. If not, then the script knows you’re just a member of the public browsing the site and won’t display an error.


    Debug using $_GET variables

    A second way, which dose not depend on storing your IP address uses the $_GET variable of PHP, which passes data from the URL into the script.
    You don’t need to keep track of your IP address in the code, which can be troublesome if you develop from multiple locations, or your IP address changes frequently.

    Instead of that you can turn debugging on and off easily, which allows you to see the site as a visitor would


    By typing any website URL like so, we have access to a variable $_GET['debug'] from within the script. Modifying our custom error handler again

    Code:
    function customError($level, $message, $file, $line)
    { 
      if($_GET['debug'] == "on"){
        echo "An error occurred ($level) : '$message'";
      } else {
        if($level >= E_USER_ERROR) {
          //write critical errors to the log for normal users
          error_log("nError level $level occured : '$message'",3, "error.log");
        }
      }
    }
    set_error_handler("customError");
    //let's trigger the error again...
    echo $hello_world;
    A small change, but one which allows us to control our debugging status more easily.

    This tutorial has only covered the basics of PHP error handling, but hopefully it’s given you a good idea of what to consider when you’re writing your code.

  5. #5
    Join Date
    Sep 2005
    Posts
    1,306

    Re: Reporting and handling errors in PHP

    Handling Exception

    A neater way of handling errors in PHP is to use a feature called exceptions. Exceptions can be used when we wish to impose conditions on the execution of our scripts, or when we want to be able to recover gracefully from conditions where, otherwise, execution of the program would grind to a halt.

    Exceptions to catch user-defined Runtime Errors

    Let’s look first at a simple of use the Exception class to prevent a function from completing execution whenever it is passed an argument out with certain boundaries.

    Code:
    function tryValue($v){
      if($v < 1 || $v > 6){
        throw new Exception("the value is not between 1 and 6 inclusive");
      }
      else return $v*2;
    }
     
    try {
      echo tryValue(4);
      echo tryValue(10);
    } catch(Exception $e) {
      echo "Exception : ".$e->getMessage();
    }
    echo "All done";

    This code produces the following output


    Code:
    8
    Exception : the value is not between 1 and 6 inclusive
    All done

    Line 1-6 : Here we define a function tryValue which simply takes an input $v and doubles it. However, we wish to ensure that the value $v is between 1 and 6 inclusive
    Line 3 : Here, we enter the if statement whenever $v is outwith our boundaries. We then trigger a new exception with the expression throw new Exception(), which halts execution of the function, and PHP then has to find a way to handle the exception
    Since the exception has been thrown, we need to have a way to catch it. Think of it as if the function is throwing the execution out of itself if it notices an error. The function call on line 9 hasn’t thrown anything, because the value is within the acceptable range. The function call on line 10 however, throws an exception, and this is caught by the catch(Exception $e) block
    Line 12 : The code within the catch block is executed whenever an exception is thrown by code within the try block. It’s almost as if you’re saying

    Code:
      try {this code} and if that throws an (Exception, $e) {do this instead (catch the throw)}
    Think of it as if the catch block is a safety net, to catch any failing functions, and prevent the code from hitting the ground hard!

    Inside the catch block you also have access to the Exception object $e, which contains some useful information about the particular error that was thrown, including the message defined at the time the exception was thrown.


    Using Exceptions to identify Errors in Classes

    One useful application of exceptions is to isolate the location of an error within a complex class that depends on many internal functions during run-time. We can encase the whole function call within a try..catch block to ensure that if an exception is thrown at any point during the operation of the class, then the class will immediately exit and return control to the try…catch block where the error will be reported.

    This is in comparison to our earlier error handling functions using set_error_handler(), which would simply output the information there and then, without leaving the scope of the class

    Code:
    class BaseClass{
      function tryValue($v){
        if($v < 1 || $v > 6){
          throw new Exception("the value is not between 1 and 6 inclusive");
        }
        else return $v*2;
      }
    }
    class MyClass extends BaseClass{
      function doubler($x){
        parent::tryValue($x);
      }
    }
    function printException(&$e){
        $trace = $e->getTrace();
        echo "Exception on line ".$e->getLine()." : ".$e->getMessage()."<br/>";
        $count = 1;
        foreach($trace as $k => $v){
            echo "Line {$v['line']} : {$v['class']}::{$v['function']}()<br/>";
            $count++;
        }
        echo "-----------------------<br/>";
    }
    $baseclass = new BaseClass;
    $myclass = new MyClass;
    try {
      echo $baseclass->tryValue(64);
    } catch(Exception $e) {
      printException($e);
    }
    try {
      echo $myclass->doubler(10);
    } catch(Exception $e) {
      printException($e);
    }
    echo "All done";
    This produces useful feedback as shown below

    Code:
    Exception on line 5 : the value is not between 1 and 6 inclusive
    Line 27 : BaseClass::tryValue()
    -----------------------
    Exception on line 5 : the value is not between 1 and 6 inclusive
    Line 11 : BaseClass::tryValue()
    Line 32 : MyClass::doubler()
    -----------------------
    All done

    The Exception instance, $e

    When an exception is thrown, PHP is nice enough to give us an instance of the Exception class $e , complete with a collection of useful methods you can utilise to retrieve more information about the error that just occurred

    • $e->getMessage() : Fetch the custom message that was defined at the point the exception was thrown
    • $e->getLine() : Get the line number where the exception occurred
    • $e->getCode() : Get the code that caused the exception (although in our case we’re manually throwing an exception, so no code is returned)
    • $e->getFile() : Get the name of the PHP file the exception happened in
    • $e->getTrace() : Returns an array containing trace information. This is the array I used to build the detailed debug information in the last example. You can also use getTraceAsString() for a pre-formatted trace string.


    Hopefully from that example you can see how an Exception based error handler can provide you with ever-useful detail about your code which makes the difference between hours of hair-tearing debugging hell.

  6. #6
    Join Date
    Jul 2011
    Posts
    1

    Re: Reporting and handling errors in PHP

    Brilliant. I've been looking for a way to keep error messages on, but hide them from visitors. My page is set up so that the entire thing is one script (divided into a bunch of includes). Some includes are only shown when I'm viewing the page with certain variables set (i.e $public = false;).

    But when I edit one of the includes that's shown on the public version, and something goes wrong, everyone sees my ugly errors. Using the set_error_handler() function allows me to pass the errors through my own simple function (i.e. if(!$public) { // show error }).

    It was getting really annoying turning the error reporting on and off all the time and letting my users see the errors for those short periods when I was debugging.

    Thanks, great info.

Similar Threads

  1. What is Connection Handling in PHP?
    By Soumen in forum Software Development
    Replies: 5
    Last Post: 09-03-2010, 01:19 AM
  2. Exception handling in PL/SQL
    By Ameeryan in forum Software Development
    Replies: 5
    Last Post: 25-02-2010, 11:04 PM
  3. Exception handling in EJB
    By KennedII in forum Software Development
    Replies: 5
    Last Post: 25-02-2010, 04:40 AM
  4. Session Handling In JSP
    By Sheenas in forum Software Development
    Replies: 5
    Last Post: 30-01-2010, 02:24 PM
  5. File Handling in C#
    By GaryK in forum Software Development
    Replies: 1
    Last Post: 10-11-2008, 05:31 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,468,756.82839 seconds with 17 queries