PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP set_error_handler(): Custom Error Handler

The set_error_handler() function in PHP is used to create a user-defined error handler function for handling errors during the script execution. This function can be very useful for controlling the way errors are managed, and can be particularly valuable for debugging.

Here is a simple tutorial on how to use set_error_handler() in PHP:

Step 1: Define your custom error handler function. This function should take at least two parameters: the error level and the error message. It can also take three optional parameters: the filename in which the error occurred, the line number where the error occurred, and an array containing every variable and their values in use when the error occurred.

Here is a simple example of a custom error handler function:

function customError($errno, $errstr, $errfile, $errline) {
    echo "<b>Error:</b> [$errno] $errstr<br>";
    echo "Error on line $errline in $errfile<br>";
    echo "Ending Script";
    die();
}

In this example, the custom error function outputs the error level, error message, line number, and filename where the error occurred, then it ends the script with die().

Step 2: Set your function as the error handler. The set_error_handler() function is used to register your custom error handler function.

Here is how to use set_error_handler():

set_error_handler("customError");

In this example, "customError" is the name of the function that will handle errors.

Step 3: Trigger an error. For the purpose of this tutorial, let's create an error by trying to echo a variable that does not exist:

echo($test);

Since the variable $test is not set, this will generate an error.

Here is the full code:

<?php
function customError($errno, $errstr, $errfile, $errline) {
    echo "<b>Error:</b> [$errno] $errstr<br>";
    echo "Error on line $errline in $errfile<br>";
    echo "Ending Script";
    die();
}

set_error_handler("customError");

echo($test);
?>

When you run this script, it will display an error message, then end the script, just like we told it to in our custom error handler function.

Remember, the set_error_handler() function returns the old error handler, and NULL if there wasn't one. You can restore the previous error handler by calling restore_error_handler().

It's important to note that not all errors can be caught by user defined error handler. For example, fatal errors and parse errors cannot be caught as they halt script execution before it even gets to the error handling code.

  1. How to implement a custom error handler in PHP: Implement a basic custom error handler:

    <?php
    function customErrorHandler($errno, $errstr, $errfile, $errline) {
        echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("customErrorHandler");
    
    // Trigger a notice
    $undefinedVariable;
    ?>
    
  2. Using set_error_handler() for centralized error handling in PHP: Centralize error handling in a dedicated function:

    <?php
    function centralizedErrorHandler($errno, $errstr, $errfile, $errline) {
        echo "Centralized Error Handler: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("centralizedErrorHandler");
    
    // Trigger an error
    echo $undefinedVariable;
    
  3. PHP error_reporting() and set_error_handler() for error control: Combine error_reporting() and set_error_handler() for fine-grained error control:

    <?php
    error_reporting(E_ALL);
    
    function customErrorHandler($errno, $errstr, $errfile, $errline) {
        echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("customErrorHandler");
    
    // Trigger a warning
    include 'nonexistent_file.php';
    
  4. Creating a logging system with set_error_handler() in PHP: Log errors to a file using set_error_handler():

    <?php
    function logToFile($errno, $errstr, $errfile, $errline) {
        $logMessage = "[$errno] $errstr in $errfile on line $errline\n";
        file_put_contents('error.log', $logMessage, FILE_APPEND);
    }
    
    set_error_handler("logToFile");
    
    // Trigger an error
    echo $undefinedVariable;
    
  5. Customizing error messages with set_error_handler() in PHP: Customize error messages based on error types:

    <?php
    function customErrorHandler($errno, $errstr, $errfile, $errline) {
        $errorType = ($errno & (E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE)) ? 'Warning' : 'Error';
        echo "$errorType: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("customErrorHandler");
    
    // Trigger a warning
    include 'nonexistent_file.php';
    
  6. Handling PHP fatal errors with set_error_handler(): Handle fatal errors using a shutdown function and register_shutdown_function():

    <?php
    function handleFatalErrors() {
        $error = error_get_last();
        if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING])) {
            echo "Fatal Error: [{$error['type']}] {$error['message']} in {$error['file']} on line {$error['line']}\n";
        }
    }
    
    register_shutdown_function("handleFatalErrors");
    
    // Trigger a fatal error
    undefinedFunction();
    
  7. Setting up email notifications for errors with PHP set_error_handler(): Send email notifications for errors using set_error_handler():

    <?php
    function emailErrorHandler($errno, $errstr, $errfile, $errline) {
        $subject = "Error Notification";
        $message = "[$errno] $errstr in $errfile on line $errline";
        $headers = "From: webmaster@example.com";
    
        mail('admin@example.com', $subject, $message, $headers);
    }
    
    set_error_handler("emailErrorHandler");
    
    // Trigger an error
    echo $undefinedVariable;
    
  8. PHP set_error_handler() for handling warnings and notices: Handle warnings and notices using set_error_handler():

    <?php
    function warningHandler($errno, $errstr, $errfile, $errline) {
        echo "Warning: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    function noticeHandler($errno, $errstr, $errfile, $errline) {
        echo "Notice: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("warningHandler", E_WARNING);
    set_error_handler("noticeHandler", E_NOTICE);
    
    // Trigger a warning and a notice
    $undefinedVariable;
    echo $undefinedVariable2;
    
  9. Restoring default error handling with restore_error_handler() in PHP: Restore the default error handling using restore_error_handler():

    <?php
    function customErrorHandler($errno, $errstr, $errfile, $errline) {
        echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_error_handler("customErrorHandler");
    
    // Trigger an error
    echo $undefinedVariable;
    
    // Restore default error handling
    restore_error_handler();
    
    // Trigger another error
    echo $anotherUndefinedVariable;
    
  10. PHP set_exception_handler() and set_error_handler() together: Use set_exception_handler() and set_error_handler() together for comprehensive error handling:

    <?php
    function exceptionHandler($exception) {
        echo "Exception: " . $exception->getMessage() . " in " . $exception->getFile() . " on line " . $exception->getLine() . "\n";
    }
    
    function errorHandler($errno, $errstr, $errfile, $errline) {
        echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n";
    }
    
    set_exception_handler("exceptionHandler");
    set_error_handler("errorHandler");
    
    // Trigger an exception
    throw new Exception("This is a test exception");
    
    // Trigger an error
    echo $undefinedVariable;
    
  11. Using set_error_handler() with anonymous functions in PHP: Use anonymous functions for more concise error handling:

    <?php
    set_error_handler(function ($errno, $errstr, $errfile, $errline) {
        echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n";
    });
    
    // Trigger an error
    echo $undefinedVariable;
    
  12. PHP set_error_handler() for logging to a database: Log errors to a database using set_error_handler():

    <?php
    function logToDatabase($errno, $errstr, $errfile, $errline) {
        $pdo = new PDO('mysql:host=localhost;dbname=error_log', 'username', 'password');
        $stmt = $pdo->prepare("INSERT INTO error_logs (error_number, error_message, error_file, error_line) VALUES (?, ?, ?, ?)");
        $stmt->execute([$errno, $errstr, $errfile, $errline]);
    }
    
    set_error_handler("logToDatabase");
    
    // Trigger an error
    echo $undefinedVariable;