PHP Error Handling

errors are the most common event a developer faces when programming. errors can be categorized as syntactical, run-time, or logical.

  • syntax error: missing the semicolon at the end of a statement.
  • run-time error : trying to connect to a database when the server is down
  • logic error : providing incorrect data to a variable

to help reduce the number of errors in your code, and to mitigate their effects, proper error handling is essential in your web application.

php error handling mechanism to improve your application's security, appearance, and debugging capabilities.

look different error handling methods:

  • die() statement
  • custom error handler
  • error reporting

triggers error.


error handling using the die() function

in the example below 'fopen' function open a file to read and write operation:

        <?php    $rw = fopen("user.txt", "r+");  ?>

if the file does not exist 'fopen' function throw an run-time error look like:

 note:-        warning: fopen(user.txt) [function.fopen]:failed to open stream:

                  no such file or directory in c:\web\data.php on line 1

in the example below we uses a simple error handling mechanism.

     <?php  
     
               if( !file_exists("user.txt")){
               
                    die("user.txt file not found );
                    
                }else 
                      {
                      
                        $rw = fopen("user.txt", "r+");
                      
                      }
     ?>

if the file does not exist the die function display a simple message: "user.txt file not found"


php custom error handling

it is possible to override php's default mechanism for handling errors. this option gives the programmer full control over what actions to take when an error is raised.

in this process we create a special function that can be called when an error occurs in php. this function must be able to handle a minimum of two parameters(error_level, error_message) but can accept up to five parameters.

syntax:

         error_function(error_level, error_message, error_file, error_line, error_context)

note : a custom error handler can't intercept fatal errors e_error, parsing errors e_parse or legacy code notifications e_strict and e_compile_error, E_compile_warning.

parameterdescription
error_levelrequired. specifies the error reporting level for the error. must be a value number.
error_messagerequired. specifies the error message.
error_fileoptional. specifies the name of the file in which the error occurred.
error_lineoptional. specifies the line number at which the error occurred
error_contextoptional. specifies an array containing every variable, their values, in use when the error occurred

PHP error report levels

These error report levels are the different types of error the user-defined error handler can be used for. these values can be used combination using | operator.

valueparameterdescription
2e_warningnon-fatal run-time errors. execution of the script is not halted.
8e_noticerun-time notices. indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
256e_user_erroruser-generated error message.this is like an e_error set by the programmer using the php function trigger_error()
512e_user_warningnon-fatal user-generated warning message. this is like an e_warning set by the programmer using the php function trigger_error()
1024e_user_noticeuser-generated notice. this is like an e_notice set by the programmer using the php function trigger_error()
4096e_recoverable_errorcatchable fatal error. this is like an e_error can be caught by a user defined handler ( set_error_handler() )
8191e_allall errors and warnings

 

first we create a error handling function. when it is triggered it generate error level, error message and line number at which the error occurred :

<?php
        function error_handler( $error_level, $error_message, $error_line){
                
             echo  "error : [" . $error_level . "]  error message :". $error_message;
                                  
             echo  "<br/> line number at which error occured :". $error_line;   
           }
     ?>

PHP set error handler

the set_error_handler() function use to sets a user-defined error handler function.

<?php
        function error_handler( $error_level, $error_message, $error_line){
                
    echo  "<br/>error : [". $error_level ."]  error message :". $error_message;
                                  
          }
                // use set_error_handler()  to tell php  to use our method
                
                set_error_handler("error_handler");
                
                echo   ( 30/0 );    // at this point run-time error will trigger  
                 
                echo   ( $data );   // at this point undefined variable error will trigger
     ?>

the output of the code above should be like this:

error : [2] error message :division by zero
error : [8] error message :undefined variable data

PHP - trigger errors

you can pragmatically trigger an error of a specific level using trigger_error() function.

           trigger_error( error_msg, error_level)
  • error_msg - the designated error message. it's limited to 1024bytes in length.
  • error_type - possible error types :-
  • e_user_error - fatal user-generated run-time error.execution of the script is halted.
  • e_user_warning - non-fatal user-generated run time error.script is not halted.
  • e_user_notice - default. user-generated run time notice.

this function is useful when you need to generate a particular response to an exception at runtime.

in example, code triggers an e_user_error warning if the value of $data is greater than 1:

<?php
        function error_handler( $error_level, $error_message, $error_line){
                
    echo  "<br/>error : [". $error_level ."]  error message :". $error_message;
                                  
          }
                // use set_error_handler()  to tell php  to use our method
                
                set_error_handler("error_handler");
                
                //trigger error
                
                $test = 2 ;
                
                if( $test>1 ){
                
                    trigger_error("value must be less then one", e_user_error);
                              
                           }    
     ?>

the output of the code above should be something like this:

      error : [256] error message : value must be less then one

php error logging

the error_log() function sends an error to a specified file or a remote destination.

by default, php sends an error log to the server logging system or a file, depending on how the error_log configuration is set in the php.ini file.

    error_log( msg, type, destination, headers)

in the example we will send an e-mail with an error message and end the script:

<?php
        function error_handler( $error_level, $error_message, $error_line){
                
    echo  "<br/>error : [". $error_level ."]  error message :". $error_message;
    
    error_log("error :[$error_level]  error message : {$error_message}",1,
    
                   "nehrasandeep76@demo.com", "from: w3webs@demo.com");
                                  
          }
                // use set_error_handler()  to tell php  to use our method
                
                set_error_handler("error_handler");
                
                //trigger error
                
                $test = 2 ;
                
                if( $test>1 ){
                
                    trigger_error("value must be less then one", e_user_warning);
                              
                           }    
     ?>

the output of the code above should be like this:

      error : [256] error message : value must be less then one

the mail received from the code above looks like:

      error : [256] error message : value must be less then one

php error reporting

the error_reporting() function indicate which errors are reported or sets the duration of the current script.

the error_reporting() has no effect if you have defined your own error handler with set_error_handler()

       error_reporting( error_level )

look the error_levels

  <?php

        // Turn off all error reporting
        error_reporting(0);

        // Report simple running errors
        error_reporting(E_ERROR | E_WARNING | E_PARSE);


        // Report all errors except E_NOTICE
        // This is the default value set in php.ini
        error_reporting(E_ALL ^ E_NOTICE);

        // Report all PHP errors (see changelog)
        error_reporting(E_ALL);

        // Report all PHP errors
        error_reporting(-1);

        //Same as error_reporting(E_ALL);
        ini_set('error_reporting', E_ALL);
        
  ?>