University Examination Solutions · Computer Applications / IT

Web Designing

May 2025 Past-Paper Solutions & Academic Reference Notes

PHP & MySQL CodeIgniter MVC SQL Injection Mitigation State Management PDO Abstraction AJAX & CMS Systems

Table of Contents

  1. Group A: Multiple Choice Questions & Analytical Explanations
  2. Question 2: PHP Comments, CodeIgniter Intro, & PHP Advantages
  3. Question 3: SQL Injection Mechanism & Defense-in-Depth Prevention
  4. Question 4: PHP Array Architectures & String Splitting Implementation
  5. Question 5: State Persistence via Sessions & E-Commerce Foundations
  6. Question 6: Cookie Management & Session vs. Cookie Comparison
  7. Question 7: RDBMS Rationale, HTTP Methods, & Secure Form Processing
  8. Question 8: Dynamic Web Architectures, PHP Imports, & SQL Sorting
  9. Question 9: Web Framework Demands & CodeIgniter MVC Architecture
  10. Question 10: Scholarly Short Notes (AJAX, CMS, and PDO)
  11. High-Yield Exam Core Points
  12. Quick Revision Matrix
Group A - MCQs

Group A: Multiple Choice Questions (2 × 10 = 20 Marks)

To secure full marks in Group A, candidates must state the correct option and provide a concise, theoretically sound justification citing standard PHP/MySQL mechanics.

