University Examination Solutions · Computer Applications / IT

Web Designing

July 2023 Past-Paper Solutions & Academic Reference Notes

Dynamic Websites State persistence Apache Web Server Secure Authentication File System Stream CodeIgniter Architecture

Table of Contents

  1. Group A: Short Answers & Operational Explanations
  2. Question 2: Static vs. Dynamic Websites & PHP Core Advantages
  3. Question 3: HTTP GET vs. POST & Dynamic Form Rendering
  4. Question 4: Documentation via Comments & Variable Scopes
  5. Question 5: Associative Array Architectures & File Imports
  6. Question 6: Session-Based Database Authentication & script Termination
  7. Question 7: File System Streams & HTTP Header Redirection
  8. Question 8: MVC Frameworks & CodeIgniter Request Lifecycle
  9. High-Yield Exam Core Points
  10. Quick Revision Matrix
Group A - Short Answers

Group A: Short Answer Questions (Answer any Five: 3 × 5 = 15 Marks)

To secure maximum marks in Group A, candidates must provide clear explanations along with correct syntaxes and standard architectural rationale.

(i) What is the usefulness of a website having Dynamic Content?
Academic Explanation

Dynamic content allows web pages to update in real-time without manual design changes. This approach has several key benefits:

  • Personalization: Generates unique user experiences by tailoring content based on active session parameters, geolocation, user roles, or interaction history.
  • Centralized Database Integration: Simplifies content management by decoupling presentation templates from database storage (e.g., MySQL), allowing updates made in a backend database to instantly reflect across all pages.
  • Enhanced User Engagement: Enables interactive features such as real-time search queries, dynamic shopping carts, e-learning dashboards, and collaborative comment systems.
(ii) Show the difference between == (Equal) and === (Identical) operators in PHP.
Academic Explanation

PHP uses both loose and strict comparison operators, which handle variable evaluation differently:

Operator Type Name Comparison Mechanism Example Result
== Loose Equality Performs Type Coercion (converts both variables to a common type before comparing values). (5 == '5') returns true
=== Strict Identity Checks both value and data type without coercion. If data types differ, it immediately returns false. (5 === '5') returns false
(iii) How Foreach loop is different from For loop in PHP?
Academic Explanation

The difference between these two iteration statements lies in how they navigate memory collections:

  • Standard for Loop: Relies on a manual counter variable, an iteration limit condition, and increment/decrement steps. It requires sequential integer keys to retrieve array values.
    for ($i = 0; $i < count($arr); $i++) { echo $arr[$i]; }
  • Modern foreach Loop: Specifically designed to iterate over arrays or object elements. It manages array pointers internally, retrieving each element sequentially without requiring a manual index variable. It also natively supports associative arrays.
    foreach ($arr as $key => $value) { echo "$key: $value"; }
(iv) List the advantages of Apache Web Server.
Academic Explanation

Apache HTTP Server is a widely used web server characterized by the following structural advantages:

  • Open-Source and Free: Distributed under the Apache License, making it free to use, customize, and extend without licensing fees.
  • Modular Architecture: Allows administrators to enable or disable specific features as needed using modules (e.g., mod_rewrite for clean URLs, mod_ssl for encryption).
  • Decentralized Configuration: Supports directory-level configurations using .htaccess files, enabling individual web applications to override global server settings without requiring server restarts.
  • Cross-Platform Stability: Highly reliable and compatible with leading operating systems (Linux, Windows, macOS), serving as a core component of the LAMP/WAMP stack.
(v) What is SQL Injection?
Academic Explanation

SQL Injection (SQLi) is an exploit technique where an attacker manipulates dynamic database queries by injecting malicious SQL code into input fields (such as form inputs, URL parameters, or headers). This occurs when user inputs are concatenated directly into SQL queries without proper sanitization or parameterization, allowing attackers to bypass authentication, retrieve confidential data, or execute destructive commands on the database server.

(vi) What is the difference between echo and print statements?
Academic Explanation

While both display output, they differ in syntax and behavior:

Feature echo Statement Construct print Statement Construct
Parameter Limits Can accept multiple comma-separated arguments (e.g., echo $a, $b;). Accepts only a single string argument.
Return Value Does not return a value (has a void return type). Always returns an integer value of 1, allowing it to be used within expression contexts.
Execution Speed Slightly faster because it does not return a status value. Slightly slower due to the overhead of returning a value.
(vii) How to delete a Cookie?
Academic Explanation

Cookies cannot be directly deleted from server-side storage. Instead, the server instructs the client's browser to delete the cookie by using the setcookie() function to set its expiration date to a time in the past.

// Set expiration to 1 hour ago (current Unix timestamp minus 3600 seconds)
setcookie("session_token", "", time() - 3600, "/");

Question 2

2. Static vs. Dynamic Websites & PHP Core Advantages (5+4 Marks)

