10 Sessions Cookies And Error Handling

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.

Sessions, Cookies, and Error Handling: notes

Session creation and initialization

A session stores user data on the server for one visitor. PHP gives the visitor a session id, which is kept in a cookie named PHPSESSID. On each request, the id is used to find the stored data.

<?php
session_start();                      // must come before any output
$_SESSION["user"] = "Ram";
$_SESSION["role"] = "admin";
echo "Session id: " . session_id();
  • session_start() creates a new session or resumes the existing one.
  • It must be called before any HTML or echo, because it sends a cookie header.
  • Data is stored in the $_SESSION array.
  • The data is kept in files on the server by default.

Session management and termination

<?php
session_start();
if (!isset($_SESSION["user"])) {
    header("Location: login.php");
    exit;
}
echo "Hello, " . htmlspecialchars($_SESSION["user"]);

To log out, clear the data and destroy the session:

<?php
session_start();
$_SESSION = [];                       // clear the data
if (ini_get("session.use_cookies")) {
    $p = session_get_cookie_params();
    setcookie(session_name(), "", time() - 3600, $p["path"], $p["domain"]);
}
session_destroy();                    // remove the session on the server
header("Location: login.php");
  • unset($_SESSION["key"]) removes one item.
  • session_destroy() removes the session file but does not clear the $_SESSION array in the current script.
  • session_regenerate_id(true) makes a new id after login. This helps against session fixation.
  • Sessions end after the time set by session.gc_maxlifetime or when the browser closes.

User data maintenance with sessions

Sessions are used to keep a user logged in, a shopping cart, and temporary messages.

<?php
session_start();

// login check
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if ($_POST["user"] === "ram" && $_POST["pass"] === "secret") {
        session_regenerate_id(true);
        $_SESSION["user"] = "ram";
    }
}

// shopping cart
$_SESSION["cart"][] = ["item" => "Book", "qty" => 2];
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;
echo "You visited " . $_SESSION["visits"] . " times";

In real code, compare a stored password hash with password_verify(). Never keep passwords in plain text.

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]

Note: The reference notes did not contain material on this topic. The following answer is based on standard PHP web development curriculum as taught in BSc CSIT. --- A cookie is a small piece of data stored on the client's browser by the server. It is used to remember information about the user a...

Open this answer on its own page →

2080 · 5 marks

What is a cookie? Write PHP program to create cookie. [5]

A cookie is a small piece of data that a server sends to the user's web browser. The browser stores it and sends it back with subsequent requests to the same server. Cookies are commonly used to: - Remember user login information - Track user sessions - Store user preferences - Maintain state bet...

Open this answer on its own page →

HTTP authentication methods

2082 · 5 marks

What is HTTP authentication? How is it done? [5]

HTTP Authentication is a built-in mechanism provided by the HTTP protocol that allows a web server to challenge a client (browser) for credentials (username and password) before granting access to a protected resource. It is defined in the HTTP specification and operates through specific request ...

Open this answer on its own page →

Error handling and error handlers

2082 · 5 marks

What is the error handler? Write a program to demonstrate error handler function. [5]

Show solved 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:

ParameterDescription
$errnoError number/level
$errstrError message
$errfileFile where error occurred
$errlineLine 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.
Open this answer on its own page →

2081 · 5 marks

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

Show solved 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

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.

Open this answer on its own page →

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 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:

ParameterDescription
$errnoThe error level, one of the E_* constants
$errstrThe message text
$errfileThe file in which the error was raised
$errlineThe 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.

Open this answer on its own page →

0 · 5 marks

Define error handling, error reporting and error suppression. [5]

These three terms describe three different responses to the same event, a PHP script running into something it cannot do. Error handling is what the program does about it, error reporting is how much PHP announces about it, and error suppression is the deliberate silencing of one such announcemen...

Open this answer on its own page →

Session creation and initialization

2081 · 5 marks

What is a session? How can you handle sessions in PHP? [5]

A session is a way to store information (in variables) to be used across multiple pages of a website. Unlike cookies, session data is stored on the server side. Each user gets a unique session ID which is used to identify and retrieve their session data. Note: Reference notes were not available f...

Open this answer on its own page →

2079 · 5 marks

Write a PHP program for illustrating the starting and ending of session. [5]

HTTP has no memory, so two requests from the same visitor look unrelated to the server. A session gives them a thread: PHP generates a session id, sends it to the browser in a cookie, and keeps a matching store on the server. The

Open this answer on its own page →

Error reporting and configuration

2081 · 5 marks

Describe the concepts of display_errors, variables_order and request_order in PHP.ini Settings. [5]

These three directives in php.ini control what a PHP script says when something goes wrong and which request data the engine hands it in the first place. The first is an error visibility setting; the other two decide which superglobals get filled and in what order. displayerrors decides whether t...

Open this answer on its own page →

2080 · 5 marks

Define error reporting and error suppression with examples. [5]

These two settings sit on opposite sides of the same question: how much should a PHP script say when something goes wrong. Error reporting decides which classes of problem PHP announces at all, and error suppression silences the announcement for one expression. The first is a development and oper...

Open this answer on its own page →

Exception handling and try catch

2080 · 5 marks

Write a PHP program to illustrate the use of exception handling. [5]

Exception handling lets a script deal with a runtime failure at the place that knows what to do about it, instead of letting the failure end the request. The code that might fail goes inside try, throw raises an object describing the failure, one or more catch blocks handle it, and an optional fi...

Open this answer on its own page →

User data maintenance with sessions

0 · 5 marks

What is session? Write a PHP program for maintaining user data with sessions. [5]

HTTP is stateless: each request stands alone and the server has no memory of the one before it. A session supplies that memory. When a session starts, PHP generates a long random session id, sends it to the browser in a cookie, and keeps a matching store on the server. On the next request the bro...

Open this answer on its own page →