i) Which of the following is not a variable scope in PHP?
a. Extern    b. Local    c. Static    d. Global Correct Option: a. Extern
Academic Explanation PHP supports three main variable scopes: local (variables declared inside a function), global (variables declared outside functions or accessed via the global keyword), and static (variables that preserve their value across function calls). The term extern is a storage class specifier used in compiled languages like C/C++ to reference variables declared in external translation units; it has no syntactic standing in PHP.
ii) Which of the following is used to display the output in PHP?
a. echo    b. write    c. print    d. Both (a) and (c) Correct Option: d. Both (a) and (c)
Academic Explanation In PHP, both echo and print are language constructs used to output strings to the client-side buffer. echo can accept multiple parameters and does not return a value, while print accepts only a single parameter and always returns 1. The keyword write is not a native PHP output construct.
iii) Which of the following is the use of strlen() function in PHP?
a. The strlen() function returns the type of string
b. The strlen() function returns the length of string
c. The strlen() function returns the value of string
d. The strlen() function returns both value and type of string Correct Option: b. The strlen() function returns the length of string
Academic Explanation The built-in function strlen(string $string): int evaluates the argument string and returns its total length in bytes (characters, in single-byte encodings). For multi-byte characters, mb_strlen() is used instead.
iv) Which of the following function is used to find files in PHP?
a. glob()    b. fold()    c. file()    d. None of the above Correct Option: a. glob()
Academic Explanation The glob() function searches for all pathnames matching a specified pattern according to the rules used by the shell (e.g., wildcard matching). Conversely, file() reads an entire file's contents into an indexed array, and fold() is not a standard file-handling function in PHP.
v) Which of the following function is used to sort an array in descending order?
a. sort()    b. asort()    c. dsort()    d. rsort() Correct Option: rsort()
Academic Explanation The rsort() function sorts an indexed array in-place in descending alphabetical or numerical order. sort() is used for ascending sorting; asort() is for associative arrays to maintain index association in ascending order; and dsort() is syntactically invalid in native PHP.
vi) Which of the following is the correct way to create an array in PHP?
a. $season = array["summer", "winter", "spring", "autumn"];
b. $season = array("summer", "winter", "spring", "autumn");
c. $season = "summer", "winter", "spring", "autumn";
d. All of the above Correct Option: b. $season = array("summer", "winter", "spring", "autumn");
Academic Explanation Standard PHP constructs arrays using either the traditional array(...) language construct or the modern short array syntax [...] (available since PHP 5.4). Declaring array[...] (as in option a) is a syntactic error as brackets are used directly for assignment/retrieval, not appended to the constructor name.
vii) Which PHP function determines the last access time of a file?
a. filetime()    b. fileatime()    c. filectime()    d. None of the above Correct Option: b. fileatime()
Academic Explanation The fileatime(string $filename): int|false function returns the Unix timestamp when the file was last accessed (read). For comparison, filectime() yields the inode change time (permissions, owner, etc.), and filemtime() returns the file's content modification time.
viii) Which of the following is a correct PHP tag?
a. <?php ?>    b. <php>    c. <?>    d. <%%> Correct Option: a. <?php ?>
Academic Explanation The standard XML-style tags <?php ... ?> are universally supported and are the recommended tags for embedding PHP within HTML files. Short tags <? ... ?> and ASP-style tags <% ... %> are deprecated or fully removed from modern PHP releases.
ix) What will be the output of the following program?
<?php $a = array(16,5,2); echo array_product($a); ?>
a. 160    b. 1652    c. 80    d. 32 Correct Option: a. 160
Academic Explanation The built-in function array_product(array $array): int|float calculates and returns the product of all numerical elements present in the provided array. Thus: $16 \times 5 \times 2 = 80 \times 2 = 160$.
x) Which of the following options tells MySQL to ask for entering the password?
a. -u    b. -p    c. -h    d. -e Correct Option: b. -p
Academic Explanation When initializing a MySQL CLI connection, the -p flag signals the command-line utility to prompt the operator for the user password in a masked, secure manner. The option -u declares the username, -h specifies the database host server, and -e executes an inline SQL query string directly.
xi) Which of the following best describes the purpose of MySQL?
a. To store and retrieve data    b. To create user interfaces    c. To build websites    d. To manage file systems Correct Option: a. To store and retrieve data
Academic Explanation MySQL is an open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL) to organize, store, manipulate, and retrieve data from structured tables containing defined relationships.
xii) What is the role of "CONSTRAINTS" in defining a table in MySQL?
a. Declaring Foreign Key    b. Declaring Primary Key    c. Restrictions on columns    d. All of the mentioned Correct Option: d. All of the mentioned
Academic Explanation SQL constraints (e.g., PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, CHECK, DEFAULT) are declarations assigned to columns or tables to enforce structural rules and data integrity. They prevent invalid or orphaned entries from being written to the database.
xiii) Which of the following is a popular front-end framework for building user interfaces in JavaScript?
a. Django    b. Angular    c. Flask    d. Node.js Correct Option: b. Angular
Academic Explanation Angular is a robust, Google-engineered front-end SPA (Single Page Application) framework written in TypeScript/JavaScript. Django and Flask are Python-based back-end frameworks, while Node.js is a server-side JavaScript runtime environment.
xiv) Which HTML tag is used to create an ordered list in a webpage?
a. <ol>    b. <ul>    c. <li>    d. <ol> and <ul> Correct Option: a. <ol>
Academic Explanation The <ol> element is used to generate an ordered, sequential (typically numbered) list. Inside this container, list items are declared using <li> tags. The <ul> tag creates unordered (bulleted) lists.
xv) What are tables in web programming?
a. Display information which are already accessed by the user
b. Containing more number of rows than columns
c. To only store data to be accessed later by the user
d. Display information in rows and columns used to display all manner of data that fits in a grid Correct Option: d. Display information in rows and columns used to display all manner of data that fits in a grid
Academic Explanation The HTML <table> tag defines a multidimensional interface designed to structure data into structured cells, columns (<td>/<th>), and rows (<tr>) for clean tabular display.

Question 2

2. PHP Comments, CodeIgniter Intro, & PHP Advantages (3+2+3 Marks)

a) Comments in PHP

Comments in server-side scripting are block lines ignored by the interpreter engine, allowing developers to annotate, document, and debug source code without affecting runtime execution.

Example: Comprehensive Comment Styles in PHP
<?php
// 1. Single-Line Comment: Used for quick annotations.
$totalPrice = 500; # Alternative Shell/Perl style single-line comment

/* * 2. Multi-Line Comment:
 * Ideal for detailing complex algorithm logic,
 * documenting class behaviors, or disabling blocks of code.
 */
function processTransaction($amount) {
    return $amount * 1.18; // Adds a standard 18% tax
}
?>