a) Structural Comparison: Static vs. Dynamic Websites

Websites are categorized based on how their pages are compiled and served to visitors. Below is an academic breakdown of static and dynamic website architectures:

Comparison Parameter Static Websites Dynamic Websites
Content Processing Web pages are stored as pre-built HTML files on the server. The server delivers files directly to the browser without any server-side processing. Web pages are generated on the fly. The server runs scripts (like PHP) to pull data from a database and build the final page before sending it to the browser.
Database Usage Does not use a database database management system (DBMS). Highly integrated with relational databases (e.g., MySQL, PostgreSQL) to store and manage content.
Scalability & Updates Low scalability. Modifying content requires editing the source code of each individual HTML file manually. Highly scalable. Content updates are made in a database or content management system (CMS), instantly updating all related pages.
Technical Requirements Requires minimal server resources. Works on basic hosting environments without special software requirements. Requires more server processing power, database support, and scripting engines (like PHP, Node.js, or Python).
User Experience Displays identical content to all visitors. Ideal for simple informational sites or portfolio pages. Can display personalized content, handle user accounts, manage carts, and provide interactive dashboards.

b) Key Advantages of Using PHP

PHP (Hypertext Preprocessor) is a widely used server-side language that offers several distinct benefits for modern web development:


Question 3

3. HTTP GET vs. POST & Dynamic Form Rendering (4+5 Marks)

a) Differentiate between $_GET and $_POST Methods

In PHP, $_GET and $_POST are superglobal associative arrays used to retrieve user input submitted via HTML forms. They handle and transmit data differently:

Operational Metric $_GET Superglobal Method $_POST Superglobal Method
Data Transport Appends variable parameters directly to the URL string as query parameters (e.g., page.php?user=id). Embeds data inside the body of the HTTP request, leaving the URL address unchanged.
Security Profile Low security. Sensitive data (such as passwords) is exposed in the URL, browser history, and server logs. High security. Data is hidden from the URL and browser history, making it suitable for sensitive transactions.
Payload Capacity Restricted by URL length limits set by web browsers and servers (typically up to ~2,048 characters). Virtually unlimited. Supports sending large datasets and file uploads.
Caching & Bookmarking Can be indexed, cached by browsers, and bookmarked by users. Cannot be cached, indexed, or bookmarked. Reloading the page prompts a re-submission warning.

b) PHP Script: Processing and Displaying Submitted Form Data

This script provides a clean implementation of a contact form. It uses the POST method, validates user input, and securely renders the submitted content on the page.

Form Processing Script (index.php)
<?php
// Initialize output variables
$submittedName = "";
$submittedEmail = "";
$formSubmitted = false;

// Process the form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Retrieve and sanitize inputs to prevent Cross-Site Scripting (XSS)
    $submittedName = htmlspecialchars(trim($_POST['username'] ?? ''));
    $submittedEmail = htmlspecialchars(trim($_POST['email'] ?? ''));

    if (!empty($submittedName) && !empty($submittedEmail)) {
        $formSubmitted = true;
    }
}
?>

<!-- HTML Interface Structure -->
<form action="" method="POST">
    <label for="username">Name:</label>
    <input type="text" id="username" name="username" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="submit">Submit Form</button>
</form>

<?php if ($formSubmitted): ?>
    <div class="key-point">
        <span class="klabel">Submitted Data Overview</span>
        <p><strong>Name:</strong> <?php echo $submittedName; ?></p>
        <p><strong>Email:</strong> <?php echo $submittedEmail; ?></p>
    </div>
<?php endif; ?>

Question 4

4. Documentation via Comments & Variable Scopes (3+6 Marks)

a) Comments in PHP

Comments are non-executable annotations in source code that are ignored by the PHP interpreter. They are used to document code, explain complex logic, and help with debugging.

PHP Comment Syntax Examples
<?php
// 1. Single-Line Comment: Used for quick annotations or one-line explanations.
$activeTaxRate = 0.18;

# 2. Alternative Single-Line Comment: Unix shell-style comment.
$shippingCost = 45.00;

/* 3. Multi-Line Comment Block:
 * Used to document complex algorithms,
 * classes, or to temporarily comment out blocks of code during debugging.
 */
function calculateFinalTotal($price, $tax) {
    return $price + ($price * $tax);
}
?>

b) Accessing Global Variables Inside PHP Functions

In PHP, global variables (variables declared outside of functions) are not automatically accessible inside function scopes due to local isolation. To access them, developers must use one of the following methods:

Method 1: The 'global' Keyword

Declaring a variable as global inside a function imports the external variable into the function's local scope, allowing it to be accessed or modified.

<?php
$appVersion = "v3.1";

function displayVersion() {
    global $appVersion; // Imports global variable
    echo "Active Version: " . $appVersion;
}
?>
Method 2: The $GLOBALS Superglobal Array

