Error handling functions deal with handling errors triggered by PHP scripts. They allow user to define their own error handling rules, as well as modify the way the errors can be logged, change and enhance error reporting to suit user’s needs. With the logging functions, messages send directly to other machines, to an email, to system logs, etc., so user can selectively log and monitor the most important parts of their applications and websites. The error reporting functions allow user to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.

A simple example of error handling would be a situation when user opens a file in PHP but the file does not exist. In such a case the parser will return an error. To prevent this situation, a function can be used:

Example of error handling for missing files in PHP

<?php
    if(!file_exists("path/file.php"))
    {
        die("File does not exist!");
    }
    else 
    {
        $file = fopen("path/file.php", "r");
    }
?>

Error handling functions

These are PHP integrated error handling functions:

  • debug_backtrace - Generates a backtrace
  • debug_print_backtrace - Prints a backtrace
  • error_get_last - Get the last occurred error
  • error_log - Send an error message to the defined error handling routines
  • error_reporting - Sets which PHP errors are reported
  • restore_error_handler - Restores the previous error handler function
  • restore_exception_handler - Restores the previously defined exception handler function
  • set_error_handler - Sets a user-defined error handler function
  • set_exception_handler - Sets a user-defined exception handler function
  • trigger_error - Generates a user-level error/warning/notice message
  • user_error - Alias of trigger_error

Example of detecting undefined variable

<?php
    function customError($errorno, $errorstr) 
    {
        echo "Error: [$errorno] $errorstr";
        die();
    }
    //error handler
    set_error_handler("customError", E_USER_WARNING);
    //call undefined variable
    echo ($variable);
?>

Error logging

These are PHP integrated error logging variables:               

 

Error logging variables

Value Constant Description
2 E_WARNING (integer) Run-time non-fatal error.
8 E_NOTICE (integer) Indicates if script could identify an error.
32 E_CORE_WARNING (integer) Non-fatal error, initiate at startup.
256  E_USER_ERROR (integer) User defined error.
512 E_USER_WARNING (integer) User defined warning message.
32767 E_ALL (integer)  All errors and warnings, as supported. 

›› go to examples ››