b) What is CodeIgniter?

Definition — CodeIgniter CodeIgniter is a lightweight, open-source PHP web application framework structured around the Model-View-Controller (MVC) architectural pattern. It is designed to enable rapid development with a minimal footprint, providing pre-packaged libraries, database abstractions, helper utilities, and secure inputs to replace redundant boilerplate coding.

c) Key Advantages of Using PHP


Question 3

3. SQL Injection Attacks & Defenses (6+2 Marks)

a) Mechanism of SQL Injection (SQLi)

Definition — SQL Injection (SQLi) An exploit technique where an attacker manipulates backend database queries by injecting malicious SQL statements into user input fields (such as form inputs, query parameters, or headers) which are subsequently concatenated directly into a dynamic SQL query without proper sanitization or parameterization.

Consider an unsafe user authentication check that dynamically concatenates values:

Unsafe Dynamic Concatenation Query Pattern SELECT * FROM users WHERE username = '$user_input' AND password = '$password_input';

If an attacker inputs admin' OR '1'='1 into the username field, the compiled query processed by the database engine becomes:

Injected Query Execution Logic SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = '...';

Because the condition '1'='1' is always true, the SQL command bypasses authentication checks and retrieves user records, often exposing sensitive administrator controls.

b) Prevention Strategies

  1. Prepared Statements (Parametrized Queries): Pre-compiles the query on the database server. Inputs are treated strictly as parameters, preventing the interpreter from treating user input as executable SQL commands.
  2. Input Validation & Sanitization: Implement strict type casting and filter incoming inputs (e.g., ensuring numeric IDs are cast using (int) or validated using filter_var()).
PHP PDO Safe Query Standard (Prepared Statements)
<?php
// Secure PDO Implementation preventing SQL Injection
$stmt = $pdo->prepare('SELECT id, username FROM users WHERE email = :email');
$stmt->execute(['email' => $userInputEmail]);
$userData = $stmt->fetch();
?>

Question 4

4. PHP Array Types & String Splitting (4+4 Marks)

a) Types of Arrays in PHP

1. Indexed Arrays

Arrays with numeric indexes, automatically assigned starting from zero unless specified.

$color = ["Red", "Green", "Blue"];
2. Associative Arrays

Arrays that use custom, developer-defined named strings as key mappings to values.

$ages = ["John" => 25, "Sara" => 31];
3. Multidimensional Arrays

Arrays containing one or more nested arrays within their elements.

$matrix = [ [1, 2], [3, 4] ];

b) Splitting a String in PHP

PHP provides native functions to divide strings based on character boundaries (str_split()) or target delimiters (explode()).

Example: Splitting Strings via PHP
<?php
$inputString = "Hypertext,PreProcessor,Server,Side";

// Split string by a specific delimiter using explode()
$arrayData = explode(",", $inputString);
print_r($arrayData);
/* Output:
Array (
    [0] => Hypertext
    [1] => PreProcessor
    [2] => Server
    [3] => Side
) */

// Split string into 4-character chunks using str_split()
$chunks = str_split("PHPENGINE", 3);
print_r($chunks);
/* Output:
Array (
    [0] => PHP
    [1] => ENG
    [2] => INE
) */
?>

Question 5

5. PHP Sessions & E-Commerce Fundamentals (2+3+3 Marks)

a) What is a PHP Session?

Definition — PHP Session A session is a server-side state-management mechanism used to preserve data across multiple page requests. Unlike stateless HTTP requests, sessions store variable values securely on the web server, associating them with a unique Session ID stored in a client-side cookie (usually named PHPSESSID).
PHP Script: Securely Erasing Session Variables
<?php
// Step 1: Initialize/join the active session.
session_start();

// Step 2: Unset all active global session variables in memory.
session_unset();

// Step 3: Completely destroy the physical session file/data on the server storage.
session_destroy();

// Step 4: Optional: Overwrite cookie reference client side
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

echo "All session variables successfully erased and destroyed.";
?>

b) What is E-Commerce?

Electronic Commerce (E-Commerce) refers to the purchase, sale, exchange, and transaction of goods, services, or data over electronic networks, primarily the internet.