PHP automatically stores all global variables in a superglobal associative array named $GLOBALS. Variable names are stored as string keys, allowing them to be accessed directly in any scope.

<?php
$databaseHost = "localhost";

function connectToDB() {
    // Accesses variable via the $GLOBALS array
    echo "Connecting to " . $GLOBALS['databaseHost'];
}
?>

Question 5

5. Associative Array Architectures & File Imports (5+4 Marks)

a) Associative Arrays in PHP

Definition — Associative Array An associative array is a data structure that maps keys to values. Unlike standard indexed arrays that use sequential integers as keys, associative arrays allow developers to use custom strings as keys to represent relationships.
Example: Initializing and Traversing Associative Arrays
<?php
// Initialize an associative array mapping student names to scores
$gradeBook = [
    "Alice" => 92,
    "Bob"   => 85,
    "Clara" => 97
];

// Display individual element value using its string key
echo "Clara's score: " . $gradeBook["Clara"] . "\n";

// Traverse the associative array using a foreach loop
foreach ($gradeBook as $studentName => $scoreValue) {
    echo "Student: $studentName | Grade: $scoreValue \n";
}
?>

b) Structural Difference: include vs. require Statements

PHP uses include and require statements to import and execute files within other scripts. They differ in how they handle missing files:

Comparison Basis include Statement Construct require Statement Construct
Error Level Emitted Emits an E_WARNING if the file is missing or inaccessible. Throws a fatal E_COMPILE_ERROR if the file is missing or contains errors.
Script Execution Flow Non-blocking. The script displays a warning and continues executing subsequent lines of code. Blocking. Script execution stops immediately, preventing any further code from running.
Recommended Use Case Ideal for non-critical layout components, such as headers, footers, or optional design elements. Best for mission-critical logic, database connections, security filters, or configuration parameters.

Question 6

6. Session-Based Database Authentication & script Termination (7+2 Marks)

a) Complete PDO and Session Login System Implementation

This script implements a secure authentication workflow. It takes form input, queries a database table named User containing UserId and Password, and registers an active session if the credentials are valid.

Secure Session Authentication System (login.php)
<?php
// Start session to persist user state
session_start();

// Database connection configuration
$host   = "localhost";
$db     = "auth_vault";
$user   = "db_administrator";
$pass   = "strong_password";
$dsn    = "mysql:host=$host;dbname=$db;charset=utf8mb4";

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
} catch (PDOException $e) {
    die("Database Connection Error: " . $e->getMessage());
}

$errorMessage = "";

// Process form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $inputUser = trim($_POST['userId'] ?? '');
    $inputPass = trim($_POST['password'] ?? '');

    if (!empty($inputUser) && !empty($inputPass)) {
        // Retrieve credentials using prepared statements to prevent SQL injection
        $stmt = $pdo->prepare("SELECT UserId, Password FROM User WHERE UserId = :userid");
        $stmt->execute([':userid' => $inputUser]);
        $userRecord = $stmt->fetch();

        // Verify password (assumes password was hashed using password_hash())
        if ($userRecord && password_verify($inputPass, $userRecord['Password'])) {
            // Save authenticated state to session variables
            $_SESSION['authenticated_user'] = $userRecord['UserId'];
            $_SESSION['login_time'] = time();

            // Redirect user to the secure dashboard page
            header("Location: dashboard.php");
            exit();
        } else {
            $errorMessage = "Invalid User-ID or Password.";
        }
    } else {
        $errorMessage = "Please fill in all credentials.";
    }
}
?>

<!-- HTML Authentication Interface -->
<form action="" method="POST">
    <h3>Secure Login Portal</h3>
    <?php if (!empty($errorMessage)): ?>
        <div class="warning"><span class="wlabel">Error</span><?php echo $errorMessage; ?></div>
    <?php endif; ?>

    <label for="userId">User-ID:</label>
    <input type="text" id="userId" name="userId" required>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>

    <button type="submit">Login</button>
</form>

b) Use of the die() Function in PHP

Formal Definition — die() The die() function (which is an alias of the exit() language construct) immediately terminates the execution of the current script. It can optionally accept a string message or an integer status code to output before exiting.

Primary Use Cases:


Question 7

7. File System Streams & HTTP Header Redirection (6+3 Marks)

a) PHP Script: Opening and Displaying File Content Securely

This script securely opens a text file named system_logs.txt in read-only mode, processes its contents line-by-line using a loop, and then releases the file resource.

Read-Only File Handler (reader.php)
<?php
$targetFile = "system_logs.txt";

