PHP Error Handling Functions

    PHP provides some functions that allow you to manage error handling and logging. You can also define your own rules to handle occurred errors. You can manage the way you can log the errors. These functions will give you complete flexibility to play around errors occurring. You can easily log errors to other machines or you can send them via emails. This allows you to keep track and monitor the errors. These functions come with the core PHP and they do not require any configuration settings. You can make runtime setting changes in php.ini file and some of the settings are given below-

    Name Default Changeable
    error_reporting NULL PHP_INI_ALL
    display_errors "1" PHP_INI_ALL
    display_startup_errors "0" PHP_INI_ALL
    log_errors "0" PHP_INI_ALL
    log_errors_max_len "1024" PHP_INI_ALL
    ignore_repeated_errors "0" PHP_INI_ALL
    ignore_repeated_source "0" PHP_INI_ALL
    report_memleaks "1" PHP_INI_ALL
    track_errors "0" PHP_INI_ALL
    html_errors "1" PHP_INI_ALL
    docref_root "" PHP_INI_ALL
    docref_ext "" PHP_INI_ALL
    error_prepend_string NULL PHP_INI_ALL
    error_append_string NULL PHP_INI_ALL
    error_log NULL PHP_INI_ALL
    warn_plus_overloading NULL

    PHP Error handling constants

    PHP provides you with the number of constants that you can use while making the configuration setting to your php.ini file. Below is the list of the constants that you can use-

    Value Constant & Description
    1 E_ERROR- these are fatal run-time errors which cannot be recovered and the execution of the script get stopped.
    2 E_WARNING- these are non-fatal run-time errors and the execution of the script is not stopped.
    4 E_PARSE- these are Compile-time parse errors which are generated by the parser
    8 E_NOTICE- these are run-time notices that usually happen while running a script normally
    16 E_CORE_ERROR- these are fatal errors at PHP startup which is like an E_ERROR in the PHP core
    32 E_CORE_WARNING- these are non-fatal errors at PHP startup which is like an E_WARNING in the PHP core
    64 E_COMPILE_ERROR- these are fatal compile-time errors which are generated by the Zend Scripting Engine
    128 E_COMPILE_WARNING- these are non-fatal compile-time errors which are generated by the Zend Scripting Engine
    256 E_USER_ERROR- these are a fatal user-generated error which is set by the programmer using the PHP trigger_error() function.
    512 E_USER_WARNING- these are non-fatal user-generated warning which is set by the programmer using the PHP trigger_error() function.
    1024 E_USER_NOTICE- these are user-generated notice which is set by the programmer using the PHP function trigger_error()
    2048 E_STRICT- these are run-time notices which help to maintain interoperability and compatibility of the code
    4096 E_RECOVERABLE_ERROR- these are a catchable fatal error which can be caught by a user-defined handle.
    8191 E_ALL- this error will include all errors and warnings, except level E_STRICT

    PHP Error Handling Functions

    1. debug_backtrace()

    This function will provide the information in an associative array and return elements like- current function name, current line number, current file name, current class name, current object, the call type and the function argument or the list of the file name. This function will not take any parameter to be passed.

    Syntax

    array debug_backtrace ( void );

    Example

    <?php
       function demo($var) {
          echo " $var";
          var_dump(debug_backtrace());
       }
       demo('hello');
    ?>

    Output

    helloarray(1) {
      [0]=>
      array(4) {
        ["file"]=>
        string(19) "/workspace/Main.php"
        ["line"]=>
        int(7)
        ["function"]=>
        string(8) "printStr"
        ["args"]=>
        array(1) {
          [0]=>
          string(5) "hello"
        }
      }
    }

    2. debug_print_backtrace()

    This function will allow you to print a PHP backtrace, the function call and also includes all the required files and eval()ed stuff.

    Syntax

     void debug_print_backtrace ( void );

    Example

    <?php
       function hello() {
          bye();
       }
       function bye() {
          demo();
       }
       function demo(){
          debug_print_backtrace();
       }
       hello();
    ?>

    Output

    #0  demo() called at [/workspace/Main.php:7]
    #1  bye() called at [/workspace/Main.php:3]
    #2  hello() called at [/workspace/Main.php:13]

    3. error_get_last()

    This function will provide you with the details of the last error occurred. The information will be in an associative array format specifying the type, message, file and the line of the error. It will return Null value if there was no error encountered.

    Syntax

    array error_get_last ( void );

    Example

    <?php
       print_r(error_get_last());
    ?>

    Output

    Array (
       [type] => 8
       [message] => Undefined variable: a
       [file] => /var/www/tutorialspoint/php/test.php
       [line] => 2
    )

    4. error_log()

    This function will allow you to send the error message to the web server’s error log, to a file or any TCP port. Below are the parameters that are being passed to this function.

    • Message- this parameter will specify the error message that needed be logged.
    • Message_type- this parameter will specify where the error should go. Below are the possible message types-

    0 ?This is the default error which will be sent to the servers logging system or to a file which will depend on the setting of error_log configuration in the php.ini file

    1 ? This error will be sent by email to the address which is mentioned in the destination parameter.

    2 ? This error will be sent using the PHP debugging connection.

    3 ? This error is needed to be added to the file destination string

    • Destination- it depends on the message_type parameter as described above.
    • Extra_headers- this parameter will be used when the message_type parameter is set to 1.

    Syntax

    bool error_log ( string $message [, int $message_type [, string $destination [, string $extra_headers]]] )

    5. error_reporting()

    This function will set the error_reporting directive at the runtime. You will get a number of error levels and you can set them for the runtime of the script. This function will take one parameter which is optional- level.

    Syntax

    int error_reporting ( [int $level] );

    Different Levels are available-

    Value Constant & Description
    1 E_ERROR- these are fatal run-time errors which cannot be recovered and the execution of the script get stopped.
    2 E_WARNING- these are non-fatal run-time errors and the execution of the script is not stopped.
    4 E_PARSE- these are Compile-time parse errors which are generated by the parser
    8 E_NOTICE- these are run-time notices that usually happen while running a script normally
    16 E_CORE_ERROR- these are fatal errors at PHP startup which is like an E_ERROR in the PHP core
    32 E_CORE_WARNING- these are non-fatal errors at PHP startup which is like an E_WARNING in the PHP core
    64 E_COMPILE_ERROR- these are fatal compile-time errors which are generated by the Zend Scripting Engine
    128 E_COMPILE_WARNING- these are non-fatal compile-time errors which are generated by the Zend Scripting Engine
    256 E_USER_ERROR- these are a fatal user-generated error which is set by the programmer using the PHP trigger_error() function.
    512 E_USER_WARNING- these are non-fatal user-generated warning which is set by the programmer using the PHP trigger_error() function.
    1024 E_USER_NOTICE- these are user-generated notice which is set by the programmer using the PHP function trigger_error()
    2048 E_STRICT- these are run-time notices which help to maintain interoperability and compatibility of the code
    4096 E_RECOVERABLE_ERROR- these are a catchable fatal error which can be caught by a user-defined handle.
    8191 E_ALL- this error will include all errors and warnings, except level E_STRICT

    Example

    <?php
       error_reporting(0);
       error_reporting(E_ALL);
    ?>

    6. restore_error_handler()

    This function will allow you to revert to the previous error handler which is set after using the set_error_handler() function. This function will mostly return true.

    Syntax

    bool restore_error_handler ( void );

    Example

    <?php
       function unserialize_han($no, $str) {
          echo "Invalid.\n";
       }
          $var = hello;
          set_error_handler('handler');
          $var2 = unserialize($var);
          restore_error_handler();
    ?>

    Output

    Invalid

    7. set_error_handler()

    This function will allow you to define your own set of rules to handle the runtime errors. If you want to delete some file or folders whenever an error is encountered you can handle this kind of situation with your set rules.

    Syntax

    mixed set_error_handler ( callback $error_handler [, int $error_types] );

    This function will take two parameters among which error_handler is mandatory and the error_types which is an optional parameter.

    Error handler function syntax

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

    Where

    • errno ? This is the first parameter which specifies the error level.
    • errstr ? The second parameter which will specify the error message.
    • errfile ? This is the third parameter which is optional and specifies the filename where an error has occurred.
    • errline ? This is the fourth optional parameter which specifies the line number of the error.
    • errcontext ? This is the fifth optional parameter which is an array pointing to the active symbol table where the error occurred.

    Example

    <?php
       function customError($errno, $errstr, $errfile, $errline) {
               die();
       }
       set_error_handler("Error");
       $test = 0;
       if ($test >  -1) {
          trigger_error("A custom error has been triggered"); } ?>

    8. set_exception_handler()

    This function will allow you to set the default exception handler in case if there is no try/catch block to catch the exception. The normal execution will halt after the exception is called. This function will take one single parameter.

    Syntax

    string set_exception_handler ( callback $exception_handler );

    Example

    <?php
       function excp_handler($excp) {
          echo "Uncaught exception -" , $excp>getMessage(), "\n";
       }
          set_exception_handler('excp_handler');
       set_exception_handler();
         throw new Exception('Not Found Exception');
       echo "not included Executed\n";
    ?>

    Output

    Uncaught exception - Not Found Exception

    9. trigger_error()

    This function will allow you to trigger an error condition which can be used in conjunction with the built-in error handler or can be used with the user-defined function as a new error-handler.

    Syntax

    bool trigger_error ( string $error_msg [, int $error_type] );

    Where error_msg will specify the message regarding the occurred error. The error_type is optional and specify the error type like- E_USER_ERROR, E_USER-WARNING, E_USER_NOTICE.

    Example

    <?php
     if ($test<10) {
        trigger_error("less than 10");
    }
    ?>

    Output

    less than 10

    10. user_error()

    This function will allow you to trigger an error condition which can be used in conjunction with the built-in error handler or can be used with the user-defined function as a new error-handler.

    Syntax

    bool trigger_error ( string $error_msg [, int $error_type] );

    Where error_msg will specify the message regarding the occurred error. The error_type is optional and specifies the error type like- E_USER_ERROR, E_USER-WARNING, E_USER_NOTICE.

    Example

    <?php
        if ($test<10) {
        user_error("less than 10");
    }
    ?>

    Output

    less than 10

    People are also reading: