University Examination Solutions · Computer Applications / IT
Table of Contents
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.
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.
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.
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.
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.
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.
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.
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.
<?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.
<?php $a = array(16,5,2); echo array_product($a); ?>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$.
-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.
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.
<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.
<table> tag defines a multidimensional interface designed to structure data into structured cells, columns (<td>/<th>), and rows (<tr>) for clean tabular display.
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.
<?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
}
?>
Consider an unsafe user authentication check that dynamically concatenates values:
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:
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.
(int) or validated using filter_var()).<?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();
?>
Arrays with numeric indexes, automatically assigned starting from zero unless specified.
$color = ["Red", "Green", "Blue"];
Arrays that use custom, developer-defined named strings as key mappings to values.
$ages = ["John" => 25, "Sara" => 31];
Arrays containing one or more nested arrays within their elements.
$matrix = [ [1, 2], [3, 4] ];
PHP provides native functions to divide strings based on character boundaries (str_split()) or target delimiters (explode()).
<?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
) */
?>
PHPSESSID).
<?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.";
?>
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. |
<?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.";
?>
| 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. |
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. |
This script securely handles incoming POST data and uses prepared statements to write to the database, preventing SQL injection vulnerabilities.
<?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.";
}
}
?>
| 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. |
The ORDER BY clause sorts the returned records in ascending (ASC) or descending (DESC) order based on one or more columns.
-- 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;
Enterprise applications rarely rely on raw "vanilla" procedural PHP. Frameworks provide several benefits:
Popular Frameworks: Laravel, CodeIgniter, Symfony, Yii, and CakePHP.
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
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 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 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.
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.
Fetch API or XMLHttpRequest to send background requests and dynamically render the returned JSON/XML payloads using DOM manipulation.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.
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.
PDOException), improving error logging and security compared to older procedural drivers like mysql_*.Use these verified technical insights to secure maximum marks in descriptive questions.
Security Foundations
PHP & MySQL Core Functions
Web Designing Past Paper Solutions · Hand-crafted Exam Notes · Aligned with May 2025 Syllabus Guidelines.