Classification Model Definition Description Practical Real-World Example
B2C (Business-to-Consumer) An enterprise markets and sells goods directly to private individual buyers. An online bookstore or retail storefront selling directly to consumers.
B2B (Business-to-Business) Transactions conducted between commercial corporations (e.g., manufacturer to wholesaler). Industrial bulk supply marketplaces.
C2C (Consumer-to-Consumer) Individuals use third-party platforms to sell items directly to other consumers. Online peer-to-peer auction and classifieds portals.

Question 6

6. Cookies & State Comparison in PHP (3+3 Marks)

a) What is a Cookie?

Definition — Cookie A cookie is a small text file sent from a web server and stored locally on the user's browser. It allows the server to recognize the client's device, track user activity, and store persistent configurations (like dark mode or language preferences) across web requests.
PHP Script: Deleting a Cookie Named "username"
<?php
// To delete a cookie, set its expiration date to a time in the past.
// The name, path, and domain parameters must match the original configuration.
setcookie("username", "", time() - 3600, "/");

echo "Cookie 'username' has been marked for deletion.";
?>

b) Structural Comparison: Session vs. Cookie

Feature Metric PHP Session State Client-Side Cookie
Storage Location Stored securely on the web server filesystem or database. Stored locally in the client browser's sandbox directory.
Security Profile High security. Data is not exposed to client-side manipulation. Low security. Vulnerable to interception and local client modifications.
Capacity Limit Virtually unlimited (restricted only by server storage capacity). Highly restricted (typically ~4KB limit per cookie domain).
Bandwidth Overhead Low. Only the Session ID cookie is transmitted in header payloads. High. The entire cookie payload is transmitted with every HTTP request.

Question 7

7. MySQL Integrations, HTTP Methods, & DB Operations (2+2+4 Marks)

a) MySQL Usage with PHP and HTTP Method Differences

Why MySQL with PHP? MySQL is highly integrated with PHP due to its open-source synergy (historically forming the foundation of the LAMP/WAMP stack). It provides native extensions, object-oriented APIs like PDO, and scalable storage mechanisms designed for high-concurrency dynamic web applications.

Operational Parameter HTTP GET Request Method HTTP POST Request Method
Data Visibility Appends payload variables in plaintext directly to the URL string. Packages payload data inside the body of the HTTP request.
Security Rating Not secure. Payload variables remain in browser history and logs. Secure for transport. Recommended for sensitive inputs (passwords).
Payload Capacity Restricted by URL length limitations (typically ~2048 characters). Virtually unlimited. Supports file uploads and binary streams.
Caching & Bookmarks Can be indexed, cached, bookmarked, and reloaded. Cannot be bookmarked or cached by standard web browsers.

b) Form Data Insertion Script (Secure PDO Standard)

This script securely handles incoming POST data and uses prepared statements to write to the database, preventing SQL injection vulnerabilities.

PHP Script: Database Form Insertion Engine
<?php
// Database configuration parameters
$host    = 'localhost';
$dbName  = 'user_registry';
$dbUser  = 'root';
$dbPass  = 'secure_password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$dbName;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    // Establish connection to database via PDO
    $pdo = new PDO($dsn, $dbUser, $dbPass, $options);
} catch (\PDOException $e) {
    die("Database Connection Failure: " . $e->getMessage());
}

// Process incoming POST form submission safely
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $fullName = trim($_POST['fullName'] ?? '');
    $userEmail = trim($_POST['userEmail'] ?? '');

    // Validate inputs
    if (!empty($fullName) && filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
        // Prepare the SQL insert statement
        $sql = "INSERT INTO subscribers (name, email) VALUES (:name, :email)";
        $stmt = $pdo->prepare($sql);

        try {
            // Execute the prepared statement with parameter binding
            $stmt->execute([
                ':name'  => $fullName,
                ':email' => $userEmail
            ]);
            echo "Registration Completed Successfully.";
        } catch (\PDOException $e) {
            echo "Error Inserting Data: " . $e->getMessage();
        }
    } else {
        echo "Invalid Form Input Data.";
    }
}
?>

Question 8

