2081 6

BIT301 ยท 2081 ยท 5 marks

Define error handlers and error logs with examples.

Define error handlers and error logs with examples. [5]

Web Technology IIChapter 10: Sessions, Cookies, and Error HandlingError handling and error handlers

Quick answer

A running PHP script reports trouble in two different ways, and the two words in this question name the two halves of the response to it. An error handler decides what happens at the moment something goes wrong, while an error log is the permanent written record that lets a developer find out afterwards what went wrong on a live server, where the message is deliberately hidden from the visitor.

Error handlers and error logs in PHP

Error handler

An error handler is a function that PHP calls instead of printing its own diagnostic message, registered with set_error_handler(). The handler receives the error number, the message, the file and the line, and it can format the message, log it, show a friendly page, or stop the script.

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<p class='err'>[" . $errno . "] "
       . htmlspecialchars($errstr, ENT_QUOTES, "UTF-8")
       . " in " . htmlspecialchars(basename($errfile), ENT_QUOTES, "UTF-8")
       . " on line " . (int) $errline . "</p>";
    return true;   // true means PHP's own handler must not run as well
}

set_error_handler("myErrorHandler");

echo $test;   // PHP 8: Warning, Undefined variable $test

The message is escaped with htmlspecialchars() before it is printed, because an error string can contain a value the visitor supplied and printing it raw would be a cross site scripting hole. Note the level too: since PHP 8.0 reading an undefined variable is an E_WARNING, not the E_NOTICE it was in PHP 5 and 7, and reading a missing array key is a warning as well.

A custom handler only sees the diagnostics PHP raises: E_WARNING, E_NOTICE, E_DEPRECATED, the E_USER_* family and so on. It is never called for E_ERROR, E_PARSE or the core and compile level errors, and it is not called for exceptions. To report a genuine fatal error you add a shutdown function:

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e !== null && ($e["type"] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR))) {
        error_log("FATAL: " . $e["message"] . " in " . $e["file"] . ":" . $e["line"]);
    }
});

The second half of handling is try and catch, and PHP 8 makes one point here that is easy to get wrong. Dividing by zero no longer emits a warning: it throws DivisionByZeroError, and that class descends from Error, not from Exception. A catch (Exception $e) block therefore does not catch it. Catch the specific class, or catch Throwable, which is the common ancestor of both branches.

try {
    $result = 10 / 0;
} catch (DivisionByZeroError $e) {          // catch (Exception $e) would MISS this
    echo "Caught: " . $e->getMessage();     // Division by zero
} finally {
    echo "Execution continues.";
}

Error log

An error log is the file, or the system log, in which PHP writes the same diagnostics instead of showing them. On a production site the visitor should see nothing but a polite message, while the developer still needs the file name, the line and the time, so logging is switched on and display is switched off.

display_errors = Off
log_errors     = On
error_log      = /var/log/php_errors.log

The same settings can be made from a script with ini_set(), and error_log() writes a message of your own into whichever destination is configured.

ini_set("log_errors", "1");
ini_set("error_log", "/var/log/php_errors.log");

error_log("Database connection failed in the login module for user id 42.");

Each entry is stamped with the date and time, the severity and the position, so the file reads like this:

[27-Jun-2026 10:35:22 UTC] PHP Warning:  Undefined variable $test in /var/www/index.php on line 15
[27-Jun-2026 10:36:01 UTC] PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in /var/www/calc.php:8
[27-Jun-2026 10:36:01 UTC] Database connection failed in the login module for user id 42.

Never log a password, a session id or a card number: the log is a plain file that operations staff and backups can read.

How the two differ

FeatureError handlerError log
When it actsAt the instant the error is raisedAfter the fact, as a record
Registered or set byset_error_handler(), try/catchlog_errors, error_log in php.ini
AudienceThe visitor and the running scriptThe developer and the administrator
Effect on flowCan format, recover, redirect or stopNone, it only records

In practice a good script uses both together: the handler keeps the page working and shows nothing sensitive, and the log keeps the evidence needed to fix the cause.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.