Skip to content
PHP Logo

How can an error handler be implemented in PHP to display error messages in a centralized location within HTML code?

When an error occurs in PHP, it can be helpful to have a centralized location within the HTML code to display error messages. This can be achieved by using an error handler function that captures any errors and then displays them in a designated area of the HTML page.

php
// Define the error handler function
function errorHandler($errno, $errstr, $errfile, $errline) {
    echo "<div style='color: red; font-weight: bold;'>Error: $errstr in $errfile on line $errline</div>";
}

// Set the error handler function
set_error_handler("errorHandler");

// Trigger an error to test the error handler
echo $undefinedVariable;