
- PHP - Home
- PHP - Roadmap
- PHP - Introduction
- PHP - Installation
- PHP - History
- PHP - Features
- PHP - Syntax
- PHP - Hello World
- PHP - Comments
- PHP - Variables
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ and $$ Variables
- PHP - Constants
- PHP - Magic Constants
- PHP - Data Types
- PHP - Type Casting
- PHP - Type Juggling
- PHP - Strings
- PHP - Boolean
- PHP - Integers
- PHP - Files & I/O
- PHP - Maths Functions
- PHP - Heredoc & Nowdoc
- PHP - Compound Types
- PHP - File Include
- PHP - Date & Time
- PHP - Scalar Type Declarations
- PHP - Return Type Declarations
- PHP - Operators
- PHP - Arithmetic Operators
- PHP - Comparison Operators
- PHP - Logical Operators
- PHP - Assignment Operators
- PHP - String Operators
- PHP - Array Operators
- PHP - Conditional Operators
- PHP - Spread Operator
- PHP - Null Coalescing Operator
- PHP - Spaceship Operator
- PHP Control Statements
- PHP - Decision Making
- PHP - If…Else Statement
- PHP - Switch Statement
- PHP - Loop Types
- PHP - For Loop
- PHP - Foreach Loop
- PHP - While Loop
- PHP - Do…While Loop
- PHP - Break Statement
- PHP - Continue Statement
- PHP Arrays
- PHP - Arrays
- PHP - Indexed Array
- PHP - Associative Array
- PHP - Multidimensional Array
- PHP - Array Functions
- PHP - Constant Arrays
- PHP Functions
- PHP - Functions
- PHP - Function Parameters
- PHP - Call by value
- PHP - Call by Reference
- PHP - Default Arguments
- PHP - Named Arguments
- PHP - Variable Arguments
- PHP - Returning Values
- PHP - Passing Functions
- PHP - Recursive Functions
- PHP - Type Hints
- PHP - Variable Scope
- PHP - Strict Typing
- PHP - Anonymous Functions
- PHP - Arrow Functions
- PHP - Variable Functions
- PHP - Local Variables
- PHP - Global Variables
- PHP Superglobals
- PHP - Superglobals
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP File Handling
- PHP - File Handling
- PHP - Open File
- PHP - Read File
- PHP - Write File
- PHP - File Existence
- PHP - Download File
- PHP - Copy File
- PHP - Append File
- PHP - Delete File
- PHP - Handle CSV File
- PHP - File Permissions
- PHP - Create Directory
- PHP - Listing Files
- Object Oriented PHP
- PHP - Object Oriented Programming
- PHP - Classes and Objects
- PHP - Constructor and Destructor
- PHP - Access Modifiers
- PHP - Inheritance
- PHP - Class Constants
- PHP - Abstract Classes
- PHP - Interfaces
- PHP - Traits
- PHP - Static Methods
- PHP - Static Properties
- PHP - Namespaces
- PHP - Object Iteration
- PHP - Encapsulation
- PHP - Final Keyword
- PHP - Overloading
- PHP - Cloning Objects
- PHP - Anonymous Classes
- PHP Web Development
- PHP - Web Concepts
- PHP - Form Handling
- PHP - Form Validation
- PHP - Form Email/URL
- PHP - Complete Form
- PHP - File Inclusion
- PHP - GET & POST
- PHP - File Uploading
- PHP - Cookies
- PHP - Sessions
- PHP - Session Options
- PHP - Sending Emails
- PHP - Sanitize Input
- PHP - Post-Redirect-Get (PRG)
- PHP - Flash Messages
- PHP AJAX
- PHP - AJAX Introduction
- PHP - AJAX Search
- PHP - AJAX XML Parser
- PHP - AJAX Auto Complete Search
- PHP - AJAX RSS Feed Example
- PHP XML
- PHP - XML Introduction
- PHP - Simple XML Parser
- PHP - SAX Parser Example
- PHP - DOM Parser Example
- PHP Login Example
- PHP - Login Example
- PHP - Facebook Login
- PHP - Paypal Integration
- PHP - MySQL Login
- PHP Advanced
- PHP - MySQL
- PHP.INI File Configuration
- PHP - Array Destructuring
- PHP - Coding Standard
- PHP - Regular Expression
- PHP - Error Handling
- PHP - Try…Catch
- PHP - Bugs Debugging
- PHP - For C Developers
- PHP - For PERL Developers
- PHP - Frameworks
- PHP - Core PHP vs Frame Works
- PHP - Design Patterns
- PHP - Filters
- PHP - JSON
- PHP - Exceptions
- PHP - Special Types
- PHP - Hashing
- PHP - Encryption
- PHP - is_null() Function
- PHP - System Calls
- PHP - HTTP Authentication
- PHP - Swapping Variables
- PHP - Closure::call()
- PHP - Filtered unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - Expectations
- PHP - Use Statement
- PHP - Integer Division
- PHP - Deprecated Features
- PHP - Removed Extensions & SAPIs
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI Process
- PHP - PDO Extension
- PHP - Built-In Functions
PHP Error Handling set_error_handler() Function
The PHP Error Handling set_error_handler() function is used for program error management. It lets you handle errors in your own way rather to depending on PHP's built-in error messages. This improves the security and usefulness of your program. Use set_error_handler() to tell PHP to use a custom function you created to handle errors.
It may address a number of problems including alerts and warnings. You can easily debug your apps using this function. Important error data are also hidden from users. This makes the process of developing more secure and efficient websites much easier.
You can specify what should happen in the case of an error by setting a custom error handler. For example, you can say that the error should be logged, that the developer should be emailed, or that the user should get a helpful message. You can even stop the script from running by using commands like exit() inside the error handler, if required.
It is important to note that set_error_handler() does not work with certain important errors, like E_ERROR or E_PARSE. These errors will be handled by PHP's built-in error handling system.
Syntax
Below is the syntax of the PHP Error Handling set_error_handler() function −
callable set_error_handler ( ?callable $handler, int $error_levels = E_ALL );
Parameters
Here are the parameters of the set_error_handler() function −
$handler: (Required) It is a user-defined function (callback) to handle errors. If null is passed, it resets the error handler to PHP's default.
$error_levels: (Optional) It determines which error levels will result in the handler, just like the error_reporting setting. The default value is E_ALL.
Here is the syntax for the $handler −
bool handler( int $errno, string $errstr, string $errfile = ?, int $errline = ?, array $errcontext = ? )
Here are the parameter's description for the above syntax −
errno:The first parameter, errno, contains the level of the error raised, as an integer.
errstr: The second parameter, errstr, contains the error message, as a string.
errfile: The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errline: The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errcontext: The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred.
Return Value
The set_error_handler() function returns the error handler (if any) that was previously defined. Null is returned if the built-in error handler is used. This function will return an indexed array containing the class and the method name if the previous error handler was a class method.
PHP Version
First introduced in core PHP 4.0.1, the set_error_handler() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
The below program defines a simple custom error handler function called errorHandlerFunc. The function is used to display error messages and generates a notification when an undefined variable is accessed. The custom error handler is set using PHP Error Handling set_error_handler() function.
<?php // Custom error handler function function errorHandlerFunc($errno, $errstr) { echo "Error: [$errno] $errstr\n"; } // Set the custom error handler set_error_handler("errorHandlerFunc"); // Trigger an error echo $undefined_variable; ?>
Output
Here is the outcome of the following code −
Error: [2] Undefined variable $undefined_variable
Example 2
In this example, the custom error handler detects warnings (e.g. trying to open a file that does not exist). The errorHandlerFunc function prints the error message once it has determined whether the problem is a warning. The handler is set with the help of the set_error_handler() function.
<?php // Custom error handler function function errorHandlerFunc($errno, $errstr) { if ($errno == E_WARNING) { echo "Warning: $errstr\n"; } } // Set custom handler set_error_handler("errorHandlerFunc"); // Trigger a warning $file = fopen("non_existent_file.txt", "r"); ?>
Output
This will generate the below output −
Warning: fopen(non_existent_file.txt): Failed to open stream: No such file or directory
Example 3
In this example, the custom error handler (advancedErrorHandler) records an error message and handles a variety of error types, such as alerts and warnings. If a fatal error (E_ERROR) be raised, the script ends using exit(). The handler (E_ALL) handles all error levels.
<?php // Custom error handler function function errorHandlerFunc($errno, $errstr, $errfile, $errline) { if ($errno == E_WARNING) { echo "Warning: $errstr<br>"; } elseif ($errno == E_NOTICE) { echo "Notice: $errstr<br>"; } else { echo "Unknown error type: $errno<br>"; } // Stop script execution for fatal errors if ($errno == E_ERROR) { echo "Fatal error occurred! Terminating the script."; exit(); } } // Set custom handler set_error_handler("errorHandlerFunc", E_ALL); // Trigger a warning echo $undefined_variable; // Trigger a fatal error trigger_error("This is a fatal error", E_ERROR); ?>
Output
This will create the below output −
Notice: Undefined variable: undefined_variable Fatal error occurred! Terminating the script.
Example 4
This code will demonstrate you how to write your own PHP error handler. It defines a function called errorHandlerFunc() to handle issues in a particular manner, like showing the file and line number where the problem occurred along with a custom problem message. This custom error handler is set using the set_error_handler() function.
<?php function errorHandlerFunc($errno, $errstr, $errfile, $errline) { echo "Custom error: [$errno] $errstr\n"; echo "Error on line $errline in $errfile\n"; echo "Ending Script"; die(); } //set error handler set_error_handler("errorHandlerFunc"); $test = 0; //trigger error if ($test > -1) { trigger_error("A custom error has been triggered"); } ?>
Output
Following is the output of the above code −
Custom error: [1024] A custom error has been triggered Error on line 16 in /home/cg/root/1531703/index.php Ending Script