// Verify file existence and readability before opening
if (file_exists($targetFile) && is_readable($targetFile)) {
    // Open the file in read-only mode ('r')
    $fileHandle = fopen($targetFile, "r");

    if ($fileHandle !== false) {
        echo "<h4>Displaying Content of File: " . htmlspecialchars($targetFile) . "</h4>";
        echo "<pre style='background: var(--paper-2); padding: 1rem; border-radius: 4px;'>";

        // Loop through the file line by line until the end-of-file (feof) is reached
        while (!feof($fileHandle)) {
            $lineContent = fgets($fileHandle);
            // Sanitize output to prevent cross-site scripting (XSS)
            echo htmlspecialchars($lineContent);
        }

        echo "</pre>";

        // Close the file stream to release the system resource
        fclose($fileHandle);
    } else {
        echo "Unable to open the specified file stream.";
    }
} else {
    echo "The file does not exist or is not readable by the system.";
}
?>

b) HTTP Header Redirection in PHP

Web page redirection is performed by sending a raw HTTP Location header to the client's browser. This is done using the header() function.

Critical Redirection Rule The header() function must be called before any actual output (HTML tags, spaces, or blank lines) is sent to the browser. Sending output before calling header() triggers a "Headers already sent" warning and breaks the redirect.
Redirect Script Implementation
<?php
// 1. Send the HTTP Location redirect header
header("Location: https://www.universityportal.edu/dashboard");

// 2. Always follow a redirect header with exit() or die()
// This prevents the server from executing subsequent code for unauthorized clients.
exit();
?>

Question 8

8. MVC Frameworks & CodeIgniter Request Lifecycle (2+7 Marks)

a) What is CodeIgniter?

Definition — CodeIgniter CodeIgniter is an open-source, lightweight PHP application framework built on the Model-View-Controller (MVC) design pattern. It is designed for developers who need a simple, fast, and elegant toolkit to build full-featured web applications, offering excellent performance with a minimal footprint and near-zero server configuration.

b) CodeIgniter Request Lifecycle Architecture

The internal request lifecycle of CodeIgniter defines how an incoming HTTP request is routed, filtered, processed, and returned to the client. This centralized process ensures consistent performance and secure access controls.

CodeIgniter Internal Architectural Request Lifecycle

index.php Routing Security Controller Cache Check View / Output

The sequential execution lifecycle consists of the following steps:

  1. Entry Point (index.php): All incoming client requests are routed through index.php, which initializes core framework variables and loads base configuration classes.
  2. Routing Engine Check: The Routing module parses the request URL to determine which Controller and method should process it. It first checks the Caching Engine: if a cached copy of the page exists, it is sent directly to the client, bypassing the standard controller execution for optimal speed.
  3. Security Filter Inspection: Before loading the Controller, the request is passed through built-in security filters. These inspect inputs for threats and apply defenses against CSRF, SQL Injection, and XSS.
  4. Controller Execution: The Controller loads and initializes Models (database resources), processes application logic, and binds the structured datasets to Views.
  5. View Rendering & Output: The finalized View generates the final HTML output, which is written to the Output class buffer and sent back to the client's browser.
High-Yield Exam Core Points

Most Important Exam Points

Key takeaways and common student traps to keep in mind for descriptive questions.

Operators & Logic

  • == checks values; === checks values and types
  • print returns 1; echo has no return value
  • die() exits execution and outputs a message
  • foreach is optimized for associative arrays
  • Use static scope to persist variables locally

Server-Side Architecture

  • Apache uses htaccess for folder configuration
  • require halts scripts on file read errors
  • include yields a warning and continues executing
  • Redirect headers require exit() to halt processes
  • CodeIgniter routes requests through index.php
Important Exam Questions

Selected Previous-Year Practice Questions

Theory — July 2023

Explain why the use of raw SQL concatenation is dangerous and show how prepared statements prevent security risks.

→ Prepared statements separate query logic from input data, compile the query on the database first, and treat user input strictly as parameters instead of executable code.

Procedural — July 2023

Differentiate between the include and require statements. Which statement is preferred for database connections?

→ require is preferred for database connections because it throws a fatal error and halts the script if the file is missing, protecting the application from executing with missing dependencies.

Quick Revision Matrix

Last-Minute Revision Sheet

Operators & Echo

  • == Comparison with type coercion
  • === Strict identity comparison
  • echo: supports multiple arguments
  • print: returns 1, single argument

Data Transport

  • $_GET: parameters exposed in URL
  • $_POST: data hidden inside request body
  • $_POST: secure and supports files
  • $_GET: indexable and bookmarkable

State Handling

  • Cookie: client browser text storage
  • Session: high-security server files
  • Delete Cookie: set time to the past
  • Close Session: session_unset()

MVC Request Lifecycle

  • index.php acts as application entry
  • Router parses requested url string
  • Cache bypasses processing if hit
  • Controller coordinates model & views

Web Designing Past Paper Solutions · Hand-crafted Exam Notes · Aligned with July 2023 Syllabus Guidelines.