CST463 Web Programming - Answer Key
CST463 Web Programming - Answer Key
April 2025 Examination
Subject: Web Programming (CST463)
Institution: APJ Abdul Kalam Technological University
Degree: B.Tech 7th Semester (S,FE)
Exam Date: April 2025
Scheme: 2019 Scheme
Total Marks: 100
Duration: 3 Hours
PART A (Short Answer Questions)
Answer all questions, each carries 3 marks
Question 1 (3 marks)
List out the difference between HTTP GET and POST requests.
Answer:
HTTP GET and POST are two common HTTP methods used to send data between client and server, but they differ in how data is transmitted and their use cases.
Key Differences:
| Aspect | GET | POST |
|---|---|---|
| Data Location | Data sent in URL as query parameters (e.g., page.php?name=John&age=25) |
Data sent in HTTP request body (not visible in URL) |
| Security | Less secure - data visible in URL, browser history, and server logs | More secure - data hidden from URL and browser history |
| Data Length | Limited by URL length (~2048 characters in most browsers) | No practical limit - can send large amounts of data |
| Caching | Can be cached by browser | Not cached by default |
| Bookmarking | Can be bookmarked (URL contains all data) | Cannot be bookmarked meaningfully |
| Use Case | Retrieving data, search queries, filtering | Submitting forms, uploading files, modifying server data |
| Idempotent | Yes - multiple identical requests have same effect | No - multiple requests may have different effects |
Example:
<!-- GET Request -->
<form method="GET" action="search.php">
<input type="text" name="query">
<button type="submit">Search</button>
</form>
<!-- URL becomes: search.php?query=userInput -->
<!-- POST Request -->
<form method="POST" action="register.php">
<input type="password" name="password">
<button type="submit">Register</button>
</form>
<!-- Password sent securely in request body -->
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTTP GET method explanation │ 1.5 marks │
│ - Data location (URL parameters) │ │
│ - Security aspects │ │
│ - Data length limitations │ │
│ - Caching and bookmarking behavior │ │
│ - Use cases and idempotent nature │ │
│ │ │
│ 2. HTTP POST method explanation │ 1.5 marks │
│ - Data location (request body) │ │
│ - Security advantages │ │
│ - No data length limitations │ │
│ - Caching behavior │ │
│ - Use cases and non-idempotent nature │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (1.5 + 1.5)
Question 2 (3 marks)
How are images used as hyperlinks? Give example.
Answer:
Images can be used as hyperlinks by wrapping an <img> tag inside an <a> (anchor) tag. When users click on the image, they are redirected to the URL specified in the href attribute of the anchor tag.
Syntax:
<a href="URL">
<img src="image-path" alt="description">
</a>
Key Points:
- The
<img>tag is nested inside the<a>tag - The
hrefattribute specifies the destination URL - The
altattribute provides alternative text for accessibility - By default, linked images have a border; use CSS to remove it if needed
Example:
<!-- Image as hyperlink to homepage -->
<a href="https://www.example.com">
<img src="logo.png" alt="Company Logo" width="200" height="100">
</a>
<!-- Image linking to another page with no border -->
<a href="products.html">
<img src="products-icon.png" alt="View Products" style="border: none;">
</a>
<!-- Image opening in new tab -->
<a href="gallery.html" target="_blank">
<img src="gallery-thumb.jpg" alt="Photo Gallery">
</a>
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Concept explanation │ 1.5 marks │
│ - How to wrap <img> inside <a> tag │ │
│ - Syntax structure │ │
│ - Key attributes (href, src, alt) │ │
│ - Additional points (border, accessibility) │ │
│ │ │
│ 2. Examples with code │ 1.5 marks │
│ - Basic image hyperlink │ │
│ - Image with styling (border removal) │ │
│ - Image opening in new tab │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (1.5 + 1.5)
Question 3 (3 marks)
Discuss the components of the box model in CSS.
Answer:
The CSS box model is a fundamental concept that defines how elements are rendered on a web page. Every HTML element is treated as a rectangular box consisting of four components.
Components of the Box Model:
- Content - The actual content of the element (text, images, etc.)
- Padding - Transparent space between content and border; creates internal spacing
- Border - A line surrounding the padding and content
- Margin - Transparent space outside the border; creates external spacing between elements
Visual Representation:
┌─────────────────────── Margin ───────────────────────┐
│ ┌────────────────────── Border ─────────────────┐ │
│ │ ┌──────────────────── Padding ──────────┐ │ │
│ │ │ │ │ │
│ │ │ Content Area │ │ │
│ │ │ │ │ │
│ │ └────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────┘
Example:
div {
width: 300px; /* Content width */
height: 200px; /* Content height */
padding: 20px; /* Space inside border */
border: 5px solid black; /* Border around padding */
margin: 15px; /* Space outside border */
}
/* Total width = margin-left + border-left + padding-left + width + padding-right + border-right + margin-right */
/* Total width = 15 + 5 + 20 + 300 + 20 + 5 + 15 = 380px */
Note: Use box-sizing: border-box; to include padding and border in the element's total width and height.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Four components explanation │ 2 marks │
│ - Content (0.5 marks) │ │
│ - Padding (0.5 marks) │ │
│ - Border (0.5 marks) │ │
│ - Margin (0.5 marks) │ │
│ │ │
│ 2. Visual representation/diagram │ 0.5 marks │
│ - ASCII diagram showing nested structure │ │
│ │ │
│ 3. CSS example with calculation │ 0.5 marks │
│ - Code example │ │
│ - Total width calculation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Components + Diagram + Example
Question 4 (3 marks)
What are the various ways of declaring arrays in JavaScript?
Answer:
JavaScript provides multiple ways to declare and initialize arrays. Arrays in JavaScript are dynamic and can hold elements of different data types.
Methods of Declaring Arrays:
-
Using Array Literal (Most Common)
let fruits = ["Apple", "Banana", "Orange"]; let empty = []; -
Using Array Constructor
let numbers = new Array(10, 20, 30); let emptyArray = new Array(); let fixedSize = new Array(5); // Creates array with 5 empty slots -
Using Array.of() Method
let items = Array.of(1, 2, 3, 4, 5); let single = Array.of(7); // Creates array [7], not array with 7 empty slots -
Using Array.from() Method
let str = "Hello"; let chars = Array.from(str); // ["H", "e", "l", "l", "o"] let range = Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4]
Examples:
// Mixed data types
let mixed = [1, "text", true, null, {name: "John"}];
// Multidimensional array
let matrix = [[1, 2], [3, 4], [5, 6]];
// Array with dynamic values
let squares = Array.from({length: 5}, (v, i) => i * i); // [0, 1, 4, 9, 16]
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Array Literal method │ 0.75 marks │
│ - Syntax and examples │ │
│ │ │
│ 2. Array Constructor method │ 0.75 marks │
│ - new Array() with examples │ │
│ │ │
│ 3. Array.of() method │ 0.75 marks │
│ - Syntax and usage example │ │
│ │ │
│ 4. Array.from() method │ 0.75 marks │
│ - Syntax and conversion examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Equal Components (0.75 × 4)
Question 5 (3 marks)
How does type casting convert between data types in PHP?
Answer:
Type casting in PHP converts a variable from one data type to another. PHP supports both automatic (implicit) and manual (explicit) type conversion.
Explicit Type Casting Syntax:
(type) $variable
Available Type Casts:
- (int) or (integer) - Convert to integer
- (float) or (double) or (real) - Convert to float
- (string) - Convert to string
- (bool) or (boolean) - Convert to boolean
- (array) - Convert to array
- (object) - Convert to object
Examples:
<?php
// String to Integer
$str = "123";
$num = (int)$str; // 123
echo $num + 10; // 133
// Float to Integer (truncates decimal)
$price = 99.99;
$rounded = (int)$price; // 99
// Integer to String
$count = 50;
$text = (string)$count; // "50"
// To Boolean
$zero = (bool)0; // false
$nonZero = (bool)5; // true
$emptyStr = (bool)""; // false
$str = (bool)"hello"; // true
// String to Float
$amount = "45.67";
$value = (float)$amount; // 45.67
// Array to Object
$arr = array("name" => "John", "age" => 25);
$obj = (object)$arr;
echo $obj->name; // John
?>
Key Points:
- Type casting does not change the original variable
- Invalid conversions may result in 0, false, or empty values
- PHP also has type conversion functions:
intval(),floatval(),strval(),boolval()
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Concept explanation and syntax │ 1.5 marks │
│ - Definition of type casting │ │
│ - Syntax: (type) $variable │ │
│ - List of available type casts │ │
│ │ │
│ 2. Examples demonstrating type conversions │ 1.5 marks │
│ - String to Integer │ │
│ - Float to Integer │ │
│ - Integer to String │ │
│ - To Boolean │ │
│ - String to Float │ │
│ - Array to Object │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (1.5 + 1.5)
Question 6 (3 marks)
Differentiate implode and explode functions in PHP with examples.
Answer:
implode() and explode() are complementary PHP string functions that convert between arrays and strings.
Key Differences:
| Aspect | explode() | implode() |
|---|---|---|
| Purpose | Splits a string into an array | Joins array elements into a string |
| Input | String | Array |
| Output | Array | String |
| Operation | String → Array | Array → String |
| Delimiter | Splits by delimiter | Joins with delimiter |
Syntax:
explode(separator, string, limit)
implode(separator, array)
Examples:
<?php
// explode() - String to Array
$fruits = "Apple,Banana,Orange,Mango";
$fruitArray = explode(",", $fruits);
print_r($fruitArray);
// Output: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
// With limit parameter
$limited = explode(",", $fruits, 2);
print_r($limited);
// Output: Array ( [0] => Apple [1] => Banana,Orange,Mango )
// implode() - Array to String
$colors = array("Red", "Green", "Blue", "Yellow");
$colorString = implode(", ", $colors);
echo $colorString;
// Output: Red, Green, Blue, Yellow
// Using different separators
$path = array("home", "user", "documents");
$filePath = implode("/", $path);
echo $filePath;
// Output: home/user/documents
// Practical Example - CSV Processing
$csvLine = "John,25,Developer,New York";
$data = explode(",", $csvLine);
echo "Name: " . $data[0]; // John
echo "Age: " . $data[1]; // 25
// Creating CSV from array
$record = array("Jane", "30", "Designer", "Boston");
$csvOutput = implode(",", $record);
echo $csvOutput;
// Output: Jane,30,Designer,Boston
?>
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. explode() function explanation │ 1.5 marks │
│ - Purpose and operation │ │
│ - Syntax with parameters │ │
│ - String to Array conversion │ │
│ - Examples with limit parameter │ │
│ │ │
│ 2. implode() function explanation │ 1.5 marks │
│ - Purpose and operation │ │
│ - Syntax with parameters │ │
│ - Array to String conversion │ │
│ - Examples with different separators │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (1.5 + 1.5)
Question 7 (3 marks)
Describe the major super global arrays in PHP.
Answer:
Superglobal arrays in PHP are built-in variables that are always available in all scopes throughout a script. They provide access to environment, server, and user input data.
Major Superglobal Arrays:
-
$_GET
- Contains data sent via URL parameters (query string)
- Used for GET method form submissions
- Example:
$_GET['name']from URLpage.php?name=John
-
$_POST
- Contains data sent via HTTP POST method
- Used for form submissions with method="POST"
- More secure than GET for sensitive data
-
$_REQUEST
- Contains data from both $_GET, $_POST, and $_COOKIE
- Can access data regardless of submission method
-
$_SERVER
- Contains server and execution environment information
- Examples:
$_SERVER['REQUEST_METHOD'],$_SERVER['HTTP_HOST'],$_SERVER['PHP_SELF']
-
$_SESSION
- Stores session variables across multiple pages
- Maintains user state during browsing session
- Requires
session_start()to initialize
-
$_COOKIE
- Contains values of cookies sent by the browser
- Accessed via
$_COOKIE['cookie_name']
-
$_FILES
- Contains information about uploaded files
- Includes file name, type, size, temporary location
-
$GLOBALS
- References all global variables
- Used to access global variables from anywhere
Examples:
<?php
// $_GET example
// URL: page.php?id=101&action=view
$id = $_GET['id']; // 101
$action = $_GET['action']; // view
// $_POST example
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
}
// $_SERVER examples
$currentPage = $_SERVER['PHP_SELF'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
// $_SESSION example
session_start();
$_SESSION['user_id'] = 123;
$_SESSION['username'] = "john_doe";
// $_COOKIE example
$theme = $_COOKIE['site_theme'] ?? 'default';
// $_FILES example (file upload)
$fileName = $_FILES['upload']['name'];
$fileSize = $_FILES['upload']['size'];
?>
Key Point: Superglobals are automatically global and accessible inside functions without using the global keyword.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Description of 8 superglobal arrays │ 2 marks │
│ - $_GET (0.25 marks) │ │
│ - $_POST (0.25 marks) │ │
│ - $_REQUEST (0.25 marks) │ │
│ - $_SERVER (0.25 marks) │ │
│ - $_SESSION (0.25 marks) │ │
│ - $_COOKIE (0.25 marks) │ │
│ - $_FILES (0.25 marks) │ │
│ - $GLOBALS (0.25 marks) │ │
│ │ │
│ 2. Code examples demonstrating usage │ 1 mark │
│ - Practical examples for each array │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Items + Examples (2 + 1)
Question 8 (3 marks)
How can a record be inserted into a database table using PHP?
Answer:
Records can be inserted into a database table using PHP through PDO (PHP Data Objects) or MySQLi. The recommended modern approach is using PDO with prepared statements for security and database independence.
Steps to Insert a Record:
- Establish database connection using PDO
- Prepare SQL INSERT statement with placeholders
- Bind parameters and execute the statement
- Handle success/error responses
Example using PDO with Prepared Statements:
<?php
try {
// Database connection
$dsn = "mysql:host=localhost;dbname=school_db;charset=utf8mb4";
$username = "root";
$password = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO($dsn, $username, $password, $options);
// Prepare INSERT statement with named placeholders
$sql = "INSERT INTO students (name, age, email, course) VALUES (:name, :age, :email, :course)";
$stmt = $pdo->prepare($sql);
// Execute with data
$stmt->execute([
'name' => 'John Doe',
'age' => 20,
'email' => 'john@example.com',
'course' => 'Computer Science'
]);
echo "Record inserted successfully. ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
?>
Key Points:
- Prepared statements prevent SQL injection attacks by separating SQL logic from data
- Use named placeholders (
:name) or positional placeholders (?) lastInsertId()returns the auto-incremented ID of the inserted record- Always use try-catch for proper error handling
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Steps and concept explanation │ 1.5 marks │
│ - Database connection establishment │ │
│ - Preparing SQL INSERT statement │ │
│ - Binding parameters and execution │ │
│ - Error handling approach │ │
│ │ │
│ 2. PDO code implementation with prepared │ 1.5 marks │
│ statements │ │
│ - Connection with options │ │
│ - Prepared statement with placeholders │ │
│ - Execute with data array │ │
│ - Try-catch error handling │ │
│ - lastInsertId() usage │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Concept + Implementation (1.5 + 1.5)
Question 9 (3 marks)
What is the significance of JSON schema?
Answer:
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the structure, data types, and constraints for JSON data, ensuring data integrity and consistency.
Significance of JSON Schema:
- Data Validation - Ensures JSON data conforms to expected structure and types
- Documentation - Serves as clear documentation for JSON data structures
- Data Integrity - Enforces constraints (required fields, data types, value ranges)
- Interoperability - Provides contract between systems for data exchange
- Error Prevention - Catches invalid data before processing
- Auto-completion - Enables IDE support for JSON editing
Key Features:
- Define data types (string, number, boolean, array, object, null)
- Specify required and optional properties
- Set constraints (minimum/maximum values, string patterns, array lengths)
- Support nested structures and references
Example:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Student",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string",
"minLength": 2,
"maxLength": 50
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 100
},
"courses": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
},
"required": ["id", "name", "email"]
}
Valid JSON instance:
{
"id": 101,
"name": "John Doe",
"email": "john@example.com",
"age": 20,
"courses": ["CST463", "CST465"]
}
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Significance and key features │ 2 marks │
│ - Data validation │ │
│ - Documentation │ │
│ - Data integrity │ │
│ - Interoperability │ │
│ - Error prevention │ │
│ - Auto-completion support │ │
│ - Key features (data types, constraints) │ │
│ │ │
│ 2. JSON Schema example with valid instance │ 1 mark │
│ - Complete schema with properties │ │
│ - Constraints and validation rules │ │
│ - Valid JSON instance conforming to schema │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (2 + 1)
Question 10 (3 marks)
With a diagram explain the MVC architecture of Laravel.
Answer:
MVC (Model-View-Controller) is a software architectural pattern that separates an application into three interconnected components. Laravel implements MVC to organize code, separate concerns, and improve maintainability.
MVC Components in Laravel:
- Model - Represents data and business logic; interacts with database using Eloquent ORM
- View - Handles presentation layer; displays data to users using Blade templates
- Controller - Processes requests; acts as intermediary between Model and View
MVC Flow Diagram:
┌──────────────────────────────────────────────────────────────┐
│ User/Browser │
└────────────┬─────────────────────────────────────┬───────────┘
│ │
│ HTTP Request │ HTTP Response
│ │
▼ │
┌─────────────────────────────────────────────────┴────────────┐
│ ROUTES │
│ (web.php / api.php) │
└────────────┬──────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────┐
│ CONTROLLER │
│ • Receives request │
│ • Processes input │
│ • Calls Model for data │
│ • Returns View with data │
└──────────┬─────────────────────────────────────┬───────────┘
│ │
│ Request Data │ Return Data
│ │
▼ │
┌──────────────────────────┐ │
│ MODEL │ │
│ • Database interaction │ │
│ • Business logic │ │
│ • Data validation │ │
│ • Eloquent ORM │ │
└──────────┬───────────────┘ │
│ │
│ Query │
▼ │
┌──────────────────────────┐ │
│ DATABASE │ │
│ (MySQL, PostgreSQL) │ │
└──────────────────────────┘ │
│
▼
┌───────────────────────┐
│ VIEW │
│ • Blade templates │
│ • HTML/CSS/JS │
│ • Display data │
└───────────────────────┘
Example Laravel MVC Workflow:
// Route (routes/web.php)
Route::get('/students', [StudentController::class, 'index']);
// Controller (app/Http/Controllers/StudentController.php)
class StudentController extends Controller {
public function index() {
$students = Student::all(); // Call Model
return view('students.index', compact('students')); // Return View
}
}
// Model (app/Models/Student.php)
class Student extends Model {
protected $table = 'students';
protected $fillable = ['name', 'email', 'course'];
}
// View (resources/views/students/index.blade.php)
@foreach($students as $student)
<p>{{ $student->name }} - {{ $student->course }}</p>
@endforeach
Benefits:
- Separation of Concerns - Each component has distinct responsibility
- Maintainability - Easy to modify one component without affecting others
- Reusability - Models and Views can be reused across controllers
- Testability - Components can be tested independently
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. MVC components explanation │ 1 mark │
│ - Model (data and business logic) │ │
│ - View (presentation layer) │ │
│ - Controller (request processing) │ │
│ │ │
│ 2. Diagram showing MVC flow │ 1 mark │
│ - User/Browser interaction │ │
│ - Routes layer │ │
│ - Controller, Model, View connections │ │
│ - Database interaction │ │
│ - Request/Response flow │ │
│ │ │
│ 3. Laravel implementation example │ 1 mark │
│ - Route definition │ │
│ - Controller with methods │ │
│ - Model with Eloquent │ │
│ - Blade view template │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Diagram + Example (1 + 1 + 1)
PART B (Long Answer Questions)
Answer any one full question from each module, each carries 14 marks
MODULE I — MODULE I
Question 11 (14 marks) — #### a) Discuss in detail with examples the audio and video tags in HTML for multimedia elements. (7 marks)
a) Discuss in detail with examples the audio and video tags in HTML for multimedia elements. (7 marks)
Answer:
HTML5 introduced native support for multimedia through <audio> and <video> tags, eliminating the need for third-party plugins like Flash. These tags provide built-in controls and support multiple formats for cross-browser compatibility.
HTML5 Audio Tag (<audio>)
The <audio> tag embeds sound content in web pages and supports formats like MP3, WAV, and OGG.
Syntax:
<audio controls>
<source src="audio-file.mp3" type="audio/mpeg">
<source src="audio-file.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Audio Tag Attributes:
| Attribute | Description |
|---|---|
controls |
Displays play, pause, volume controls |
autoplay |
Starts playing automatically when page loads |
loop |
Repeats audio continuously |
muted |
Starts with audio muted |
preload |
Specifies if/how audio should be loaded (auto, metadata, none) |
src |
Specifies audio file URL |
Audio Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio Example</title>
</head>
<body>
<h2>Audio Player Demo</h2>
<!-- Basic audio with controls -->
<audio controls>
<source src="background-music.mp3" type="audio/mpeg">
<source src="background-music.ogg" type="audio/ogg">
Your browser does not support audio playback.
</audio>
<!-- Audio with autoplay and loop -->
<h3>Background Music (Autoplay)</h3>
<audio controls autoplay loop muted>
<source src="ambient.mp3" type="audio/mpeg">
</audio>
<!-- Audio with preload -->
<h3>Podcast Episode</h3>
<audio controls preload="metadata">
<source src="podcast-ep01.mp3" type="audio/mpeg">
</audio>
</body>
</html>
HTML5 Video Tag (<video>)
The <video> tag embeds video content and supports formats like MP4, WebM, and OGG.
Syntax:
<video controls width="640" height="360">
<source src="video-file.mp4" type="video/mp4">
<source src="video-file.webm" type="video/webm">
Your browser does not support the video element.
</video>
Video Tag Attributes:
| Attribute | Description |
|---|---|
controls |
Displays video controls (play, pause, seek, volume) |
autoplay |
Starts playing automatically |
loop |
Repeats video continuously |
muted |
Starts with audio muted |
poster |
Image displayed before video plays |
width/height |
Dimensions of video player |
preload |
How video should be loaded |
Video Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Video Example</title>
<style>
video {
border: 2px solid #333;
border-radius: 8px;
}
</style>
</head>
<body>
<h2>Video Player Demo</h2>
<!-- Basic video with controls and poster -->
<video controls width="750" height="500" poster="video-thumbnail.jpg">
<source src="MySafety.mp4" type="video/mp4">
<source src="MySafety.webm" type="video/webm">
Your browser does not support HTML5 video.
</video>
<!-- Video with autoplay and loop (muted for autoplay to work) -->
<h3>Background Video</h3>
<video autoplay loop muted width="640" height="360">
<source src="background-video.mp4" type="video/mp4">
</video>
<!-- Video with all attributes -->
<h3>Tutorial Video</h3>
<video controls width="800" height="450" preload="auto" poster="tutorial-thumb.jpg">
<source src="tutorial.mp4" type="video/mp4">
<source src="tutorial.webm" type="video/webm">
<track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">
Your browser does not support this video format.
</video>
</body>
</html>
Supported Formats:
| Format | MIME Type | Audio/Video |
|---|---|---|
| MP3 | audio/mpeg | Audio |
| WAV | audio/wav | Audio |
| OGG | audio/ogg | Audio |
| MP4 | video/mp4 | Video |
| WebM | video/webm | Video |
| OGG | video/ogg | Video |
Key Points:
- Always provide multiple formats for cross-browser compatibility
- Use
controlsattribute for user interaction - Modern browsers require
mutedforautoplayto work <track>element adds subtitles/captions to videos- Fallback text displays for unsupported browsers
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML5 <audio> tag explanation │ 3.5 marks │
│ - Introduction and syntax │ │
│ - Audio tag attributes (controls, autoplay, │ │
│ loop, muted, preload, src) │ │
│ - Code examples demonstrating attributes │ │
│ - Supported audio formats │ │
│ │ │
│ 2. HTML5 <video> tag explanation │ 3.5 marks │
│ - Introduction and syntax │ │
│ - Video tag attributes (controls, autoplay, │ │
│ loop, muted, poster, width/height) │ │
│ - Code examples with different scenarios │ │
│ - Supported video formats and <track> │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Nearly Equal Parts (3.5 + 3.5)
b) Write an HTML code to create the nested list as shown in the question. (7 marks)
Answer:
Overview: The question requires creating a nested list structure with ordered and unordered lists representing CSE department semesters and their subjects.
Complete HTML Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSE Department - Semester Structure</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
h2 {
color: #333;
border-bottom: 2px solid #007bff;
padding-bottom: 10px;
}
ol {
line-height: 1.8;
}
ul {
line-height: 1.6;
list-style-type: disc;
}
</style>
</head>
<body>
<div class="container">
<h2>Department Course Structure</h2>
<ol>
<li>CSE
<ol>
<li>First Semester
<ul>
<li>Graphics</li>
<li>Chemistry</li>
<li>Life Skills</li>
</ul>
</li>
<li>Second Semester
<ul>
<li>Mechanics</li>
<li>Programming in C</li>
<li>Physics</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</body>
</html>
Explanation:
- Outer Ordered List (
<ol>) - Contains the department name (CSE) - Inner Ordered List - Contains semester numbers (First Semester, Second Semester)
- Unordered Lists (
<ul>) - Contains subject names for each semester - Styling - Added professional CSS for better presentation with proper spacing, container styling, and visual hierarchy
Structure Breakdown:
1. CSE
1. First Semester
• Graphics
• Chemistry
• Life Skills
2. Second Semester
• Mechanics
• Programming in C
• Physics
Key Features:
- Proper nesting:
<ol>→<ol>→<ul> - Semantic HTML5 structure with DOCTYPE
- Responsive design with viewport meta tag
- Professional styling for readability
- Clean indentation for maintainability
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML structure and DOCTYPE │ 1 mark │
│ - Complete HTML5 document structure │ │
│ - Proper DOCTYPE and meta tags │ │
│ │ │
│ 2. Outer ordered list (CSE department level) │ 1.5 marks │
│ - Correct <ol> tag for department │ │
│ - Proper nesting structure │ │
│ │ │
│ 3. Inner ordered list (semester levels) │ 2.5 marks │
│ - First Semester <ol> item │ │
│ - Second Semester <ol> item │ │
│ - Correct numbering and hierarchy │ │
│ │ │
│ 4. Unordered lists (subject names) │ 2 marks │
│ - First Semester subjects (<ul> with 3 <li>)│ │
│ - Second Semester subjects (<ul> with 3 <li>)│ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML Form/Structure with Multiple Components
Question 12 (14 marks) — #### a) What is MIME? Explain the significance of MIME and the types of MIME used in web pages. (7 marks)
a) What is MIME? Explain the significance of MIME and the types of MIME used in web pages. (7 marks)
Answer:
Definition:
MIME (Multipurpose Internet Mail Extensions) is a standard that extends the format of email messages and web content to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs.
Full Form: Multipurpose Internet Mail Extensions
Significance of MIME:
- Content Type Identification - Tells browsers/servers how to handle different file types
- Proper Rendering - Ensures correct display of multimedia content
- File Transfer - Enables transmission of non-text data over text-based protocols
- Security - Helps browsers determine if content is safe to execute
- Multi-part Messages - Allows single message to contain multiple data types
- Character Encoding - Supports international characters beyond ASCII
MIME Type Syntax:
type/subtype
Examples:
text/html- HTML documentimage/jpeg- JPEG imagevideo/mp4- MP4 video
Types of MIME Used in Web Pages:
1. Text Types
| MIME Type | Description | Usage |
|---|---|---|
text/html |
HTML documents | Web pages |
text/css |
CSS stylesheets | Styling |
text/javascript |
JavaScript files | Client-side scripts |
text/plain |
Plain text | Text files |
text/xml |
XML documents | Data exchange |
Example:
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="script.js"></script>
2. Image Types
| MIME Type | Description | File Extension |
|---|---|---|
image/jpeg |
JPEG images | .jpg, .jpeg |
image/png |
PNG images | .png |
image/gif |
GIF images | .gif |
image/svg+xml |
SVG vector images | .svg |
image/webp |
WebP images | .webp |
image/x-icon |
Icon files | .ico |
Example:
<img src="photo.jpg" type="image/jpeg">
<img src="logo.png" type="image/png">
3. Audio Types
| MIME Type | Description | File Extension |
|---|---|---|
audio/mpeg |
MP3 audio | .mp3 |
audio/wav |
WAV audio | .wav |
audio/ogg |
OGG audio | .ogg |
audio/webm |
WebM audio | .webm |
Example:
<audio controls>
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
</audio>
4. Video Types
| MIME Type | Description | File Extension |
|---|---|---|
video/mp4 |
MP4 video | .mp4 |
video/webm |
WebM video | .webm |
video/ogg |
OGG video | .ogv |
video/quicktime |
QuickTime video | .mov |
Example:
<video controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.webm" type="video/webm">
</video>
5. Application Types
| MIME Type | Description | Usage |
|---|---|---|
application/json |
JSON data | APIs, data exchange |
application/pdf |
PDF documents | Document viewing |
application/zip |
ZIP archives | File compression |
application/xml |
XML documents | Data structure |
application/x-www-form-urlencoded |
Form data | Form submissions |
multipart/form-data |
Form with files | File uploads |
Example:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="upload">
</form>
Complete Example Demonstrating Multiple MIME Types:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MIME Types Demo</title>
<!-- CSS: text/css -->
<link rel="stylesheet" type="text/css" href="styles.css">
<!-- JavaScript: text/javascript -->
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>MIME Types in Action</h1>
<!-- Images: image/* -->
<img src="logo.png" type="image/png" alt="Logo">
<img src="photo.jpg" type="image/jpeg" alt="Photo">
<!-- Audio: audio/* -->
<audio controls>
<source src="music.mp3" type="audio/mpeg">
<source src="music.ogg" type="audio/ogg">
</audio>
<!-- Video: video/* -->
<video controls width="640" height="360">
<source src="tutorial.mp4" type="video/mp4">
<source src="tutorial.webm" type="video/webm">
</video>
<!-- PDF Download: application/pdf -->
<a href="document.pdf" type="application/pdf">Download PDF</a>
<!-- Form with file upload: multipart/form-data -->
<form method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" name="document" accept="application/pdf,image/*">
<button type="submit">Upload</button>
</form>
</body>
</html>
Key Points:
- MIME types ensure proper content handling across different platforms
- Always specify correct MIME type for multimedia elements
- Modern web applications rely heavily on MIME types for API responses (JSON, XML)
- Incorrect MIME types can cause browsers to misinterpret content
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition of MIME │ 1 mark │
│ - Full form (Multipurpose Internet Mail │ │
│ Extensions) │ │
│ - Purpose and basic concept │ │
│ │ │
│ 2. Significance of MIME │ 2 marks │
│ - Content type identification │ │
│ - Proper rendering │ │
│ - File transfer capability │ │
│ - Security aspects │ │
│ - Multi-part messages │ │
│ - Character encoding support │ │
│ │ │
│ 3. Types of MIME used in web pages │ 4 marks │
│ - Text types (text/html, text/css, etc.) │ 0.8 marks │
│ - Image types (image/jpeg, image/png, etc.) │ 0.8 marks │
│ - Audio types (audio/mpeg, audio/wav, etc.) │ 0.8 marks │
│ - Video types (video/mp4, video/webm, etc.) │ 0.8 marks │
│ - Application types (application/json, etc.)│ 0.8 marks │
│ - Examples demonstrating each type │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Significance + Types (1 + 2 + 4)
b) Write HTML5 elements to accomplish the specified tasks. (7 marks)
Answer:
Overview: Create HTML5 form elements for: (a) autofocus text input for first name, (b) rating scale 1-10, (c) required email field, (d) comments textarea with submit button.
HTML5 Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Feedback Form</title>
</head>
<body>
<h1>Student Cafeteria Feedback Form</h1>
<form action="submit_feedback.php" method="POST">
<!-- Task (a): Text input with autofocus for first name -->
<label for="firstName">First Name:</label>
<input
type="text"
id="firstName"
name="firstName"
autofocus
required
placeholder="Enter your first name">
<br><br>
<!-- Task (b): Rating scale from 1 to 10 for cafeteria food -->
<label for="foodRating">Rate the Food Quality (1 to 10):</label>
<input
type="range"
id="foodRating"
name="foodRating"
min="1"
max="10"
value="5"
step="1">
<output for="foodRating" id="ratingOutput">5</output>
<br><br>
<!-- Task (c): Email input field (required) -->
<label for="emailId">Email Address (Required):</label>
<input
type="email"
id="emailId"
name="emailId"
required
placeholder="student@example.com">
<br><br>
<!-- Task (d): Textarea for student comments -->
<label for="comments">Additional Comments:</label>
<br>
<textarea
id="comments"
name="comments"
rows="5"
cols="50"
placeholder="Share your thoughts about the cafeteria..."></textarea>
<br><br>
<!-- Submit button -->
<button type="submit">Submit Feedback</button>
</form>
<script>
// Update range value display
const rangeInput = document.getElementById('foodRating');
const output = document.getElementById('ratingOutput');
rangeInput.addEventListener('input', function() {
output.textContent = this.value;
});
</script>
</body>
</html>
Explanation of HTML5 Elements:
Task (a): First Name Input with Autofocus
<input type="text" id="firstName" name="firstName" autofocus required>
type="text"- Standard text input fieldautofocus- HTML5 attribute that automatically focuses this field when page loadsrequired- HTML5 validation attribute; form won't submit without this field filledplaceholder- Shows hint text inside the input field
Task (b): Food Rating Scale (1-10)
<input type="range" id="foodRating" name="foodRating" min="1" max="10" value="5" step="1">
<output for="foodRating" id="ratingOutput">5</output>
type="range"- HTML5 input type that creates a slider controlmin="1"andmax="10"- Define the range from 1 to 10value="5"- Sets default middle valuestep="1"- Ensures whole number increments only<output>- HTML5 element to display the current slider value- JavaScript updates the output value as user moves the slider
Task (c): Required Email Field
<input type="email" id="emailId" name="emailId" required>
type="email"- HTML5 input type with automatic email format validationrequired- Makes this field mandatory; browser validates before submission- Browser automatically checks for valid email format (contains @, domain, etc.)
- Shows built-in error message if invalid
Task (d): Comments Textarea
<textarea id="comments" name="comments" rows="5" cols="50"></textarea>
<textarea>- HTML element for multi-line text inputrows="5"- Sets visible height to 5 linescols="50"- Sets visible width to 50 charactersplaceholder- Provides hint text for users
Task (d): Submit Button
<button type="submit">Submit Feedback</button>
type="submit"- Submits the form data to the server- Triggers HTML5 validation before submission
- Form validates all
requiredfields andtypeconstraints
Key HTML5 Features Demonstrated:
- ✓ autofocus attribute (automatic focus)
- ✓ type="range" (slider input)
- ✓ type="email" (email validation)
- ✓ required attribute (mandatory field validation)
- ✓ <output> element (display dynamic values)
- ✓ placeholder attribute (hint text)
- ✓ <textarea> element (multi-line input)
- ✓ Built-in HTML5 form validation (no server-side code needed for basic checks)
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ Task (a): Text input with autofocus │ 1.5 marks │
│ - <input type="text"> │ │
│ - autofocus attribute implementation │ │
│ - proper id, name, and placeholder │ │
│ │ │
│ Task (b): Rating scale from 1 to 10 │ 2 marks │
│ - <input type="range"> element │ │
│ - min="1", max="10" attributes │ │
│ - value, step attributes │ │
│ - <output> element for display │ │
│ - JavaScript for dynamic value update │ │
│ │ │
│ Task (c): Required email field │ 1.5 marks │
│ - <input type="email"> │ │
│ - required attribute │ │
│ - proper validation setup │ │
│ │ │
│ Task (d): Comments textarea and submit button │ 2 marks │
│ - <textarea> with rows and cols │ │
│ - proper label and attributes │ │
│ - <button type="submit"> │ │
│ - Form structure and action/method │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Tasks (1.5 + 2 + 1.5 + 2)
MODULE II — MODULE II
Question 13 (14 marks) — #### a) Differentiate class selectors and generic selectors in CSS. Apply appropriate selectors to create two different paragraph styles as specified. (7 marks)
a) Differentiate class selectors and generic selectors in CSS. Apply appropriate selectors to create two different paragraph styles as specified. (7 marks)
Answer:
Difference Between Class Selectors and Generic Selectors:
| Aspect | Generic Selectors | Class Selectors |
|---|---|---|
| Syntax | Element name (e.g., p, div, h1) |
.className (e.g., .highlight, .error) |
| Application | Applies to ALL elements of that type | Applies only to elements with that class |
| Specificity | Low specificity | Higher specificity than generic |
| Reusability | Applies automatically to all elements | Can be applied to any element |
| HTML Required | No class attribute needed | Requires class="className" in HTML |
| Use Case | Default styling for all elements | Specific styling for selected elements |
Example:
/* Generic Selector - applies to ALL paragraphs */
p {
color: black;
}
/* Class Selector - applies only to paragraphs with class="special" */
.special {
color: red;
}
<p>This is black (generic selector)</p>
<p class="special">This is red (class selector)</p>
Complete Implementation with Two Paragraph Styles:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selectors - Class vs Generic</title>
<style>
body {
font-family: Georgia, serif;
background-color: #f8f9fa;
padding: 40px;
max-width: 900px;
margin: 0 auto;
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 40px;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
/* Style 1 - Using Class Selector */
.style1 {
font-family: 'Times New Roman', Times, serif;
color: red;
font-style: italic;
text-indent: 1.5em;
}
/* Style 2 - Using Class Selector */
.style2 {
line-height: 2em;
text-align: center;
background-color: yellow;
}
/* Additional styling for demonstration */
.style-label {
font-weight: bold;
color: #34495e;
margin-top: 25px;
margin-bottom: 10px;
font-size: 18px;
border-left: 4px solid #3498db;
padding-left: 12px;
}
.explanation {
background-color: #e8f4f8;
border-left: 4px solid #3498db;
padding: 15px;
margin: 20px 0;
border-radius: 4px;
}
code {
background-color: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
font-family: 'Courier New', monospace;
color: #c7254e;
}
</style>
</head>
<body>
<div class="container">
<h1>CSS Class Selectors vs Generic Selectors</h1>
<div class="explanation">
<h3>Understanding the Difference:</h3>
<p><strong>Generic Selector (p):</strong> Applies to ALL paragraph elements automatically.</p>
<p><strong>Class Selector (.className):</strong> Applies only to elements with <code>class="className"</code> attribute.</p>
</div>
<h3 class="style-label">Style 1 Demonstration</h3>
<p><strong>CSS Applied:</strong> <code>font-family: Times New Roman</code>, <code>color: red</code>, <code>font-style: italic</code>, <code>text-indent: 1.5em</code></p>
<p class="style1">
This paragraph demonstrates Style 1 using a class selector. The text is displayed in
Times New Roman font, colored in red, styled in italics, and has a first-line indentation
of 1.5em. This styling is achieved using the .style1 class selector, which provides
precise control over which paragraphs receive this formatting. Class selectors allow us
to apply specific styles to selected elements rather than all elements of the same type.
</p>
<p class="style1">
This is another paragraph with Style 1 applied. Notice how the first line is indented by
1.5em, creating a traditional book-like appearance. The italic red text in Times New Roman
gives it a distinctive, classical look that stands out from regular paragraphs.
</p>
<h3 class="style-label">Style 2 Demonstration</h3>
<p><strong>CSS Applied:</strong> <code>line-height: 2em</code>, <code>text-align: center</code>, <code>background-color: yellow</code></p>
<p class="style2">
This paragraph demonstrates Style 2 using a different class selector. The text has
double line spacing (2em), is center-aligned, and has a yellow background color.
This creates excellent readability with generous spacing between lines.
</p>
<p class="style2">
Another paragraph with Style 2 applied. The center alignment and yellow background
make this text visually distinct and easy to identify. The 2em line height provides
comfortable reading space, making it ideal for important announcements or callouts.
</p>
<h3 class="style-label">Generic Selector Example (For Comparison)</h3>
<p><strong>Note:</strong> If we used a generic selector like <code>p { color: red; }</code>,
ALL paragraphs on this page would be red, including this explanation paragraph.</p>
<div class="explanation">
<h3>Key Takeaway:</h3>
<p><strong>Class selectors (.style1, .style2)</strong> provide flexibility by allowing you to:</p>
<ul>
<li>Apply styles selectively to specific elements</li>
<li>Reuse the same style across different element types</li>
<li>Override generic selector styles with higher specificity</li>
<li>Maintain cleaner, more maintainable CSS code</li>
</ul>
</div>
</div>
</body>
</html>
CSS Breakdown:
Style 1 Properties:
.style1 {
font-family: 'Times New Roman', Times, serif; /* Classic serif font */
color: red; /* Red text color */
font-style: italic; /* Italic text */
text-indent: 1.5em; /* First line indentation */
}
Style 2 Properties:
.style2 {
line-height: 2em; /* Double line spacing */
text-align: center; /* Center alignment */
background-color: yellow; /* Yellow background */
}
HTML Usage:
<!-- Applying Style 1 -->
<p class="style1">This paragraph has Style 1</p>
<!-- Applying Style 2 -->
<p class="style2">This paragraph has Style 2</p>
<!-- No class = no special styling -->
<p>This paragraph has default styling</p>
Why Class Selectors are Better Than Generic:
- Selective Application - Only styled elements receive the formatting
- Reusability - Same class can be applied to
<p>,<div>,<span>, etc. - Maintainability - Easy to update styling for specific elements
- Specificity Control - Class selectors override generic selectors
This implementation demonstrates both styles clearly and showcases the power and flexibility of CSS class selectors compared to generic element selectors.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Differentiation between class selectors │ 2 marks │
│ and generic selectors │ │
│ - Syntax comparison │ │
│ - Application differences │ │
│ - Specificity levels │ │
│ - Reusability and use cases │ │
│ - HTML requirements │ │
│ │ │
│ 2. Style 1 implementation │ 2.5 marks │
│ - font-family: Times New Roman │ │
│ - color: red │ │
│ - font-style: italic │ │
│ - text-indent: 1.5em │ │
│ - Proper class selector usage │ │
│ │ │
│ 3. Style 2 implementation │ 2.5 marks │
│ - line-height: 2em │ │
│ - text-align: center │ │
│ - background-color: yellow │ │
│ - Proper class selector usage │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiation + Two Applications (2 + 2.5 + 2.5)
b) Write JavaScript code to find the factorial of numbers from 1 to 5 and display the results in a table with a blue, dotted border. (7 marks)
Answer:
Overview: Create a JavaScript program that calculates factorials for numbers 1-5 and displays results in an HTML table with styling.
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Calculator - JavaScript</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 40px 20px;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background-color: white;
padding: 40px;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
max-width: 600px;
width: 100%;
}
h1 {
color: #333;
margin-bottom: 10px;
text-align: center;
font-size: 28px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
/* Table with blue dotted border as required */
table {
width: 100%;
border-collapse: collapse;
border: 3px dotted blue; /* Blue dotted border */
margin: 20px 0;
background-color: #f9f9f9;
}
th, td {
border: 2px dotted blue; /* Blue dotted border for cells */
padding: 15px;
text-align: center;
font-size: 16px;
}
th {
background-color: #4169e1; /* Royal blue background */
color: white;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
}
td {
background-color: white;
}
tr:nth-child(even) td {
background-color: #e6f2ff; /* Light blue for alternate rows */
}
tr:hover td {
background-color: #cce5ff; /* Hover effect */
transition: background-color 0.3s;
}
.number-cell {
font-weight: bold;
color: #2c3e50;
}
.factorial-cell {
color: #27ae60;
font-weight: bold;
font-size: 18px;
}
.calculation-cell {
color: #666;
font-size: 14px;
font-family: 'Courier New', monospace;
}
.info {
background-color: #e8f4f8;
border-left: 4px solid #3498db;
padding: 15px;
margin-top: 20px;
border-radius: 4px;
font-size: 14px;
color: #2c3e50;
}
.info strong {
color: #2980b9;
}
</style>
</head>
<body>
<div class="container">
<h1>Factorial Calculator</h1>
<p class="subtitle">Calculating factorials for numbers 1 through 5</p>
<!-- Table will be populated by JavaScript -->
<table id="factorialTable">
<thead>
<tr>
<th>Number (n)</th>
<th>Calculation</th>
<th>Factorial (n!)</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Rows will be inserted here by JavaScript -->
</tbody>
</table>
<div class="info">
<strong>Note:</strong> Factorial of a number n (denoted as n!) is the product of all positive
integers less than or equal to n. For example: 5! = 5 × 4 × 3 × 2 × 1 = 120
</div>
</div>
<script>
// Function to calculate factorial of a number
function calculateFactorial(n) {
if (n === 0 || n === 1) {
return 1;
}
let factorial = 1;
for (let i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
// Function to generate calculation string (e.g., "5 × 4 × 3 × 2 × 1")
function getCalculationString(n) {
if (n === 0 || n === 1) {
return "1";
}
let calculation = [];
for (let i = n; i >= 1; i--) {
calculation.push(i);
}
return calculation.join(" × ");
}
// Function to populate the table
function generateFactorialTable() {
const tableBody = document.getElementById('tableBody');
// Calculate factorials for numbers 1 to 5
for (let num = 1; num <= 5; num++) {
const factorial = calculateFactorial(num);
const calculation = getCalculationString(num);
// Create table row
const row = document.createElement('tr');
// Number cell
const numberCell = document.createElement('td');
numberCell.className = 'number-cell';
numberCell.textContent = num;
// Calculation cell
const calcCell = document.createElement('td');
calcCell.className = 'calculation-cell';
calcCell.textContent = calculation;
// Factorial result cell
const factorialCell = document.createElement('td');
factorialCell.className = 'factorial-cell';
factorialCell.textContent = factorial.toLocaleString();
// Append cells to row
row.appendChild(numberCell);
row.appendChild(calcCell);
row.appendChild(factorialCell);
// Append row to table body
tableBody.appendChild(row);
}
}
// Generate table when page loads
window.onload = function() {
generateFactorialTable();
console.log("Factorial table generated successfully!");
// Display results in console as well
console.log("Factorial Results:");
for (let i = 1; i <= 5; i++) {
console.log(`${i}! = ${calculateFactorial(i)}`);
}
};
</script>
</body>
</html>
Explanation:
1. Factorial Calculation Function:
function calculateFactorial(n) {
if (n === 0 || n === 1) {
return 1; // Base case: 0! = 1, 1! = 1
}
let factorial = 1;
for (let i = 2; i <= n; i++) {
factorial *= i; // Multiply factorial by each number
}
return factorial;
}
- Handles base cases (0 and 1)
- Uses iterative approach for efficiency
- Multiplies all numbers from 2 to n
2. Calculation String Generator:
function getCalculationString(n) {
let calculation = [];
for (let i = n; i >= 1; i--) {
calculation.push(i);
}
return calculation.join(" × "); // Returns "5 × 4 × 3 × 2 × 1"
}
- Creates visual representation of calculation
- Shows multiplication sequence
3. Table Generation:
function generateFactorialTable() {
const tableBody = document.getElementById('tableBody');
for (let num = 1; num <= 5; num++) {
const factorial = calculateFactorial(num);
const row = document.createElement('tr');
// Create and append cells...
tableBody.appendChild(row);
}
}
- Dynamically creates table rows
- Populates with calculated values
4. Blue Dotted Border (CSS):
table {
border: 3px dotted blue; /* Blue dotted border for table */
}
th, td {
border: 2px dotted blue; /* Blue dotted border for cells */
}
Output Table:
| Number (n) | Calculation | Factorial (n!) |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 × 1 | 2 |
| 3 | 3 × 2 × 1 | 6 |
| 4 | 4 × 3 × 2 × 1 | 24 |
| 5 | 5 × 4 × 3 × 2 × 1 | 120 |
Key Features:
- ✓ Calculates factorials for numbers 1-5
- ✓ Displays results in HTML table
- ✓ Table has blue, dotted border as required
- ✓ Shows calculation breakdown for each factorial
- ✓ Professional styling with hover effects
- ✓ Responsive design
- ✓ Console logging for debugging
- ✓ Clean, well-commented code
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Factorial calculation logic │ 3 marks │
│ - calculateFactorial() function │ │
│ - Correct algorithm (iterative/recursive) │ │
│ - Base case handling (0! = 1, 1! = 1) │ │
│ - Loop to multiply values │ │
│ │ │
│ 2. Loop to calculate factorials for 1-5 │ 2 marks │
│ - For loop iterating from 1 to 5 │ │
│ - Calling factorial function for each number│ │
│ - Storing/processing results │ │
│ │ │
│ 3. Table creation and display │ 2 marks │
│ - HTML table structure │ │
│ - Blue, dotted border (border: dotted blue) │ │
│ - Proper table rows with number and result │ │
│ - Dynamic table generation with JavaScript │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Calculation Logic + Loop + Display (3 + 2 + 2)
Question 14 (14 marks) — #### a) What are CSS selectors? Explain in detail the CSS selectors with examples. (7 marks)
a) What are CSS selectors? Explain in detail the CSS selectors with examples. (7 marks)
Answer:
Definition:
CSS Selectors are patterns used to select and style HTML elements. They define which elements in the DOM (Document Object Model) will be affected by CSS rules.
Syntax:
selector {
property: value;
}
Types of CSS Selectors:
*1. Universal Selector (``)**
Selects all elements on the page.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
Usage: Global resets, applying default styles to all elements.
2. Element/Type Selector
Selects all elements of a specific HTML tag.
p {
color: blue;
font-size: 16px;
}
h1 {
font-weight: bold;
}
Example:
<p>This paragraph will be blue.</p>
<h1>This heading will be bold.</h1>
3. Class Selector (.className)
Selects all elements with a specific class attribute. Most commonly used selector.
.highlight {
background-color: yellow;
font-weight: bold;
}
.error {
color: red;
border: 1px solid red;
}
Example:
<p class="highlight">Highlighted text</p>
<div class="error">Error message</div>
Key Points:
- Can be applied to any element type
- Multiple elements can share the same class
- Elements can have multiple classes:
class="highlight error"
4. ID Selector (#idName)
Selects a single element with a specific ID attribute. IDs must be unique.
#header {
background-color: navy;
color: white;
padding: 20px;
}
#footer {
text-align: center;
}
Example:
<div id="header">Website Header</div>
<div id="footer">Copyright 2025</div>
Key Point: ID selectors have higher specificity than class selectors.
5. Descendant Selector (space)
Selects elements that are descendants of another element.
div p {
color: green; /* All paragraphs inside divs */
}
.container h2 {
font-size: 24px; /* All h2 elements inside .container */
}
Example:
<div>
<p>This will be green</p>
<section>
<p>This will also be green (descendant of div)</p>
</section>
</div>
6. Child Selector (>)
Selects direct children only (not all descendants).
div > p {
color: red; /* Only paragraphs that are direct children of div */
}
Example:
<div>
<p>Red (direct child)</p>
<section>
<p>Not red (not a direct child of div)</p>
</section>
</div>
7. Adjacent Sibling Selector (+)
Selects an element immediately following another element.
h1 + p {
font-weight: bold; /* First paragraph immediately after h1 */
}
Example:
<h1>Heading</h1>
<p>This paragraph will be bold</p>
<p>This paragraph will not be bold</p>
8. General Sibling Selector (~)
Selects all siblings following an element.
h1 ~ p {
color: gray; /* All paragraphs that are siblings after h1 */
}
9. Attribute Selectors
Selects elements based on attributes and their values.
/* Has attribute */
input[type] {
border: 1px solid black;
}
/* Specific value */
input[type="text"] {
background-color: white;
}
/* Contains value */
a[href*="example"] {
color: blue;
}
/* Starts with */
a[href^="https"] {
color: green;
}
/* Ends with */
img[src$=".png"] {
border: 2px solid gray;
}
Example:
<input type="text" placeholder="Name">
<input type="email" placeholder="Email">
<a href="https://example.com">Secure Link</a>
<img src="photo.png" alt="Photo">
10. Pseudo-class Selectors
Selects elements based on their state or position.
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: orange; }
/* Form states */
input:focus {
border-color: blue;
outline: none;
}
input:disabled {
background-color: #ccc;
}
/* Structural pseudo-classes */
li:first-child {
font-weight: bold;
}
li:last-child {
border-bottom: none;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
li:nth-child(even) {
background-color: white;
}
11. Pseudo-element Selectors
Selects and styles specific parts of elements.
/* First letter */
p::first-letter {
font-size: 32px;
font-weight: bold;
color: red;
}
/* First line */
p::first-line {
font-weight: bold;
}
/* Before and after */
.quote::before {
content: '"';
font-size: 24px;
}
.quote::after {
content: '"';
font-size: 24px;
}
12. Grouping Selector (,)
Applies same styles to multiple selectors.
h1, h2, h3 {
font-family: Arial, sans-serif;
color: navy;
}
.header, .footer, .sidebar {
background-color: #f5f5f5;
}
Complete Example Demonstrating Multiple Selectors:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Selectors Demo</title>
<style>
/* Universal Selector */
* {
margin: 0;
padding: 0;
}
/* Element Selector */
body {
font-family: Arial, sans-serif;
padding: 20px;
}
/* ID Selector */
#header {
background-color: #2c3e50;
color: white;
padding: 20px;
text-align: center;
}
/* Class Selector */
.highlight {
background-color: yellow;
padding: 5px;
}
.container {
max-width: 800px;
margin: 20px auto;
}
/* Descendant Selector */
.container p {
line-height: 1.6;
}
/* Child Selector */
.nav > li {
display: inline-block;
margin-right: 15px;
}
/* Attribute Selector */
input[type="email"] {
border: 2px solid blue;
}
/* Pseudo-class Selectors */
a:hover {
color: red;
text-decoration: underline;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
/* Pseudo-element Selector */
p::first-letter {
font-size: 24px;
font-weight: bold;
color: #e74c3c;
}
/* Grouping Selector */
h1, h2, h3 {
color: #2c3e50;
margin-bottom: 10px;
}
/* Adjacent Sibling Selector */
h2 + p {
font-style: italic;
}
</style>
</head>
<body>
<div id="header">
<h1>CSS Selectors Demonstration</h1>
</div>
<div class="container">
<h2>Introduction</h2>
<p>This paragraph is italicized (adjacent sibling selector).</p>
<p class="highlight">This paragraph is highlighted with class selector.</p>
<h3>List Example</h3>
<ul class="nav">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<h3>Form Example</h3>
<input type="email" placeholder="Enter email">
<input type="text" placeholder="Enter name">
<h3>Links</h3>
<a href="#">Hover over this link</a>
</div>
</body>
</html>
Selector Specificity (from highest to lowest):
- Inline styles:
<p style="color: red;"> - ID selectors:
#header - Class selectors, attribute selectors, pseudo-classes:
.highlight,[type="text"],:hover - Element selectors, pseudo-elements:
p,::first-letter - Universal selector:
*
Key Takeaways:
- Element selectors for general styling
- Class selectors for reusable styles (most common)
- ID selectors for unique elements
- Pseudo-classes for interactive states
- Combinators (space, >, +, ~) for relationships
- Attribute selectors for targeting specific attributes
- Understanding specificity helps resolve style conflicts
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and concept of CSS selectors │ 1 mark │
│ - What are CSS selectors │ │
│ - Purpose and basic syntax │ │
│ │ │
│ 2. Explanation of different CSS selector types │ 5 marks │
│ - Universal Selector (*) │ │
│ - Element/Type Selector │ │
│ - Class Selector (.className) │ │
│ - ID Selector (#idName) │ │
│ - Descendant Selector (space) │ │
│ - Child Selector (>) │ │
│ - Attribute Selector ([attr]) │ │
│ - Pseudo-class Selectors (:hover, :nth) │ │
│ - Pseudo-element Selectors (::first-letter) │ │
│ - Grouping Selector (,) │ │
│ - Adjacent Sibling Selector (+) │ │
│ │ │
│ 3. Examples demonstrating selector usage │ 1 mark │
│ - Code examples for each type │ │
│ - Complete demonstration page │ │
│ - Specificity explanation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Multiple Types + Examples (1 + 5 + 1)
b) Write a JavaScript function to determine the largest of three numbers. Use prompt dialog box to enter the three numbers. (7 marks)
Answer:
Overview: Create a JavaScript program that prompts the user to enter three numbers and determines which is the largest using conditional logic.
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Largest of Three Numbers</title>
</head>
<body>
<h1>Find the Largest of Three Numbers</h1>
<button onclick="findLargest()">Click to Enter Three Numbers</button>
<p id="result"></p>
<script>
// Function to determine the largest of three numbers
function findLargestNumber(num1, num2, num3) {
let largest;
// Using if-else statements
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
return largest;
}
// Main function to get input and display results
function findLargest() {
// Get three numbers using prompt dialogs
let num1 = prompt("Enter the first number:");
let num2 = prompt("Enter the second number:");
let num3 = prompt("Enter the third number:");
// Validate input
if (num1 === null || num2 === null || num3 === null) {
alert("Operation cancelled!");
return;
}
// Convert to numbers
num1 = parseFloat(num1);
num2 = parseFloat(num2);
num3 = parseFloat(num3);
// Check if inputs are valid numbers
if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {
alert("Please enter valid numbers!");
return;
}
// Find the largest number
let largest = findLargestNumber(num1, num2, num3);
// Display result
document.getElementById('result').innerHTML =
`First Number: ${num1}<br>` +
`Second Number: ${num2}<br>` +
`Third Number: ${num3}<br><br>` +
`<strong>The largest number is: ${largest}</strong>`;
}
// Alternative method using Math.max()
function findLargestUsingMath(num1, num2, num3) {
return Math.max(num1, num2, num3);
}
// Alternative implementation using ternary operators
function findLargestTernary(num1, num2, num3) {
return num1 >= num2 ?
(num1 >= num3 ? num1 : num3) :
(num2 >= num3 ? num2 : num3);
}
</script>
</body>
</html>
Explanation:
1. Core Logic - Finding Largest Number:
function findLargestNumber(num1, num2, num3) {
let largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1; // num1 is largest
} else if (num2 >= num1 && num2 >= num3) {
largest = num2; // num2 is largest
} else {
largest = num3; // num3 is largest
}
return largest;
}
Logic Breakdown:
- First condition: If num1 is greater than or equal to both num2 and num3, num1 is largest
- Second condition: If num2 is greater than or equal to both num1 and num3, num2 is largest
- Else: num3 must be the largest
2. Getting User Input with Prompts:
let num1 = prompt("Enter the first number:");
let num2 = prompt("Enter the second number:");
let num3 = prompt("Enter the third number:");
3. Input Validation:
// Check if user cancelled
if (num1 === null || num2 === null || num3 === null) {
alert("Operation cancelled!");
return;
}
// Convert to numbers
num1 = parseFloat(num1);
num2 = parseFloat(num2);
num3 = parseFloat(num3);
// Validate numeric input
if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {
alert("Please enter valid numbers!");
return;
}
4. Alternative Methods:
Method 2 - Using Math.max():
function findLargestUsingMath(num1, num2, num3) {
return Math.max(num1, num2, num3);
}
Method 3 - Using Ternary Operator:
function findLargestTernary(num1, num2, num3) {
return num1 >= num2 ?
(num1 >= num3 ? num1 : num3) :
(num2 >= num3 ? num2 : num3);
}
Test Cases:
| Test Case | Input | Expected Output |
|---|---|---|
| 1 | 10, 20, 15 | 20 |
| 2 | 50, 25, 30 | 50 |
| 3 | 5, 10, 100 | 100 |
| 4 | 15, 15, 10 | 15 |
| 5 | 8, 8, 8 | 8 (all equal) |
| 6 | -5, -10, -3 | -3 |
| 7 | 3.5, 3.7, 3.6 | 3.7 |
Key Features:
- ✓ Uses prompt dialogs for user input as required
- ✓ Proper input validation (checks for null and NaN)
- ✓ Handles negative numbers and decimals
- ✓ Clean, exam-friendly code that students can write
- ✓ Multiple implementation methods shown
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Prompt dialog boxes to get three numbers │ 1 mark │
│ - prompt() for first number │ │
│ - prompt() for second number │ │
│ - prompt() for third number │ │
│ │ │
│ 2. Function to find largest number │ 3 marks │
│ - Conditional logic (if-else/ternary) │ │
│ - Comparing num1 >= num2 && num1 >= num3 │ │
│ - Comparing num2 >= num1 && num2 >= num3 │ │
│ - Returning correct largest value │ │
│ │ │
│ 3. Input validation and error handling │ 1.5 marks │
│ - Check for cancelled input (null) │ │
│ - Convert string to number (parseFloat) │ │
│ - Validate numeric input (isNaN check) │ │
│ - Display error messages │ │
│ │ │
│ 4. Display result │ 1.5 marks │
│ - Show all three input numbers │ │
│ - Display largest number │ │
│ - Proper formatting and presentation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Prompt + Logic + Validation + Display (1+3+1.5+1.5)
MODULE III — MODULE III
Question 15 (14 marks) — #### a) What are associative arrays in PHP? Create an associative array to declare name and age of three persons. Use appropriate functions to print each element and sort in ascending order of names and ages. (7 marks)
a) What are associative arrays in PHP? Create an associative array to declare name and age of three persons. Use appropriate functions to print each element and sort in ascending order of names and ages. (7 marks)
Answer:
Definition:
Associative arrays in PHP are arrays that use named keys (strings) instead of numeric indices. They allow you to create key-value pairs where each key is associated with a specific value, similar to dictionaries or hash maps in other languages.
Syntax:
$arrayName = array("key1" => "value1", "key2" => "value2");
// OR (PHP 5.4+)
$arrayName = ["key1" => "value1", "key2" => "value2"];
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Associative Arrays Demo</title>
</head>
<body>
<h1>PHP Associative Arrays - Names and Ages</h1>
<?php
// ===== PART 1: Creating Associative Array =====
echo '<h2>Part 1: Creating Associative Array</h2>';
// Create associative array with names as keys and ages as values
$persons = array(
"John" => 25,
"Alice" => 30,
"Bob" => 22
);
echo '<h3>Original Array:</h3>';
foreach ($persons as $name => $age) {
echo "$name => $age<br>";
}
// ===== PART 2: Printing Each Element =====
echo '<h2>Part 2: Printing Each Element</h2>';
echo '<h3>Method 1: Using foreach loop</h3>';
foreach ($persons as $name => $age) {
echo "$name is $age years old<br>";
}
echo '<h3>Method 2: Using array_keys() and array_values()</h3>';
$names = array_keys($persons);
$ages = array_values($persons);
for ($i = 0; $i < count($persons); $i++) {
echo "{$names[$i]} is {$ages[$i]} years old<br>";
}
echo '<h3>Method 3: Using print_r()</h3>';
echo '<pre>';
print_r($persons);
echo '</pre>';
// ===== PART 3: Sorting by Names (Keys) =====
echo '<h2>Part 3: Sorting by Names (Keys) - Ascending Order</h2>';
// Create copy for sorting by keys
$personsByName = $persons;
ksort($personsByName); // Sort by keys (names) in ascending order
echo '<p><strong>Using ksort():</strong></p>';
foreach ($personsByName as $name => $age) {
echo "$name => $age<br>";
}
// ===== PART 4: Sorting by Ages (Values) =====
echo '<h2>Part 4: Sorting by Ages (Values) - Ascending Order</h2>';
// Create copy for sorting by values
$personsByAge = $persons;
asort($personsByAge); // Sort by values (ages) in ascending order
echo '<p><strong>Using asort():</strong></p>';
foreach ($personsByAge as $name => $age) {
echo "$name => $age<br>";
}
?>
</body>
</html>
Explanation:
1. Creating Associative Array:
$persons = array(
"John" => 25, // "John" is key, 25 is value
"Alice" => 30,
"Bob" => 22
);
2. Printing Each Element:
Method 1 - foreach loop:
foreach ($persons as $name => $age) {
echo "$name is $age years old";
}
Method 2 - Using array_keys() and array_values():
$names = array_keys($persons); // ["John", "Alice", "Bob"]
$ages = array_values($persons); // [25, 30, 22]
3. Sorting by Names (Keys):
ksort($personsByName); // Sort by keys in ascending order (A-Z)
// Result: Alice => 30, Bob => 22, John => 25
4. Sorting by Ages (Values):
asort($personsByAge); // Sort by values in ascending order
// Result: Bob => 22, John => 25, Alice => 30
PHP Array Sorting Functions:
| Function | Sorts By | Order | Maintains Keys |
|---|---|---|---|
ksort() |
Keys | Ascending | Yes |
krsort() |
Keys | Descending | Yes |
asort() |
Values | Ascending | Yes |
arsort() |
Values | Descending | Yes |
sort() |
Values | Ascending | No |
rsort() |
Values | Descending | No |
Key Differences:
- Indexed Arrays: Use numeric keys (0, 1, 2, ...)
- Associative Arrays: Use string keys ("name", "age", ...)
Output:
Original:
- John => 25
- Alice => 30
- Bob => 22
Sorted by Names (ksort):
- Alice => 30
- Bob => 22
- John => 25
Sorted by Ages (asort):
- Bob => 22
- John => 25
- Alice => 30
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition of associative arrays │ 1 mark │
│ - What are associative arrays │ │
│ - Key-value pair concept │ │
│ - Syntax explanation │ │
│ │ │
│ 2. Create associative array with 3 persons │ 2 marks │
│ - Array declaration with proper syntax │ │
│ - Name and age for three persons │ │
│ - Correct key => value structure │ │
│ │ │
│ 3. Print each element using appropriate │ 2 marks │
│ functions │ │
│ - foreach loop or similar iteration │ │
│ - Display key and value properly │ │
│ - Formatted output │ │
│ │ │
│ 4. Sort in ascending order │ 2 marks │
│ - Sort by names (ksort) - 1 mark │ │
│ - Sort by ages (asort) - 1 mark │ │
│ - Display sorted results │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Creation + Operations (1+2+2+2)
b) Write a function in PHP to check if a number read is a palindrome or not. (7 marks)
Answer:
Overview: A palindrome number reads the same backward as forward (e.g., 121, 1331, 12321). Create a PHP function that checks if a given number is a palindrome.
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Palindrome Number Checker</title>
</head>
<body>
<h1>Palindrome Number Checker</h1>
<form method="POST" action="">
<label for="number">Enter a Number:</label>
<input type="number" id="number" name="number" required>
<button type="submit">Check Palindrome</button>
</form>
<?php
// Function to check if a number is palindrome - Method 1 (String Reversal)
function isPalindromeString($number) {
// Convert number to string
$numStr = (string)$number;
// Reverse the string
$reversedStr = strrev($numStr);
// Compare original and reversed
return $numStr === $reversedStr;
}
// Function to check if a number is palindrome - Method 2 (Mathematical)
function isPalindromeMath($number) {
$original = $number;
$reversed = 0;
// Reverse the number mathematically
while ($number > 0) {
$digit = $number % 10; // Get last digit
$reversed = ($reversed * 10) + $digit; // Build reversed number
$number = (int)($number / 10); // Remove last digit
}
// Compare original and reversed
return $original == $reversed;
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['number'])) {
$number = abs((int)$_POST['number']); // Get absolute value
// Check using both methods
$isPalindrome = isPalindromeString($number);
echo "<hr>";
echo "<h2>Result:</h2>";
if ($isPalindrome) {
echo "<p><strong>$number</strong> is a PALINDROME</p>";
echo "<p>It reads the same forwards and backwards.</p>";
} else {
echo "<p><strong>$number</strong> is NOT a palindrome</p>";
$reversedNum = (int)strrev((string)$number);
echo "<p>Original: $number, Reversed: $reversedNum</p>";
}
// Show step-by-step process for mathematical method
echo "<h3>Step-by-Step Process (Mathematical Method):</h3>";
$tempNum = $number;
$reversed = 0;
$step = 1;
echo "<p>Original Number: $number</p>";
while ($tempNum > 0) {
$digit = $tempNum % 10;
$oldReversed = $reversed;
$reversed = ($reversed * 10) + $digit;
$tempNum = (int)($tempNum / 10);
echo "<p>Step $step: Extract digit = $digit, Reversed = ($oldReversed × 10) + $digit = $reversed, Remaining = $tempNum</p>";
$step++;
}
echo "<p>Final Reversed Number: $reversed</p>";
echo "<p>Comparison: $number " . ($number == $reversed ? "==" : "!=") . " $reversed</p>";
}
?>
<hr>
<h3>Test Examples:</h3>
<p>Palindrome numbers: 121, 1331, 12321, 9009, 4554</p>
<p>Non-palindrome numbers: 123, 1234, 567</p>
</body>
</html>
Explanation:
Method 1: String Reversal Approach
function isPalindromeString($number) {
$numStr = (string)$number; // Convert to string: "121"
$reversedStr = strrev($numStr); // Reverse: "121"
return $numStr === $reversedStr; // Compare: "121" === "121" → true
}
Method 2: Mathematical Approach
function isPalindromeMath($number) {
$original = $number; // Store original: 121
$reversed = 0;
while ($number > 0) {
$digit = $number % 10; // Get last digit: 1
$reversed = ($reversed * 10) + $digit; // Build reversed: 0*10+1=1
$number = (int)($number / 10); // Remove last digit: 12
}
return $original == $reversed; // 121 == 121 → true
}
Step-by-Step Example for 121:
| Iteration | Number | Digit | Reversed Calculation | Reversed | Remaining |
|---|---|---|---|---|---|
| Start | 121 | - | - | 0 | 121 |
| 1 | 121 | 1 | (0 × 10) + 1 | 1 | 12 |
| 2 | 12 | 2 | (1 × 10) + 2 | 12 | 1 |
| 3 | 1 | 1 | (12 × 10) + 1 | 121 | 0 |
| End | - | - | - | 121 | - |
Result: 121 == 121 ✓ Palindrome
Test Cases:
| Input | Reversed | Palindrome? | Explanation |
|---|---|---|---|
| 121 | 121 | Yes | Reads same both ways |
| 1331 | 1331 | Yes | Symmetrical |
| 12321 | 12321 | Yes | Perfect palindrome |
| 123 | 321 | No | Different when reversed |
| 9009 | 9009 | Yes | Palindrome with zeros |
| 7 | 7 | Yes | Single digit is palindrome |
Key Features:
- ✓ Two implementation methods (string and mathematical)
- ✓ Form-based input with validation
- ✓ Step-by-step process display
- ✓ Example table with multiple test cases
- ✓ Handles single-digit numbers
- ✓ Clear code documentation
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Function definition and structure │ 2 marks │
│ - Function name and parameter │ │
│ - Variable initialization │ │
│ - Proper function syntax │ │
│ │ │
│ 2. Logic to reverse the number │ 3 marks │
│ - While loop to extract digits │ │
│ - Extract digit using modulo (% 10) │ │
│ - Build reversed number (reversed*10+digit) │ │
│ - Remove last digit (number / 10) │ │
│ │ │
│ 3. Comparison and return result │ 2 marks │
│ - Compare original with reversed number │ │
│ - Return true/false or appropriate message │ │
│ - Display result to user │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Function + Logic + Validation (2 + 3 + 2)
Question 16 (14 marks) — #### a) Write a PHP script to print the sum of the digits of a three digit number. (7 marks)
a) Write a PHP script to print the sum of the digits of a three digit number. (7 marks)
Answer:
Overview: Create a PHP script that takes a three-digit number as input and calculates the sum of its individual digits. For example, for number 456: 4 + 5 + 6 = 15.
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum of Digits - Three Digit Number</title>
</head>
<body>
<h1>Sum of Digits Calculator</h1>
<p>Enter a three-digit number to calculate the sum of its digits</p>
<form method="POST" action="">
<label for="number">Enter a 3-digit number:</label>
<input type="number" id="number" name="number" min="100" max="999" required>
<button type="submit">Calculate Sum</button>
</form>
<?php
// Function to calculate sum of digits - Method 1 (Mathematical)
function sumOfDigitsMath($number) {
$sum = 0;
// Extract each digit and add to sum
while ($number > 0) {
$digit = $number % 10; // Get last digit
$sum += $digit; // Add to sum
$number = (int)($number / 10); // Remove last digit
}
return $sum;
}
// Function to calculate sum of digits - Method 2 (String)
function sumOfDigitsString($number) {
$numStr = (string)$number;
$sum = 0;
for ($i = 0; $i < strlen($numStr); $i++) {
$sum += (int)$numStr[$i];
}
return $sum;
}
// Function to get individual digits
function getDigits($number) {
$hundreds = (int)($number / 100);
$tens = (int)(($number % 100) / 10);
$units = $number % 10;
return array($hundreds, $tens, $units);
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['number'])) {
$number = (int)$_POST['number'];
// Validate three-digit number
if ($number < 100 || $number > 999) {
echo "<p style='color: red;'>Please enter a valid three-digit number (100-999)</p>";
} else {
// Calculate sum
$sum = sumOfDigitsMath($number);
// Get individual digits
list($hundreds, $tens, $units) = getDigits($number);
echo "<hr>";
echo "<h2>Result:</h2>";
echo "<p><strong>Number entered:</strong> $number</p>";
echo "<p><strong>Hundreds place:</strong> $hundreds</p>";
echo "<p><strong>Tens place:</strong> $tens</p>";
echo "<p><strong>Units place:</strong> $units</p>";
echo "<p><strong>Calculation:</strong> $hundreds + $tens + $units = $sum</p>";
echo "<p><strong>Sum of digits:</strong> $sum</p>";
// Show step-by-step process
echo "<h3>Step-by-Step Process (Mathematical Method):</h3>";
$tempNum = $number;
$tempSum = 0;
$step = 1;
echo "<p>Original Number: $number</p>";
while ($tempNum > 0) {
$digit = $tempNum % 10;
$tempSum += $digit;
$tempNum = (int)($tempNum / 10);
echo "<p>Step $step: Extract digit = $digit, Sum = $tempSum, Remaining = $tempNum</p>";
$step++;
}
echo "<p>Final Sum: $tempSum</p>";
}
}
?>
<hr>
<h3>Example Calculations:</h3>
<table border="1" cellpadding="5">
<tr>
<th>Number</th>
<th>Digits</th>
<th>Calculation</th>
<th>Sum</th>
</tr>
<tr>
<td>123</td>
<td>1, 2, 3</td>
<td>1 + 2 + 3</td>
<td>6</td>
</tr>
<tr>
<td>456</td>
<td>4, 5, 6</td>
<td>4 + 5 + 6</td>
<td>15</td>
</tr>
<tr>
<td>999</td>
<td>9, 9, 9</td>
<td>9 + 9 + 9</td>
<td>27</td>
</tr>
<tr>
<td>100</td>
<td>1, 0, 0</td>
<td>1 + 0 + 0</td>
<td>1</td>
</tr>
</table>
</body>
</html>
Explanation:
Method 1: Mathematical Approach
function sumOfDigitsMath($number) {
$sum = 0;
while ($number > 0) {
$digit = $number % 10; // Get last digit
$sum += $digit; // Add to sum
$number = (int)($number / 10); // Remove last digit
}
return $sum;
}
Step-by-Step Example for 456:
| Iteration | Number | Operation | Digit | Sum | Remaining |
|---|---|---|---|---|---|
| Start | 456 | - | - | 0 | 456 |
| 1 | 456 | 456 % 10 | 6 | 0 + 6 = 6 | 45 |
| 2 | 45 | 45 % 10 | 5 | 6 + 5 = 11 | 4 |
| 3 | 4 | 4 % 10 | 4 | 11 + 4 = 15 | 0 |
Final Sum: 15
Method 2: String Approach
function sumOfDigitsString($number) {
$numStr = (string)$number; // Convert to string: "456"
$sum = 0;
for ($i = 0; $i < strlen($numStr); $i++) {
$sum += (int)$numStr[$i]; // Add each character as integer
}
return $sum;
}
Method 3: Direct Extraction
function getDigits($number) {
$hundreds = (int)($number / 100); // 456 / 100 = 4
$tens = (int)(($number % 100) / 10); // (456 % 100) / 10 = 56 / 10 = 5
$units = $number % 10; // 456 % 10 = 6
return array($hundreds, $tens, $units);
}
// Sum: 4 + 5 + 6 = 15
Key Features:
- ✓ Form-based input with validation (100-999 range)
- ✓ Three different implementation methods
- ✓ Step-by-step calculation display
- ✓ Individual digit extraction
- ✓ Example table with multiple test cases
- ✓ Clean, exam-friendly code
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML form for input │ 2 marks │
│ - Form structure with method │ │
│ - Input field for 3-digit number │ │
│ - Submit button │ │
│ - Form validation (optional but adds value) │ │
│ │ │
│ 2. Logic to extract individual digits │ 3 marks │
│ - Extract first digit (hundreds place) │ │
│ - Extract second digit (tens place) │ │
│ - Extract third digit (units place) │ │
│ - Using % 10 and / 10 operations │ │
│ │ │
│ 3. Calculate sum and display result │ 2 marks │
│ - Add all three digits │ │
│ - Display formatted result │ │
│ - Show calculation breakdown │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML Form + Digit Logic + Display (2 + 3 + 2)
b) How are functions defined in PHP? Write a PHP function which checks whether a string passed to it starts with the character pattern "PHP". Apply pattern matching concept. (7 marks)
Answer:
Part 1: How Functions are Defined in PHP
PHP functions are reusable blocks of code that perform specific tasks. They help in code organization, reusability, and maintainability.
Function Syntax:
function functionName($parameter1, $parameter2, ...) {
// Function body
return $value; // Optional return statement
}
Key Components:
functionkeyword - Declares a function- Function name - Must start with letter or underscore, followed by letters, numbers, or underscores
- Parameters - Input values (optional)
- Function body - Code to be executed
- Return statement - Returns a value to caller (optional)
Function Types:
1. Function without parameters:
function greet() {
echo "Hello, World!";
}
greet(); // Outputs: Hello, World!
2. Function with parameters:
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3); // Returns: 8
3. Function with default parameters:
function greetUser($name = "Guest") {
return "Hello, $name!";
}
echo greetUser(); // Hello, Guest!
echo greetUser("John"); // Hello, John!
4. Function with return value:
function multiply($x, $y) {
return $x * $y;
}
$product = multiply(4, 5); // Returns: 20
5. Function with type declarations (PHP 7+):
function divide(float $a, float $b): float {
return $a / $b;
}
Part 2: Function to Check if String Starts with "PHP" Using Pattern Matching
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP String Pattern Matching</title>
</head>
<body>
<h1>Check if String Starts with "PHP"</h1>
<form method="POST" action="">
<label for="inputString">Enter a string:</label>
<input type="text" id="inputString" name="inputString" size="50" required>
<button type="submit">Check Pattern</button>
</form>
<?php
// Method 1: Using preg_match() with Regular Expression
function startsWithPHP_Regex($string) {
// Pattern: ^ = start of string, PHP = literal characters
// i = case-insensitive matching
return preg_match('/^PHP/i', $string) === 1;
}
// Method 2: Using substr() to extract beginning
function startsWithPHP_Substr($string) {
// Extract first 3 characters and compare
return substr($string, 0, 3) === 'PHP';
}
// Method 3: Using strpos() to find position
function startsWithPHP_Strpos($string) {
// Check if "PHP" is at position 0
return strpos($string, 'PHP') === 0;
}
// Method 4: Using str_starts_with() (PHP 8+)
function startsWithPHP_Native($string) {
if (function_exists('str_starts_with')) {
return str_starts_with($string, 'PHP');
}
return false;
}
// Main function using regex pattern matching
function checkPHPPattern($string) {
$pattern = '/^PHP/'; // Pattern to match "PHP" at start
if (preg_match($pattern, $string)) {
return true;
}
return false;
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['inputString'])) {
$inputString = $_POST['inputString'];
echo "<hr>";
echo "<h2>Results:</h2>";
echo "<p><strong>Input String:</strong> \"$inputString\"</p>";
// Test with all methods
$result1 = startsWithPHP_Regex($inputString);
$result2 = startsWithPHP_Substr($inputString);
$result3 = startsWithPHP_Strpos($inputString);
$result4 = checkPHPPattern($inputString);
echo "<h3>Method 1: Regular Expression (preg_match)</h3>";
echo "<p>Pattern: /^PHP/i (case-insensitive)</p>";
echo "<p>Result: " . ($result1 ? "TRUE - Starts with 'PHP'" : "FALSE - Does not start with 'PHP'") . "</p>";
echo "<h3>Method 2: Substring Extraction (substr)</h3>";
echo "<p>Checking first 3 characters: " . substr($inputString, 0, 3) . "</p>";
echo "<p>Result: " . ($result2 ? "TRUE - Starts with 'PHP'" : "FALSE - Does not start with 'PHP'") . "</p>";
echo "<h3>Method 3: String Position (strpos)</h3>";
echo "<p>Position of 'PHP': " . (strpos($inputString, 'PHP') !== false ? strpos($inputString, 'PHP') : "Not found") . "</p>";
echo "<p>Result: " . ($result3 ? "TRUE - Starts with 'PHP'" : "FALSE - Does not start with 'PHP'") . "</p>";
echo "<h3>Method 4: Pattern Matching (checkPHPPattern)</h3>";
echo "<p>Pattern: /^PHP/ (exact match at start)</p>";
echo "<p>Result: " . ($result4 ? "TRUE - Starts with 'PHP'" : "FALSE - Does not start with 'PHP'") . "</p>";
// Advanced pattern matching examples
echo "<h3>Additional Pattern Matching Examples:</h3>";
// Case-insensitive
echo "<p><strong>Case-insensitive match:</strong> " .
(preg_match('/^PHP/i', $inputString) ? "Yes" : "No") . "</p>";
// Match with word boundary
echo "<p><strong>PHP as whole word:</strong> " .
(preg_match('/^PHP\b/', $inputString) ? "Yes" : "No") . "</p>";
// Match PHP followed by space or number
echo "<p><strong>PHP followed by space or number:</strong> " .
(preg_match('/^PHP[\s\d]/', $inputString) ? "Yes" : "No") . "</p>";
}
?>
<hr>
<h3>Test Examples:</h3>
<table border="1" cellpadding="5">
<tr>
<th>String</th>
<th>Starts with "PHP"?</th>
<th>Pattern Match</th>
</tr>
<tr>
<td>PHP is awesome</td>
<td>Yes</td>
<td>/^PHP/ matches</td>
</tr>
<tr>
<td>PHP7.4</td>
<td>Yes</td>
<td>/^PHP/ matches</td>
</tr>
<tr>
<td>Learning PHP programming</td>
<td>No</td>
<td>/^PHP/ does not match (PHP not at start)</td>
</tr>
<tr>
<td>php scripting</td>
<td>No (case-sensitive)</td>
<td>/^PHP/ does not match, /^PHP/i would match</td>
</tr>
<tr>
<td>PHPStorm IDE</td>
<td>Yes</td>
<td>/^PHP/ matches</td>
</tr>
</table>
<hr>
<h3>Regular Expression Pattern Explanation:</h3>
<table border="1" cellpadding="5">
<tr>
<th>Pattern</th>
<th>Meaning</th>
<th>Example</th>
</tr>
<tr>
<td>/^PHP/</td>
<td>^ = start of string, PHP = literal</td>
<td>Matches "PHP is great"</td>
</tr>
<tr>
<td>/^PHP/i</td>
<td>i = case-insensitive</td>
<td>Matches "php is great" or "PHP is great"</td>
</tr>
<tr>
<td>/^PHP\s/</td>
<td>\s = whitespace after PHP</td>
<td>Matches "PHP programming" but not "PHPStorm"</td>
</tr>
<tr>
<td>/^PHP[\d]/</td>
<td>[\d] = digit after PHP</td>
<td>Matches "PHP7" or "PHP8"</td>
</tr>
</table>
</body>
</html>
Explanation:
Regular Expression Pattern Matching:
function checkPHPPattern($string) {
$pattern = '/^PHP/'; // ^ means "start of string"
if (preg_match($pattern, $string)) {
return true; // Pattern matches
}
return false; // Pattern doesn't match
}
Pattern Components:
/- Delimiter for regex pattern^- Anchor: Matches start of stringPHP- Literal characters to match/- Closing delimiter
Key PHP String Functions:
1. preg_match() - Pattern matching
preg_match('/^PHP/', $string); // Returns 1 if matches, 0 if not
2. substr() - Extract substring
substr($string, 0, 3) === 'PHP' // Compare first 3 characters
3. strpos() - Find string position
strpos($string, 'PHP') === 0 // Check if PHP is at position 0
Test Cases:
| Input String | Starts with "PHP"? | Reason |
|---|---|---|
| "PHP is great" | ✓ Yes | Starts exactly with PHP |
| "PHP7.4" | ✓ Yes | Starts with PHP |
| "Learning PHP" | ✗ No | PHP not at beginning |
| "php scripting" | ✗ No | Lowercase (case-sensitive) |
| "PHPStorm IDE" | ✓ Yes | Starts with PHP |
Key Features:
- ✓ Multiple implementation methods
- ✓ Regular expression pattern matching
- ✓ Form-based input
- ✓ Detailed explanation of each method
- ✓ Pattern syntax table
- ✓ Comprehensive test examples
- ✓ Case-sensitive and case-insensitive options
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. How functions are defined in PHP │ 3 marks │
│ - Function syntax and structure │ │
│ - Parameters and return values │ │
│ - Function types (built-in vs user-defined) │ │
│ - Examples of function definition │ │
│ │ │
│ 2. Pattern matching function implementation │ 4 marks │
│ - Function definition with parameter │ 1 mark │
│ - Regular expression pattern (/^PHP/) │ 1.5 marks │
│ - preg_match() or equivalent implementation │ 1 mark │
│ - Return value and result display │ 0.5 marks │
│ │ │
│ Alternative methods (bonus understanding): │ │
│ - substr() method │ │
│ - strpos() method │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Function Definition + Pattern Matching (3 + 4)
Question 18 (14 marks) — #### a) Write a HTML file to create a form for collecting details of a student like name, branch, age and phone number. Create a PHP script that validates the phone number when the form data is submitted using a 'Register' Button. If not valid the error message 'Enter a valid phone number' is to be displayed. (7 marks)
a) Write a HTML file to create a form for collecting details of a student like name, branch, age and phone number. Create a PHP script that validates the phone number when the form data is submitted using a 'Register' Button. If not valid the error message 'Enter a valid phone number' is to be displayed. (7 marks)
Answer:
Overview: Create an HTML form that collects student details (name, branch, age, phone number) and uses PHP to validate the phone number using pattern matching when the Register button is clicked.
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
</head>
<body>
<h1>Student Registration Form</h1>
<p>Please fill in your details to register</p>
<?php
// Function to validate phone number
function validatePhoneNumber($phone) {
// Remove any spaces, dashes, or parentheses
$phone = preg_replace('/[\s\-\(\)]/', '', $phone);
// Check if phone number contains only digits
if (!preg_match('/^\d+$/', $phone)) {
return false;
}
// Check if phone number is 10 digits (Indian format)
if (preg_match('/^[6-9]\d{9}$/', $phone)) {
return true;
}
// Check if phone number is 11 digits starting with 0
if (preg_match('/^0[6-9]\d{9}$/', $phone)) {
return true;
}
// Check if phone number is 12 digits starting with 91 (country code)
if (preg_match('/^91[6-9]\d{9}$/', $phone)) {
return true;
}
return false;
}
// Initialize variables
$name = $branch = $age = $phone = "";
$phoneError = "";
$registrationSuccess = false;
// Process form submission
if (isset($_POST['register'])) {
$name = trim($_POST['name']);
$branch = trim($_POST['branch']);
$age = (int)$_POST['age'];
$phone = trim($_POST['phone']);
// Validate phone number
if (validatePhoneNumber($phone)) {
$registrationSuccess = true;
} else {
$phoneError = "Enter a valid phone number";
}
}
?>
<?php if ($registrationSuccess): ?>
<div style="background-color: #d4edda; color: #155724; padding: 15px; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 20px;">
<h2>Registration Successful!</h2>
<p><strong>Name:</strong> <?php echo htmlspecialchars($name); ?></p>
<p><strong>Branch:</strong> <?php echo htmlspecialchars($branch); ?></p>
<p><strong>Age:</strong> <?php echo $age; ?></p>
<p><strong>Phone Number:</strong> <?php echo htmlspecialchars($phone); ?></p>
</div>
<?php endif; ?>
<?php if ($phoneError): ?>
<div style="background-color: #f8d7da; color: #721c24; padding: 15px; border: 1px solid #f5c6cb; border-radius: 4px; margin-bottom: 20px;">
<strong>Error:</strong> <?php echo $phoneError; ?>
</div>
<?php endif; ?>
<form method="POST" action="">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" size="30" required value="<?php echo htmlspecialchars($name); ?>">
<br><br>
<label for="branch">Branch:</label><br>
<select id="branch" name="branch" required>
<option value="">-- Select Branch --</option>
<option value="Computer Science" <?php if($branch == "Computer Science") echo "selected"; ?>>Computer Science</option>
<option value="Information Technology" <?php if($branch == "Information Technology") echo "selected"; ?>>Information Technology</option>
<option value="Electronics" <?php if($branch == "Electronics") echo "selected"; ?>>Electronics</option>
<option value="Mechanical" <?php if($branch == "Mechanical") echo "selected"; ?>>Mechanical</option>
<option value="Civil" <?php if($branch == "Civil") echo "selected"; ?>>Civil</option>
<option value="Electrical" <?php if($branch == "Electrical") echo "selected"; ?>>Electrical</option>
</select>
<br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age" min="15" max="100" required value="<?php echo $age > 0 ? $age : ''; ?>">
<br><br>
<label for="phone">Phone Number:</label><br>
<input type="tel" id="phone" name="phone" size="30" required value="<?php echo htmlspecialchars($phone); ?>" placeholder="Enter 10-digit mobile number">
<br><br>
<button type="submit" name="register">Register</button>
</form>
<hr>
<h3>Phone Number Format Guidelines:</h3>
<table border="1" cellpadding="5">
<tr>
<th>Format</th>
<th>Example</th>
<th>Valid?</th>
</tr>
<tr>
<td>10 digits (starts with 6-9)</td>
<td>9876543210</td>
<td>✓ Yes</td>
</tr>
<tr>
<td>11 digits (starts with 0)</td>
<td>09876543210</td>
<td>✓ Yes</td>
</tr>
<tr>
<td>12 digits (starts with 91)</td>
<td>919876543210</td>
<td>✓ Yes</td>
</tr>
<tr>
<td>With spaces/dashes</td>
<td>98765-43210 or 987 654 3210</td>
<td>✓ Yes (automatically cleaned)</td>
</tr>
<tr>
<td>Less than 10 digits</td>
<td>987654</td>
<td>✗ No</td>
</tr>
<tr>
<td>Starts with 0-5</td>
<td>5876543210</td>
<td>✗ No</td>
</tr>
<tr>
<td>Contains letters</td>
<td>98765abc10</td>
<td>✗ No</td>
</tr>
</table>
</body>
</html>
Explanation:
HTML Form Structure:
<form method="POST" action="">
<input type="text" name="name" required>
<select name="branch" required></select>
<input type="number" name="age" min="15" max="100" required>
<input type="tel" name="phone" required>
<button type="submit" name="register">Register</button>
</form>
Key Form Elements:
- Name field: Text input with
requiredattribute - Branch field: Dropdown (select) with predefined options
- Age field: Number input with min/max constraints
- Phone field: Tel input for phone number
- Register button: Submit button with name="register"
PHP Phone Number Validation:
Validation Function:
function validatePhoneNumber($phone) {
// Remove spaces, dashes, parentheses
$phone = preg_replace('/[\s\-\(\)]/', '', $phone);
// Check if only digits
if (!preg_match('/^\d+$/', $phone)) {
return false;
}
// Pattern 1: 10 digits starting with 6-9
if (preg_match('/^[6-9]\d{9}$/', $phone)) {
return true;
}
// Pattern 2: 11 digits starting with 0
if (preg_match('/^0[6-9]\d{9}$/', $phone)) {
return true;
}
// Pattern 3: 12 digits starting with 91
if (preg_match('/^91[6-9]\d{9}$/', $phone)) {
return true;
}
return false;
}
Regular Expression Patterns:
-
/^[6-9]\d{9}$/- 10-digit Indian mobile number^- Start of string[6-9]- First digit must be 6, 7, 8, or 9\d{9}- Exactly 9 more digits$- End of string
-
/^0[6-9]\d{9}$/- 11-digit with leading 0 -
/^91[6-9]\d{9}$/- 12-digit with country code 91
Form Processing Logic:
if (isset($_POST['register'])) {
$name = trim($_POST['name']);
$branch = trim($_POST['branch']);
$age = (int)$_POST['age'];
$phone = trim($_POST['phone']);
if (validatePhoneNumber($phone)) {
$registrationSuccess = true;
// Display success message with details
} else {
$phoneError = "Enter a valid phone number";
// Display error message
}
}
Security Features:
trim()- Removes whitespacehtmlspecialchars()- Prevents XSS attacks- Input validation before processing
- Type casting for age
(int)
Test Cases:
| Phone Number | Cleaned | Pattern | Valid? |
|---|---|---|---|
| 9876543210 | 9876543210 | 10 digits | ✓ Yes |
| 09876543210 | 09876543210 | 11 digits | ✓ Yes |
| 919876543210 | 919876543210 | 12 digits | ✓ Yes |
| 98765-43210 | 9876543210 | 10 digits | ✓ Yes |
| 5876543210 | 5876543210 | Starts with 5 | ✗ No |
| 98765 | 98765 | Too short | ✗ No |
| 98765abc10 | - | Contains letters | ✗ No |
Key Features:
- ✓ Complete HTML form with all required fields
- ✓ PHP phone number validation using regex
- ✓ Error message display as specified
- ✓ Success message with submitted details
- ✓ Form field persistence (values retained after submission)
- ✓ Security measures (XSS prevention)
- ✓ Multiple phone format support
- ✓ User-friendly dropdown for branch selection
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML form creation │ 3 marks │
│ - Form structure with action/method │ │
│ - Name input field │ │
│ - Branch input field │ │
│ - Age input field │ │
│ - Phone number input field │ │
│ - Register button │ │
│ │ │
│ 2. PHP phone number validation │ 3 marks │
│ - Retrieve form data ($_POST) │ │
│ - Validation logic (regex pattern) │ │
│ - Check for valid phone format │ │
│ - Regular expression implementation │ │
│ │ │
│ 3. Error/Success message display │ 1 mark │
│ - Display "Enter a valid phone number" error│ │
│ - Show success message when valid │ │
│ - Conditional message rendering │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML Form + PHP Validation + Display (3 + 3 + 1)
b) Explain the server side sessions in detail. (7 marks)
Answer:
Definition:
Server-side sessions are a mechanism to preserve user state and data across multiple HTTP requests. Unlike cookies (stored on client), session data is stored on the server, making it more secure for sensitive information.
Why Sessions are Needed:
- HTTP is Stateless - Each HTTP request is independent; sessions maintain state
- User Authentication - Track logged-in users across pages
- Shopping Carts - Store items user wants to purchase
- Multi-step Forms - Preserve data across form pages
- User Preferences - Remember settings during browsing session
- Secure Data Storage - Store sensitive data server-side
How Server-Side Sessions Work:
┌─────────────┐ ┌──────────────┐
│ Client │ │ Server │
│ Browser │ │ │
└──────┬──────┘ └──────┬───────┘
│ │
│ 1. First Request (Login) │
│─────────────────────────────────────────────────>│
│ │
│ 2. Start Session │
│ session_start() │
│ Generate Session ID │
│ Store data on server│
│ │
│ 3. Response + Set Session Cookie │
│<─────────────────────────────────────────────────│
│ Set-Cookie: PHPSESSID=abc123xyz... │
│ │
│ (Browser stores session ID cookie) │
│ │
│ 4. Subsequent Request + Session Cookie │
│─────────────────────────────────────────────────>│
│ Cookie: PHPSESSID=abc123xyz... │
│ │
│ 5. Retrieve Session │
│ session_start() │
│ Load $_SESSION data │
│ │
│ 6. Response with personalized content │
│<─────────────────────────────────────────────────│
│ │
Session Lifecycle:
1. Session Initialization
session_start(); // Must be called before any output
2. Storing Data in Session
$_SESSION['user_id'] = 123;
$_SESSION['username'] = "john_doe";
$_SESSION['role'] = "admin";
3. Retrieving Session Data
if (isset($_SESSION['username'])) {
echo "Welcome, " . $_SESSION['username'];
}
4. Destroying Session
session_destroy(); // Destroys all session data
Complete Example - Login System with Sessions:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Management Example</title>
</head>
<body>
<h1>Server-Side Session Management Demo</h1>
<?php
// Start session (must be called before any output)
session_start();
// Hardcoded credentials for demonstration
$valid_username = "admin";
$valid_password = "password123";
// Handle login
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === $valid_username && $password === $valid_password) {
// Store user information in session
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $username;
$_SESSION['login_time'] = date('Y-m-d H:i:s');
$_SESSION['page_views'] = 1;
echo "<p style='color: green;'>Login successful! Welcome, $username</p>";
} else {
echo "<p style='color: red;'>Invalid username or password</p>";
}
}
// Handle logout
if (isset($_POST['logout'])) {
// Destroy session
session_unset(); // Remove all session variables
session_destroy(); // Destroy session
echo "<p style='color: blue;'>You have been logged out successfully</p>";
}
// Check if user is logged in
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
// Increment page views
if (isset($_SESSION['page_views'])) {
$_SESSION['page_views']++;
}
// User is logged in - show profile
?>
<h2>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h2>
<div style="background-color: #e8f4f8; padding: 15px; border-radius: 5px; margin: 20px 0;">
<h3>Session Information:</h3>
<p><strong>Session ID:</strong> <?php echo session_id(); ?></p>
<p><strong>Username:</strong> <?php echo $_SESSION['username']; ?></p>
<p><strong>Login Time:</strong> <?php echo $_SESSION['login_time']; ?></p>
<p><strong>Page Views:</strong> <?php echo $_SESSION['page_views']; ?></p>
<p><strong>Session Status:</strong> Active</p>
</div>
<form method="POST" action="">
<button type="submit" name="logout">Logout</button>
</form>
<hr>
<h3>Session Data Stored on Server:</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php
} else {
// User is not logged in - show login form
?>
<h2>Login Form</h2>
<p>Please login to access your session</p>
<form method="POST" action="">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<button type="submit" name="login">Login</button>
</form>
<p style="background-color: #fff3cd; padding: 10px; border-radius: 5px; margin-top: 20px;">
<strong>Demo Credentials:</strong><br>
Username: admin<br>
Password: password123
</p>
<?php
}
?>
<hr>
<h2>PHP Session Functions:</h2>
<table border="1" cellpadding="10">
<tr>
<th>Function</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr>
<td><code>session_start()</code></td>
<td>Initializes or resumes session</td>
<td><code>session_start();</code></td>
</tr>
<tr>
<td><code>session_id()</code></td>
<td>Gets or sets session ID</td>
<td><code>echo session_id();</code></td>
</tr>
<tr>
<td><code>session_destroy()</code></td>
<td>Destroys all session data</td>
<td><code>session_destroy();</code></td>
</tr>
<tr>
<td><code>session_unset()</code></td>
<td>Removes all session variables</td>
<td><code>session_unset();</code></td>
</tr>
<tr>
<td><code>session_name()</code></td>
<td>Gets or sets session name</td>
<td><code>session_name("MyApp");</code></td>
</tr>
<tr>
<td><code>session_regenerate_id()</code></td>
<td>Regenerates session ID</td>
<td><code>session_regenerate_id(true);</code></td>
</tr>
<tr>
<td><code>$_SESSION</code></td>
<td>Superglobal array to store session data</td>
<td><code>$_SESSION['key'] = 'value';</code></td>
</tr>
</table>
<hr>
<h2>Session Configuration (php.ini):</h2>
<table border="1" cellpadding="10">
<tr>
<th>Directive</th>
<th>Description</th>
<th>Default Value</th>
</tr>
<tr>
<td><code>session.save_handler</code></td>
<td>Where sessions are stored</td>
<td>files</td>
</tr>
<tr>
<td><code>session.save_path</code></td>
<td>Directory where session files are saved</td>
<td>/tmp</td>
</tr>
<tr>
<td><code>session.name</code></td>
<td>Name of session cookie</td>
<td>PHPSESSID</td>
</tr>
<tr>
<td><code>session.cookie_lifetime</code></td>
<td>Session cookie expiration (seconds)</td>
<td>0 (until browser closes)</td>
</tr>
<tr>
<td><code>session.gc_maxlifetime</code></td>
<td>Session data lifetime (seconds)</td>
<td>1440 (24 minutes)</td>
</tr>
</table>
</body>
</html>
Key Session Concepts:
1. Session ID:
- Unique identifier for each session
- Generated automatically by PHP
- Typically 32-character hexadecimal string
- Stored in cookie named
PHPSESSIDby default
2. Session Storage:
- By default, stored as files on server
- File location:
/tmpor path specified inphp.ini - Filename format:
sess_[SESSION_ID] - Can be stored in database, memory (Redis), or other handlers
3. Session Data:
- Stored in
$_SESSIONsuperglobal array - Serialized and saved to server storage
- Automatically loaded when
session_start()is called - Accessible across all pages of the application
Common Session Operations:
1. Check if Session Variable Exists:
if (isset($_SESSION['user_id'])) {
// User is logged in
}
2. Remove Specific Session Variable:
unset($_SESSION['cart']); // Remove cart from session
3. Complete Session Cleanup:
session_start();
session_unset(); // Remove all variables
session_destroy(); // Destroy session
setcookie(session_name(), '', time()-3600, '/'); // Delete cookie
4. Session Regeneration (Security):
session_regenerate_id(true); // Prevent session fixation attacks
Sessions vs Cookies:
| Aspect | Sessions | Cookies |
|---|---|---|
| Storage Location | Server | Client browser |
| Data Size | Unlimited (server-dependent) | ~4KB per cookie |
| Security | More secure (data on server) | Less secure (visible to client) |
| Expiration | Ends when browser closes or timeout | Can persist for years |
| Access | Server-side only | Client and server |
| Performance | Slight server overhead | No server storage needed |
| Data Type | Any PHP data type | String only |
Session Security Best Practices:
- Use HTTPS - Encrypt session cookie transmission
- Regenerate Session ID - After login to prevent fixation attacks
- Set Secure Flags -
session.cookie_secure = 1(HTTPS only) - Set HttpOnly Flag -
session.cookie_httponly = 1(prevent JavaScript access) - Short Timeout - Set appropriate
session.gc_maxlifetime - Validate User Agent - Store and verify browser fingerprint
- IP Address Validation - Check for IP changes (with caution)
- Strong Session IDs - Use
session.sid_bits_per_character = 6
Session Timeout Example:
session_start();
$timeout_duration = 1800; // 30 minutes
if (isset($_SESSION['last_activity'])) {
$elapsed_time = time() - $_SESSION['last_activity'];
if ($elapsed_time > $timeout_duration) {
session_unset();
session_destroy();
echo "Session expired due to inactivity";
exit();
}
}
$_SESSION['last_activity'] = time(); // Update last activity time
Advantages of Server-Side Sessions:
- ✓ Secure - Data stored on server
- ✓ Large storage capacity
- ✓ Support complex data types
- ✓ Cannot be modified by users
- ✓ Automatic expiration handling
Disadvantages:
- ✗ Server resource consumption
- ✗ Scalability challenges (load balancing)
- ✗ Requires cookie for session ID
- ✗ Lost if server restarts (file-based)
MODULE IV — MODULE IV
Question 17 (14 marks) — #### a) Why are cookies used in web pages? With an example explain how cookies are written to the client. (7 marks)
a) Why are cookies used in web pages? With an example explain how cookies are written to the client. (7 marks)
Answer:
Definition:
Cookies are small text files stored on the client's browser by a web server. They contain data in key-value pairs and are sent back to the server with every HTTP request to that domain.
Why Cookies are Used in Web Pages:
1. Session Management
- User login status and authentication
- Shopping cart contents
- Game scores and user preferences
2. Personalization
- User preferences (theme, language, font size)
- Customized content based on previous visits
- Remember user settings
3. Tracking and Analytics
- Track user behavior and navigation patterns
- Analyze website usage statistics
- Monitor user engagement
4. Remember User Information
- "Remember Me" functionality for login
- Auto-fill form data
- Recently viewed items
5. Advertisement Targeting
- Display relevant ads based on browsing history
- Track ad campaign effectiveness
6. Maintain State
- HTTP is stateless; cookies help maintain state across requests
- Keep track of user actions across multiple pages
Writing Cookies to Client - PHP Example:
<?php
// Example 1: Simple cookie (30 days)
$cookie_name = "username";
$cookie_value = "JohnDoe123";
$expiry_time = time() + (30 * 24 * 60 * 60); // 30 days
setcookie($cookie_name, $cookie_value, $expiry_time, "/");
// Example 2: Reading cookies
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
}
// Example 3: Deleting cookies
setcookie("username", "", time() - 3600);
?>
Key Features:
- ✓ Persistent storage across browser sessions
- ✓ Automatic transmission with each HTTP request
- ✓ Simple key-value pair storage
- ✓ Configurable expiration times
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and concept of sessions │ 1 mark │
│ - What are server-side sessions │ │
│ - Purpose and significance │ │
│ │ │
│ 2. How sessions work (lifecycle and mechanism) │ 3 marks │
│ - session_start() function │ │
│ - Session ID generation and storage │ │
│ - $_SESSION superglobal array │ │
│ - Session data storage on server │ │
│ - Cookie-based session tracking │ │
│ │ │
│ 3. Session operations with examples │ 3 marks │
│ - Creating/setting session variables │ │
│ - Reading session variables │ │
│ - Modifying session data │ │
│ - Destroying sessions (session_destroy) │ │
│ - Code examples demonstrating operations │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Mechanism + Operations (1 + 3 + 3)
b) Design an HTML form for entering a number by the user. Write a PHP code to display a message indicating whether the number is even or not when clicking on the submit button. (7 marks)
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Even or Odd Number Checker</title>
</head>
<body>
<h1>Even or Odd Number Checker</h1>
<form method="POST" action="">
<label for="number">Enter a Number:</label>
<input type="number" id="number" name="number" required>
<button type="submit" name="submit">Check Even/Odd</button>
</form>
<?php
// Function to check if number is even
function isEven($number) {
return $number % 2 == 0;
}
// Process form submission
if (isset($_POST['submit']) && isset($_POST['number'])) {
$number = (int)$_POST['number'];
echo "<hr>";
echo "<h2>Result:</h2>";
echo "<p><strong>Number entered:</strong> $number</p>";
if (isEven($number)) {
echo "<p><strong>$number is an EVEN number</strong></p>";
} else {
echo "<p><strong>$number is an ODD number</strong></p>";
}
}
?>
</body>
</html>
Key Features:
- ✓ HTML form with number input
- ✓ PHP modulo operator for even/odd check
- ✓ Self-processing form
- ✓ Clear result display
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML form creation │ 2 marks │
│ - Form structure with action/method │ │
│ - Number input field │ │
│ - Submit button │ │
│ │ │
│ 2. PHP even/odd checking logic │ 3 marks │
│ - Retrieve number from form ($_POST) │ │
│ - Modulo operator (% 2) to check even/odd │ │
│ - Conditional logic (if-else) │ │
│ - Correct algorithm implementation │ │
│ │ │
│ 3. Display result message │ 2 marks │
│ - Display "even" or "not even" message │ │
│ - Show the entered number │ │
│ - Proper formatting and presentation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML Form + Logic + Display (2 + 3 + 2)
MODULE V — MODULE V
Question 19 (14 marks) — #### a) How are objects created in JSON? What are the different ways of accessing objects using JSON? (7 marks)
a) How are objects created in JSON? What are the different ways of accessing objects using JSON? (7 marks)
Answer:
Definition:
JSON (JavaScript Object Notation) is a lightweight data interchange format that uses human-readable text to store and transmit data objects consisting of key-value pairs and arrays.
Creating Objects in JSON:
JSON Object Syntax:
{
"key1": "value1",
"key2": "value2",
"key3": value3
}
Example 1: Simple JSON Object
{
"name": "John Doe",
"age": 25,
"email": "john@example.com",
"active": true
}
Example 2: Nested JSON Object
{
"student": {
"id": 101,
"name": "Alice Smith",
"course": "Computer Science",
"grades": {
"math": 95,
"physics": 88,
"programming": 92
}
}
}
Example 3: JSON Object with Array
{
"company": "Tech Corp",
"employees": [
{"id": 1, "name": "John", "role": "Developer"},
{"id": 2, "name": "Jane", "role": "Designer"},
{"id": 3, "name": "Bob", "role": "Manager"}
]
}
Example 4: Complex JSON Structure
{
"university": "KTU",
"departments": [
{
"name": "Computer Science",
"hod": "Dr. Smith",
"students": 150,
"courses": ["CST463", "CST465", "CST401"]
},
{
"name": "Electronics",
"hod": "Dr. Johnson",
"students": 120,
"courses": ["ECT301", "ECT303"]
}
]
}
Different Ways of Accessing JSON Objects:
Method 1: JavaScript - Dot Notation
let student = {
"name": "John Doe",
"age": 25,
"course": "CST463"
};
console.log(student.name); // "John Doe"
console.log(student.age); // 25
console.log(student.course); // "CST463"
Method 2: JavaScript - Bracket Notation
let student = {
"name": "John Doe",
"age": 25,
"course": "CST463"
};
console.log(student["name"]); // "John Doe"
console.log(student["age"]); // 25
console.log(student["course"]); // "CST463"
// Useful for dynamic keys
let key = "name";
console.log(student[key]); // "John Doe"
Method 3: JavaScript - Parse JSON String
// JSON string
let jsonString = '{"name":"John Doe","age":25,"course":"CST463"}';
// Parse JSON string to object
let student = JSON.parse(jsonString);
console.log(student.name); // "John Doe"
console.log(student.age); // 25
Method 4: JavaScript - Access Nested Objects
let data = {
"student": {
"personal": {
"name": "John Doe",
"age": 25
},
"academic": {
"course": "CST463",
"grade": "A"
}
}
};
console.log(data.student.personal.name); // "John Doe"
console.log(data.student.academic.course); // "CST463"
console.log(data["student"]["personal"]["age"]); // 25
Method 5: JavaScript - Access Arrays in JSON
let data = {
"courses": ["CST463", "CST465", "CST401"]
};
console.log(data.courses[0]); // "CST463"
console.log(data.courses[1]); // "CST465"
console.log(data.courses.length); // 3
// Loop through array
data.courses.forEach(course => {
console.log(course);
});
Method 6: PHP - Accessing JSON Objects
<?php
// JSON string
$jsonString = '{"name":"John Doe","age":25,"course":"CST463"}';
// Method 1: Decode as associative array
$student = json_decode($jsonString, true);
echo $student['name']; // "John Doe"
echo $student['age']; // 25
// Method 2: Decode as object
$studentObj = json_decode($jsonString);
echo $studentObj->name; // "John Doe"
echo $studentObj->age; // 25
?>
Method 7: PHP - Accessing Nested JSON
<?php
$jsonString = '{
"student": {
"name": "John Doe",
"grades": {
"math": 95,
"physics": 88
}
}
}';
$data = json_decode($jsonString, true);
echo $data['student']['name']; // "John Doe"
echo $data['student']['grades']['math']; // 95
?>
Complete Example - HTML/JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Object Access Methods</title>
</head>
<body>
<h1>Accessing JSON Objects</h1>
<div id="output"></div>
<script>
// Create JSON object
let student = {
"id": 101,
"name": "John Doe",
"age": 25,
"email": "john@example.com",
"courses": ["CST463", "CST465", "CST401"],
"address": {
"city": "Trivandrum",
"state": "Kerala",
"pincode": "695001"
}
};
let output = document.getElementById('output');
output.innerHTML = `
<h2>Method 1: Dot Notation</h2>
<p>Name: ${student.name}</p>
<p>Age: ${student.age}</p>
<p>City: ${student.address.city}</p>
<h2>Method 2: Bracket Notation</h2>
<p>Email: ${student["email"]}</p>
<p>State: ${student["address"]["state"]}</p>
<h2>Method 3: Array Access</h2>
<p>First Course: ${student.courses[0]}</p>
<p>Second Course: ${student.courses[1]}</p>
<h2>Method 4: Loop Through Array</h2>
<ul>
${student.courses.map(course => `<li>${course}</li>`).join('')}
</ul>
<h2>Method 5: Convert to JSON String</h2>
<pre>${JSON.stringify(student, null, 2)}</pre>
`;
</script>
</body>
</html>
Summary of Access Methods:
| Method | Syntax | Use Case |
|---|---|---|
| Dot Notation | object.property |
Static property names |
| Bracket Notation | object["property"] |
Dynamic property names |
| Parse String | JSON.parse(string) |
Convert JSON string to object |
| Nested Access | object.nested.property |
Multi-level objects |
| Array Access | object.array[index] |
Array elements |
| PHP Array | $data['key'] |
PHP associative array |
| PHP Object | $data->key |
PHP object notation |
Key Features:
- ✓ Multiple access methods for flexibility
- ✓ Support for nested structures
- ✓ Array and object combinations
- ✓ Cross-language compatibility (JavaScript, PHP)
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. How objects are created in JSON │ 3 marks │
│ - JSON object syntax { key: value } │ │
│ - Creating objects with properties │ │
│ - Nested objects │ │
│ - Code examples │ │
│ │ │
│ 2. Different ways of accessing JSON objects │ 4 marks │
│ - Dot notation (obj.property) │ 1 mark │
│ - Bracket notation (obj["property"]) │ 1 mark │
│ - JavaScript access methods │ 1 mark │
│ - PHP json_decode() and access │ 1 mark │
│ - Examples demonstrating each method │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Creation + Access Methods (3 + 4)
b) Explain route model binding in Laravel. (7 marks)
Answer:
Definition:
Route Model Binding is a Laravel feature that automatically injects model instances directly into routes based on route parameters. Instead of manually retrieving models by ID, Laravel automatically resolves the model instance.
Types of Route Model Binding:
1. Implicit Binding
2. Explicit Binding
1. Implicit Route Model Binding:
Laravel automatically resolves Eloquent models defined in routes whose variable names match route segment names.
Example:
Route Definition (routes/web.php):
Route::get('/students/{student}', [StudentController::class, 'show']);
Controller (app/Http/Controllers/StudentController.php):
<?php
namespace App\Http\Controllers;
use App\Models\Student;
class StudentController extends Controller
{
// Laravel automatically injects Student model
public function show(Student $student)
{
// $student is automatically fetched from database
// No need for: $student = Student::findOrFail($id);
return view('students.show', compact('student'));
}
}
Without Route Model Binding (Traditional Way):
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student'));
}
With Route Model Binding:
public function show(Student $student)
{
// Student automatically loaded by Laravel
return view('students.show', compact('student'));
}
How It Works:
- URL:
/students/5 - Laravel sees
{student}parameter - Checks for
Student $studenttype-hint in controller - Executes:
Student::where('id', 5)->firstOrFail() - Injects model instance or returns 404 if not found
2. Explicit Route Model Binding:
Define custom resolution logic in RouteServiceProvider.
Example - Bind by Slug Instead of ID:
RouteServiceProvider (app/Providers/RouteServiceProvider.php):
<?php
namespace App\Providers;
use App\Models\Student;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
public function boot()
{
// Explicit binding: resolve by slug instead of id
Route::model('student', Student::class);
// Custom resolution
Route::bind('student', function ($value) {
return Student::where('slug', $value)->firstOrFail();
});
}
}
Route:
Route::get('/students/{student}', [StudentController::class, 'show']);
Controller:
public function show(Student $student)
{
// $student resolved by slug, not id
return view('students.show', compact('student'));
}
URL: /students/john-doe (slug) instead of /students/5 (id)
Customizing the Key (Implicit Binding):
Model (app/Models/Student.php):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
// Use 'slug' column instead of 'id' for route binding
public function getRouteKeyName()
{
return 'slug';
}
}
Route:
Route::get('/students/{student}', [StudentController::class, 'show']);
Now URL: /students/john-doe automatically works!
Soft Deleted Models:
Include soft-deleted models in route binding:
Route:
Route::get('/students/{student}', [StudentController::class, 'show'])
->withTrashed();
Now route binding includes soft-deleted students.
Complete Example:
Migration:
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('slug')->unique();
$table->string('course');
$table->integer('age');
$table->timestamps();
});
Model (app/Models/Student.php):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['name', 'email', 'slug', 'course', 'age'];
// Route binding using slug
public function getRouteKeyName()
{
return 'slug';
}
}
Routes (routes/web.php):
<?php
use App\Http\Controllers\StudentController;
// List all students
Route::get('/students', [StudentController::class, 'index']);
// Show single student (implicit binding)
Route::get('/students/{student}', [StudentController::class, 'show']);
// Edit student form
Route::get('/students/{student}/edit', [StudentController::class, 'edit']);
// Update student
Route::put('/students/{student}', [StudentController::class, 'update']);
// Delete student
Route::delete('/students/{student}', [StudentController::class, 'destroy']);
Controller (app/Http/Controllers/StudentController.php):
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// List all students
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
// Show single student (automatic model injection)
public function show(Student $student)
{
// $student automatically loaded by slug
return view('students.show', compact('student'));
}
// Edit student form
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
// Update student
public function update(Request $request, Student $student)
{
$student->update($request->validated());
return redirect()->route('students.show', $student);
}
// Delete student
public function destroy(Student $student)
{
$student->delete();
return redirect()->route('students.index');
}
}
View (resources/views/students/show.blade.php):
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h1>Student Details</h1>
<p><strong>Name:</strong> {{ $student->name }}</p>
<p><strong>Email:</strong> {{ $student->email }}</p>
<p><strong>Course:</strong> {{ $student->course }}</p>
<p><strong>Age:</strong> {{ $student->age }}</p>
<a href="{{ route('students.edit', $student) }}">Edit</a>
<form action="{{ route('students.destroy', $student) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</body>
</html>
Advantages of Route Model Binding:
- Cleaner Code - Eliminates repetitive
findOrFail()calls - Automatic 404 - Returns 404 if model not found
- Type Safety - IDE auto-completion for model methods
- Consistency - Standardized model resolution across application
- Flexibility - Custom resolution logic with explicit binding
- Less Code - Reduces boilerplate in controllers
Comparison:
Without Route Model Binding:
public function show($id)
{
$student = Student::findOrFail($id);
if (!$student) {
abort(404);
}
return view('students.show', compact('student'));
}
With Route Model Binding:
public function show(Student $student)
{
return view('students.show', compact('student'));
}
Key Features:
- ✓ Automatic model injection
- ✓ Customizable resolution key (id, slug, etc.)
- ✓ Built-in 404 handling
- ✓ Works with soft deletes
- ✓ Explicit and implicit binding options
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and concept │ 1 mark │
│ - What is route model binding │ │
│ - Purpose and benefits │ │
│ │ │
│ 2. Types of route model binding │ 3 marks │
│ - Implicit binding (1.5 marks) │ │
│ * Route parameter naming convention │ │
│ * Automatic resolution │ │
│ * Code example │ │
│ - Explicit binding (1.5 marks) │ │
│ * Custom key specification │ │
│ * RouteServiceProvider setup │ │
│ * Code example │ │
│ │ │
│ 3. Implementation and examples │ 3 marks │
│ - Route definition │ │
│ - Controller method with type-hinted param │ │
│ - Complete working example │ │
│ - Comparison with/without binding │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Types + Implementation (1 + 3 + 3)
Question 20 (14 marks) — #### a) Write a JSON Schema for validating a student information. Also create a student instance conforming to the schema. (7 marks)
a) Write a JSON Schema for validating a student information. Also create a student instance conforming to the schema. (7 marks)
Answer:
Overview: JSON Schema is a vocabulary for annotating and validating JSON documents. It defines the structure, data types, and constraints for JSON data.
JSON Schema for Student Information:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/student.schema.json",
"title": "Student",
"description": "A schema representing a student's information",
"type": "object",
"properties": {
"studentId": {
"description": "Unique identifier for the student",
"type": "integer",
"minimum": 1
},
"name": {
"description": "Full name of the student",
"type": "string",
"minLength": 2,
"maxLength": 100
},
"email": {
"description": "Student's email address",
"type": "string",
"format": "email"
},
"age": {
"description": "Age of the student",
"type": "integer",
"minimum": 15,
"maximum": 100
},
"course": {
"description": "Course enrolled in",
"type": "string",
"enum": ["Computer Science", "Information Technology", "Electronics", "Mechanical", "Civil"]
},
"semester": {
"description": "Current semester",
"type": "integer",
"minimum": 1,
"maximum": 8
},
"gpa": {
"description": "Grade Point Average",
"type": "number",
"minimum": 0.0,
"maximum": 10.0
},
"address": {
"description": "Student's address",
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
},
"pincode": {
"type": "string",
"pattern": "^[0-9]{6}$"
}
},
"required": ["city", "state", "pincode"]
},
"subjects": {
"description": "List of subjects enrolled",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
},
"isActive": {
"description": "Whether student is currently active",
"type": "boolean"
},
"enrollmentDate": {
"description": "Date of enrollment",
"type": "string",
"format": "date"
},
"phoneNumber": {
"description": "Contact phone number",
"type": "string",
"pattern": "^[6-9][0-9]{9}$"
}
},
"required": ["studentId", "name", "email", "age", "course", "semester"],
"additionalProperties": false
}
Valid Student Instance Conforming to Schema:
{
"studentId": 101,
"name": "John Doe",
"email": "john.doe@example.com",
"age": 20,
"course": "Computer Science",
"semester": 7,
"gpa": 8.5,
"address": {
"street": "123 Main Street",
"city": "Trivandrum",
"state": "Kerala",
"pincode": "695001"
},
"subjects": [
"CST463 - Web Programming",
"CST465 - Computer Graphics",
"CST401 - Operating Systems"
],
"isActive": true,
"enrollmentDate": "2021-08-15",
"phoneNumber": "9876543210"
}
Another Valid Example:
{
"studentId": 102,
"name": "Alice Smith",
"email": "alice.smith@university.edu",
"age": 21,
"course": "Information Technology",
"semester": 5,
"gpa": 9.2,
"address": {
"street": "456 Park Avenue",
"city": "Kochi",
"state": "Kerala",
"pincode": "682001"
},
"subjects": [
"IT301 - Database Management",
"IT303 - Network Security",
"IT305 - Cloud Computing",
"IT307 - Machine Learning"
],
"isActive": true,
"enrollmentDate": "2022-07-01",
"phoneNumber": "8765432109"
}
Schema Validation Rules Explained:
- studentId - Must be an integer ≥ 1
- name - String between 2-100 characters
- email - Must be valid email format
- age - Integer between 15-100
- course - Must be one of predefined values (enum)
- semester - Integer between 1-8
- gpa - Number between 0.0-10.0
- address - Nested object with required fields
- subjects - Array with 1-10 unique strings
- isActive - Boolean value
- enrollmentDate - Valid date format (YYYY-MM-DD)
- phoneNumber - 10-digit Indian mobile pattern
Required Fields: studentId, name, email, age, course, semester
Invalid Examples (would fail validation):
Example 1: Missing required field
{
"studentId": 103,
"name": "Bob Wilson",
"age": 19
// Missing: email, course, semester (required fields)
}
Error: Missing required properties
Example 2: Invalid email format
{
"studentId": 104,
"name": "Charlie Brown",
"email": "invalid-email", // Invalid format
"age": 22,
"course": "Computer Science",
"semester": 6
}
Error: email does not match format "email"
Example 3: Age out of range
{
"studentId": 105,
"name": "David Lee",
"email": "david@example.com",
"age": 12, // Below minimum (15)
"course": "Computer Science",
"semester": 1
}
Error: age must be >= 15
Example 4: Invalid course
{
"studentId": 106,
"name": "Eve Johnson",
"email": "eve@example.com",
"age": 19,
"course": "Aerospace Engineering", // Not in enum
"semester": 3
}
Error: course must be one of the allowed values
JSON Schema Data Types:
| Type | Description | Example |
|---|---|---|
string |
Text data | "John Doe" |
number |
Numeric data (int/float) | 8.5 |
integer |
Whole numbers | 101 |
boolean |
True/false | true |
array |
List of items | ["item1", "item2"] |
object |
Nested structure | {"key": "value"} |
null |
Null value | null |
Common Validation Keywords:
| Keyword | Applies To | Description |
|---|---|---|
type |
All | Data type |
minimum/maximum |
Number | Value range |
minLength/maxLength |
String | Length constraints |
pattern |
String | Regex validation |
format |
String | Pre-defined formats (email, date, uri) |
enum |
All | Allowed values |
required |
Object | Required properties |
minItems/maxItems |
Array | Array size |
uniqueItems |
Array | No duplicates |
properties |
Object | Nested properties |
Key Features:
- ✓ Comprehensive validation rules
- ✓ Nested object support
- ✓ Array validation with constraints
- ✓ Pattern matching for strings
- ✓ Enum for restricted values
- ✓ Required and optional fields
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20a - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Schema creation for student │ 5 marks │
│ - Schema structure with $schema declaration │ │
│ - Define properties (id, name, email, etc.) │ │
│ - Data type specifications │ │
│ - Constraints (minLength, maxLength, etc.) │ │
│ - Required fields array │ │
│ - Pattern validations (email format) │ │
│ │ │
│ 2. Student instance creation │ 2 marks │
│ - Valid JSON instance conforming to schema │ │
│ - All required fields included │ │
│ - Proper data types and format │ │
│ - Example meets all constraints │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: JSON Schema + Instance (5 + 2)
b) What are views and redirections in Laravel? With example explain how are they used in Laravel. (7 marks)
Answer:
Part 1: Views in Laravel
Definition:
Views in Laravel contain the HTML of your application and separate presentation logic from business logic. They are stored in the resources/views directory and use the Blade templating engine.
Creating Views:
Basic View (resources/views/welcome.blade.php):
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to Laravel</h1>
<p>This is a basic view.</p>
</body>
</html>
Returning View from Controller:
<?php
namespace App\Http\Controllers;
class HomeController extends Controller
{
public function index()
{
return view('welcome'); // Returns resources/views/welcome.blade.php
}
}
Passing Data to Views:
Method 1: Using compact()
public function show()
{
$name = "John Doe";
$age = 25;
return view('profile', compact('name', 'age'));
}
Method 2: Using array
public function show()
{
return view('profile', [
'name' => 'John Doe',
'age' => 25
]);
}
Method 3: Using with()
public function show()
{
return view('profile')
->with('name', 'John Doe')
->with('age', 25);
}
View (resources/views/profile.blade.php):
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>User Profile</h1>
<p>Name: {{ $name }}</p>
<p>Age: {{ $age }}</p>
</body>
</html>
Blade Templating Features:
1. Variables:
{{ $name }} // Escaped output (safe from XSS)
{!! $html !!} // Unescaped output
2. Conditional Statements:
@if($age >= 18)
<p>Adult</p>
@elseif($age >= 13)
<p>Teenager</p>
@else
<p>Child</p>
@endif
3. Loops:
@foreach($students as $student)
<p>{{ $student->name }}</p>
@endforeach
@for($i = 0; $i < 10; $i++)
<p>{{ $i }}</p>
@endfor
4. Layout Inheritance:
Master Layout (resources/views/layouts/app.blade.php):
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
<header>
@include('partials.header')
</header>
<main>
@yield('content')
</main>
<footer>
@include('partials.footer')
</footer>
</body>
</html>
Child View (resources/views/students/show.blade.php):
@extends('layouts.app')
@section('title', 'Student Details')
@section('content')
<h1>Student Details</h1>
<p>Name: {{ $student->name }}</p>
<p>Course: {{ $student->course }}</p>
@endsection
Part 2: Redirections in Laravel
Definition:
Redirections send the user to a different URL. Laravel provides several methods to perform redirects.
Types of Redirections:
1. Basic Redirect to URL:
return redirect('/home');
2. Redirect to Named Route:
return redirect()->route('students.index');
3. Redirect to Controller Action:
return redirect()->action([StudentController::class, 'index']);
4. Redirect Back:
return redirect()->back(); // Return to previous page
5. Redirect with Flash Data:
return redirect('/dashboard')->with('success', 'Login successful!');
Accessing flash data in view:
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
6. Redirect with Input:
return redirect('/form')->withInput(); // Preserve form input
7. Redirect with Errors:
return redirect('/form')
->withErrors(['email' => 'Invalid email address'])
->withInput();
Complete Example - Student Management System:
Routes (routes/web.php):
<?php
use App\Http\Controllers\StudentController;
Route::get('/students', [StudentController::class, 'index'])->name('students.index');
Route::get('/students/create', [StudentController::class, 'create'])->name('students.create');
Route::post('/students', [StudentController::class, 'store'])->name('students.store');
Route::get('/students/{student}', [StudentController::class, 'show'])->name('students.show');
Route::get('/students/{student}/edit', [StudentController::class, 'edit'])->name('students.edit');
Route::put('/students/{student}', [StudentController::class, 'update'])->name('students.update');
Route::delete('/students/{student}', [StudentController::class, 'destroy'])->name('students.destroy');
Controller (app/Http/Controllers/StudentController.php):
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// Display list of students (VIEW)
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
// Show create form (VIEW)
public function create()
{
return view('students.create');
}
// Store new student (REDIRECT)
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email|unique:students',
'course' => 'required|string',
'age' => 'required|integer|min:15'
]);
$student = Student::create($validated);
// Redirect with success message
return redirect()->route('students.show', $student)
->with('success', 'Student created successfully!');
}
// Show single student (VIEW)
public function show(Student $student)
{
return view('students.show', compact('student'));
}
// Show edit form (VIEW)
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
// Update student (REDIRECT)
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email|unique:students,email,' . $student->id,
'course' => 'required|string',
'age' => 'required|integer|min:15'
]);
$student->update($validated);
// Redirect back with success message
return redirect()->route('students.show', $student)
->with('success', 'Student updated successfully!');
}
// Delete student (REDIRECT)
public function destroy(Student $student)
{
$student->delete();
// Redirect to index with success message
return redirect()->route('students.index')
->with('success', 'Student deleted successfully!');
}
}
View - List Students (resources/views/students/index.blade.php):
@extends('layouts.app')
@section('title', 'Students List')
@section('content')
<h1>Students</h1>
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<a href="{{ route('students.create') }}">Add New Student</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->course }}</td>
<td>
<a href="{{ route('students.show', $student) }}">View</a>
<a href="{{ route('students.edit', $student) }}">Edit</a>
<form action="{{ route('students.destroy', $student) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
View - Show Student (resources/views/students/show.blade.php):
@extends('layouts.app')
@section('title', 'Student Details')
@section('content')
<h1>Student Details</h1>
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<p><strong>Name:</strong> {{ $student->name }}</p>
<p><strong>Email:</strong> {{ $student->email }}</p>
<p><strong>Course:</strong> {{ $student->course }}</p>
<p><strong>Age:</strong> {{ $student->age }}</p>
<a href="{{ route('students.edit', $student) }}">Edit</a>
<a href="{{ route('students.index') }}">Back to List</a>
<form action="{{ route('students.destroy', $student) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit">Delete Student</button>
</form>
@endsection
View - Create Form (resources/views/students/create.blade.php):
@extends('layouts.app')
@section('title', 'Add Student')
@section('content')
<h1>Add New Student</h1>
@if($errors->any())
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('students.store') }}" method="POST">
@csrf
<label>Name:</label>
<input type="text" name="name" value="{{ old('name') }}" required>
<br>
<label>Email:</label>
<input type="email" name="email" value="{{ old('email') }}" required>
<br>
<label>Course:</label>
<input type="text" name="course" value="{{ old('course') }}" required>
<br>
<label>Age:</label>
<input type="number" name="age" value="{{ old('age') }}" required>
<br>
<button type="submit">Create Student</button>
</form>
<a href="{{ route('students.index') }}">Cancel</a>
@endsection
Summary:
Views:
- Contain HTML presentation
- Use Blade templating engine
- Support layouts and components
- Receive data from controllers
- Located in
resources/views
Redirections:
- Send users to different URLs
- Can pass flash messages
- Preserve form input on errors
- Support named routes
- Return HTTP redirect response
Key Features:
- ✓ Clean separation of concerns
- ✓ Blade templating for dynamic content
- ✓ Flash messages for user feedback
- ✓ Form validation with error display
- ✓ Named routes for maintainability
- ✓ RESTful resource patterns
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20b - MARK DISTRIBUTION (Total: 7 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Views in Laravel │ 3.5 marks │
│ - Definition and purpose │ │
│ - Blade templating engine │ │
│ - Creating views (resources/views) │ │
│ - Passing data to views │ │
│ - Example with controller and view code │ │
│ │ │
│ 2. Redirections in Laravel │ 3.5 marks │
│ - Definition and types │ │
│ - redirect() methods │ │
│ - Route redirections │ │
│ - Flash messages with redirects │ │
│ - Example with redirect code │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Nearly Equal Parts (3.5 + 3.5)