8. Dynamic Web Architectures, Imports, & Query Sorting (2+2+4 Marks)

a) Dynamic Websites & PHP File Imports

Definition — Dynamic Website A dynamic website is an interactive site that generates web page content in real-time. It retrieves data from a backend database on demand and displays it according to template layouts customized to individual user profiles, browser types, or user interactions.
Comparison Basis include Language Construct require Language Construct
Error Handling Emits an E_WARNING if the file is missing and continues script execution. Throws a fatal E_COMPILE_ERROR and halts script execution immediately.
Use Case Used for non-critical elements (such as footers, sidebars, or optional UI blocks). Used for mission-critical core logic, config files, or database connections.

b) The MySQL ORDER BY Clause

The ORDER BY clause sorts the returned records in ascending (ASC) or descending (DESC) order based on one or more columns.

Example: SQL Sorting Operation
-- Sort products by price in descending order, and secondary sort by name ascending
SELECT id, name, price, stock
FROM catalog_items
WHERE stock > 0
ORDER BY price DESC, name ASC;

Question 9

9. Framework Demands & CodeIgniter MVC Architecture (2+1+5 Marks)

a) Why Use a PHP Framework?

Enterprise applications rarely rely on raw "vanilla" procedural PHP. Frameworks provide several benefits:

Popular Frameworks: Laravel, CodeIgniter, Symfony, Yii, and CakePHP.

b) The CodeIgniter MVC Paradigm

CodeIgniter uses a clean implementation of the Model-View-Controller pattern, enforcing a separation between business logic, database queries, and the presentation layer.

CodeIgniter MVC Architectural Request Lifecycle

HTTP Client Controller Model (Data) View (UI)
The Model

The Model manages the database transactions, schema relationships, and core business rules of the application. It runs validation queries and feeds structured datasets to the Controller.

The Controller

The Controller acts as the central coordinator. It receives incoming HTTP routing requests, processes client input parameters, queries the appropriate Model for data, and loads the corresponding View.

The View

The View displays the UI presented to the end-user. It receives structured, unformatted variables from the Controller and renders them into clean HTML, CSS, and client-side JavaScript.


Question 10

10. Scholarly Short Notes (Answer any two: 4 + 4 Marks)

a) AJAX (Asynchronous JavaScript And XML)

AJAX is a development technique used to construct fast, dynamic user interfaces. It enables web pages to update content asynchronously by exchanging data with a backend server in the background, avoiding the need to reload the entire page.

b) Content Management System (CMS)

A CMS is a software application or suite of tools that allows users to create, organize, edit, and publish digital web content without needing to write backend source code manually.

c) PDO (PHP Data Objects)

PDO is a lightweight, consistent database abstraction layer for PHP. It defines a uniform, object-oriented API for interacting with databases, allowing developers to switch the underlying storage system (e.g., from MySQL to PostgreSQL or SQLite) without major code rewrites.

High-Yield Exam Core Points

Most Important Exam Points

Use these verified technical insights to secure maximum marks in descriptive questions.

Security Foundations

  • PDO Prepared Statements prevent SQLi
  • Session state stored strictly on Server
  • Cookies stored client-side in browser
  • Sanitize user inputs with filter_var()
  • Never use raw unescaped POST inputs

PHP & MySQL Core Functions

  • session_start() must run first
  • setcookie() parameters set time()
  • explode() converts string to array
  • rsort() sorts values descending
  • ORDER BY keyword sorts query rows
Quick Revision Matrix

Last-Minute Revision Sheet

Scope & Variables

  • Local scope: inside functions
  • Global scope: keyword lookup
  • Static scope: preserves values
  • No extern scope in PHP

Array Structures

  • Indexed: numeric keys (0+)
  • Associative: string key value
  • Multidimensional: nested arrays
  • Create using array() or []

State Handling

  • Session: high-security server files
  • Cookie: client browser strings
  • Session end: session_destroy()
  • Cookie delete: set to past time

Exploits & Defenses

  • SQLi: dynamic string injection
  • Cause: concatenation of inputs
  • Fix: PDO Prepared Statements
  • Benefit: parameters compiled separately

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