University Examination Solutions · Computer Applications / IT
Table of Contents
To secure maximum marks in Group A, candidates must provide clear explanations along with correct syntaxes and standard architectural rationale.
Dynamic content allows web pages to update in real-time without manual design changes. This approach has several key benefits:
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 |
The difference between these two iteration statements lies in how they navigate memory collections:
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]; }
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"; }
Apache HTTP Server is a widely used web server characterized by the following structural advantages:
mod_rewrite for clean URLs, mod_ssl for encryption)..htaccess files, enabling individual web applications to override global server settings without requiring server restarts.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.
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. |
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, "/");
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. |
PHP (Hypertext Preprocessor) is a widely used server-side language that offers several distinct benefits for modern web development:
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. |
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.
<?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; ?>
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
// 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);
}
?>
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:
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;
}
?>
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'];
}
?>
<?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";
}
?>
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. |
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.
<?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>
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:
$conn = mysqli_connect(...) or die("Failed to connect to database.");
header("Location: login.php"); die();
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.
<?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.";
}
?>
Web page redirection is performed by sending a raw HTTP Location header to the client's browser. This is done using the header() function.
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.
<?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();
?>
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
The sequential execution lifecycle consists of the following steps:
index.php, which initializes core framework variables and loads base configuration classes.Key takeaways and common student traps to keep in mind for descriptive questions.
Operators & Logic
Server-Side Architecture
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.
Web Designing Past Paper Solutions · Hand-crafted Exam Notes · Aligned with July 2023 Syllabus Guidelines.