Web Technology II · Unit 10
Sessions, Cookies, and Error Handling
Exam-focused notes for Sessions, Cookies, and Error Handling (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.
Sessions, Cookies, and Error Handling in short
HTTP does not remember users between requests. Sessions and cookies solve this. This chapter also covers how PHP reports, handles and logs errors, and how it protects pages with HTTP authentication.
What this unit covers
- Session creation and initialization
- Session management and termination
- User data maintenance with sessions
- Cookie creation and handling
- Cookie and session comparison
- Error handling and error handlers
- Error reporting and configuration
- Error suppression techniques
- Exception handling and try catch
- Error logs and logging
- HTTP authentication methods
- PHP.ini configuration settings
Cookie creation and handling
2082 · 5 marks
How can you handle cookies and sessions? Illustrate with examples. [5]
2080 · 5 marks
What is a cookie? Write PHP program to create cookie. [5]
HTTP authentication methods
Error handling and error handlers
2082 · 5 marks
What is the error handler? Write a program to demonstrate error handler function. [5]
Show solved answerHide answer
Error Handler in PHP
Definition
An error handler is a user-defined function that is called automatically whenever a PHP error occurs. Instead of displaying the default PHP error messages, a custom error handler allows the programmer to control how errors are handled, such as logging them, displaying custom messages, or redirecting the user.
In PHP, the built-in function set_error_handler() is used to register a custom error handling function.
Syntax
set_error_handler("functionName");
The custom error handler function must accept the following parameters:
| Parameter | Description |
|---|---|
$errno | Error number/level |
$errstr | Error message |
$errfile | File where error occurred |
$errline | Line number where error occurred |
Program to Demonstrate Error Handler
<?php
// Step 1: Define the custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Custom Error Handler Triggered!</b> ";
echo "Error Number : " . $errno . " ";
echo "Error Message: " . $errstr . " ";
echo "Error File : " . $errfile . " ";
echo "Error Line : " . $errline . " ";
echo "<hr>";
}
// Step 2: Register the custom error handler
set_error_handler("myErrorHandler");
// Step 3: Trigger errors to test the handler
// Triggering a user-defined notice
trigger_error("This is a user notice!", E_USER_NOTICE);
// Triggering a user-defined warning
trigger_error("This is a user warning!", E_USER_WARNING);
// Triggering a division by zero warning
$a = 10;
$b = 0;
if ($b == 0) {
trigger_error("Division by zero is not allowed!", E_USER_ERROR);
}
echo "Program continues after error handling.";
?>
Output
Custom Error Handler Triggered!
Error Number : 1024
Error Message: This is a user notice!
Error File : /path/to/file.php
Error Line : 20
---
Custom Error Handler Triggered!
Error Number : 512
Error Message: This is a user warning!
Error File : /path/to/file.php
Error Line : 23
---
Custom Error Handler Triggered!
Error Number : 256
Error Message: Division by zero is not allowed!
Error File : /path/to/file.php
Error Line : 28
Key Points
set_error_handler()overrides PHP's default error handling.trigger_error()is used to manually generate an error for testing.- Common error constants:
E_USER_NOTICE,E_USER_WARNING,E_USER_ERROR. - Custom error handlers help in debugging, logging, and providing user-friendly error messages.
2081 · 5 marks
Define error handlers and error logs with examples. [5]
Show solved answerHide answer
Error handlers and error logs in PHP
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 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
| Feature | Error handler | Error log |
|---|---|---|
| When it acts | At the instant the error is raised | After the fact, as a record |
| Registered or set by | set_error_handler(), try/catch | log_errors, error_log in php.ini |
| Audience | The visitor and the running script | The developer and the administrator |
| Effect on flow | Can format, recover, redirect or stop | None, 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.
2079 · 5 marks
What is error handler? Write a PHP program to show use of error handler to format and print errors. [5]
Show solved answerHide answer
Error handler in PHP
An error handler is a function of your own that PHP calls whenever it raises a diagnostic, in place of printing its built in message. Instead of a raw grey line of text in the middle of a page, the handler receives the details as arguments and can format them, write them to a log, show a friendly message, or stop the script. It is registered with set_error_handler().
set_error_handler("functionName");
The handler is called with four useful arguments:
| Parameter | Description |
|---|---|
$errno | The error level, one of the E_* constants |
$errstr | The message text |
$errfile | The file in which the error was raised |
$errline | The line number in that file |
What it returns matters. Returning true tells PHP the error has been dealt with, so its own handler stays quiet; returning false lets the standard handler run as well, which is how you keep normal logging while adding your own formatting.
A custom handler covers the diagnostics the engine raises, that is E_WARNING, E_NOTICE, E_DEPRECATED and the E_USER_* family. It is never invoked for E_ERROR, E_PARSE or the core and compile level errors, and it is not invoked for a thrown Exception or Error; those need try and catch, and a fatal fault needs register_shutdown_function() with error_get_last().
A program that formats and prints errors
<?php
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
$labels = [
E_WARNING => "Warning",
E_NOTICE => "Notice",
E_DEPRECATED => "Deprecated",
E_USER_ERROR => "User error",
E_USER_WARNING=> "User warning",
E_USER_NOTICE => "User notice",
];
$label = $labels[$errno] ?? "Unknown";
echo "<div style='border:2px solid #c00; padding:10px; background:#ffe6e6;'>";
echo "<strong>" . $label . " caught</strong> ";
echo "<b>Level:</b> " . (int) $errno . " ";
echo "<b>Message:</b> " . htmlspecialchars($errstr, ENT_QUOTES, "UTF-8") . " ";
echo "<b>File:</b> " . htmlspecialchars(basename($errfile), ENT_QUOTES, "UTF-8") . " ";
echo "<b>Line:</b> " . (int) $errline . " ";
echo "</div> ";
if ($errno === E_USER_ERROR) {
exit(1); // PHP does not halt by itself once a handler is installed
}
return true;
}
set_error_handler("myErrorHandler");
echo $undefinedVariable; // PHP 8: E_WARNING, value 2
include "nonexistent_file.php"; // E_WARNING, the file cannot be opened
trigger_error("This is a custom user error.", E_USER_ERROR); // 256
The message text is passed through htmlspecialchars() before it is printed, and the numbers are cast to int, because an error string often quotes a value the visitor supplied and echoing it raw into a page would be a cross site scripting hole. Only the file's base name is shown, so the server's directory layout is not published.
What the page shows
+-----------------------------------------------------------+
| Warning caught |
| Level: 2 |
| Message: Undefined variable $undefinedVariable |
| File: error_demo.php |
| Line: 30 |
+-----------------------------------------------------------+
+-----------------------------------------------------------+
| Warning caught |
| Level: 2 |
| Message: include(nonexistent_file.php): Failed to open |
| stream: No such file or directory |
| File: error_demo.php |
| Line: 32 |
+-----------------------------------------------------------+
+-----------------------------------------------------------+
| User error caught |
| Level: 256 |
| Message: This is a custom user error. |
| File: error_demo.php |
| Line: 34 |
+-----------------------------------------------------------+
Points worth noting
Reading an undefined variable is an E_WARNING with the value 2 in PHP 8, not the E_NOTICE with the value 8 that PHP 5 and 7 produced, and the message now names the variable, as in "Undefined variable $undefinedVariable". A missing array key changed in the same way. A failed include raises two warnings, one from the failed open and one from the failed inclusion, so the handler fires twice for that single line.
trigger_error() raises a diagnostic on purpose and is the usual way to test a handler. Once a custom handler is installed, PHP no longer stops the script on E_USER_ERROR, so the handler must call exit() itself if the run should end, which is why the example does so.
A custom handler improves readability, keeps file paths and query fragments off a production page, and gives one place to add error_log(), so the same code can present a tidy message to the visitor and a complete record to the developer.
0 · 5 marks
Define error handling, error reporting and error suppression. [5]
Session creation and initialization
2081 · 5 marks
What is a session? How can you handle sessions in PHP? [5]
2079 · 5 marks
Write a PHP program for illustrating the starting and ending of session. [5]
Error reporting and configuration
2081 · 5 marks
Describe the concepts of display_errors, variables_order and request_order in PHP.ini Settings. [5]
2080 · 5 marks
Define error reporting and error suppression with examples. [5]
Exception handling and try catch
2080 · 5 marks
Write a PHP program to illustrate the use of exception handling. [5]
User data maintenance with sessions
0 · 5 marks
What is session? Write a PHP program for maintaining user data with sessions. [5]
Make Unit 10 stick
Practice BIT301 with flashcards & quizzes