CST463 Web Programming - Answer Key
CST463 Web Programming - Answer Key
May 2024 Examination
Subject: Web Programming (CST463)
Date: May 2024
Total Marks: 100
Duration: 3 Hours
Exam Type: End Semester Examination
Academic Level: Seventh Semester B.Tech Degree (S, FE)
Institution: APJ Abdul Kalam Technological University
PART A (Short Answer Questions)
Answer all questions, each carries 3 marks.
Question 1 (3 marks)
Describe World Wide Web and its significance.
Answer:
The World Wide Web (WWW) is a system of interlinked hypertext documents and resources accessed via the Internet using web browsers. It was invented by Tim Berners-Lee in 1989 and operates on the client-server model using HTTP/HTTPS protocols.
Significance:
- Information Access: Provides instant access to vast amounts of information from anywhere in the world
- Communication: Enables global communication through email, social media, video conferencing, and messaging platforms
- E-Commerce: Facilitates online business transactions, digital marketing, and global trade
- Education: Offers online learning platforms, digital libraries, and educational resources accessible to everyone
- Entertainment: Delivers streaming services, online gaming, and multimedia content
- Collaboration: Enables remote work, cloud-based applications, and real-time collaboration tools
The WWW has transformed how society functions, making information universally accessible and revolutionizing communication, business, education, and entertainment.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and Introduction of WWW │ 1 mark │
│ - Definition of World Wide Web │ │
│ - Inventor and year (Tim Berners-Lee, 1989) │ │
│ - Basic operating model (client-server, │ │
│ HTTP/HTTPS) │ │
│ │ │
│ 2. Significance of WWW │ 2 marks │
│ - Information access capabilities │ │
│ - Communication features │ │
│ - E-Commerce applications │ │
│ - Educational benefits │ │
│ - Entertainment services │ │
│ - Collaboration tools │ │
│ - Overall impact on society │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Definition + Detailed Explanation (Section 1.2, Pattern 2)
Question 2 (3 marks)
Differentiate between block tags and inline tags. Illustrate with suitable examples.
Answer:
Block Tags:
- Occupy the full width available, starting on a new line and extending to the right edge
- Always start on a new line and push subsequent content to the next line
- Can contain other block-level and inline elements
- Default display property:
display: block - Examples:
<div>,<p>,<h1>to<h6>,<ul>,<ol>,<table>,<form>,<header>,<footer>,<section>
Inline Tags:
- Occupy only the space bounded by their content, without breaking the flow
- Do not start on a new line; they appear on the same line as adjacent content
- Can only contain other inline elements and text (not block elements)
- Default display property:
display: inline - Examples:
<span>,<a>,<strong>,<em>,<img>,<input>,<label>,<code>
Example:
<!-- Block tags example -->
<h1>This is a heading</h1>
<p>This is a paragraph. It starts on a new line.</p>
<div>This div also starts on a new line.</div>
<!-- Inline tags example -->
<p>This is <strong>bold text</strong> and this is <em>italic text</em> within the same line.</p>
<span>Span 1</span><span>Span 2</span> <!-- Both spans appear on the same line -->
Visual Difference:
- Block:
[■■■■■■■■■■■■■■■](full width) - Inline:
[■■■]only content width
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Block Tags Explanation │ 1.5 marks │
│ - Full width behavior │ │
│ - New line characteristics │ │
│ - Can contain block/inline elements │ │
│ - Display property │ │
│ - Examples of block tags │ │
│ │ │
│ 2. Inline Tags Explanation │ 1.5 marks │
│ - Content-width behavior │ │
│ - Same line characteristics │ │
│ - Can only contain inline elements │ │
│ - Display property │ │
│ - Examples of inline tags │ │
│ - Code illustrations │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Differentiate Two Concepts (Section 1.2, Pattern 1)
Question 3 (3 marks)
Write CSS style rules to implement the following in a web page:
- a. to display the content of hyperlinks with red background colour and in italics.
- b. to display the contents of unordered lists in Times New Roman font.
- c. to display "Ocean.gif" as the background image of the page.
Answer:
/* a) Hyperlinks with red background and italics */
a {
background-color: red;
font-style: italic;
}
/* b) Unordered lists in Times New Roman font */
ul {
font-family: "Times New Roman", Times, serif;
}
/* c) Display Ocean.gif as background image */
body {
background-image: url('Ocean.gif');
}
Alternative with additional styling options:
/* a) Hyperlinks - can also target different states */
a {
background-color: red;
font-style: italic;
color: white; /* Optional: for better readability */
padding: 2px 5px; /* Optional: for spacing */
}
/* b) Unordered lists */
ul {
font-family: "Times New Roman", Times, serif;
}
/* c) Background image with additional properties */
body {
background-image: url('Ocean.gif');
background-repeat: repeat; /* or no-repeat, repeat-x, repeat-y */
background-size: cover; /* Optional: to cover entire page */
background-attachment: fixed; /* Optional: fixed background */
}
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Part (a): Hyperlinks styling │ 1 mark │
│ - Red background color CSS rule │ │
│ - Italic font style CSS rule │ │
│ │ │
│ 2. Part (b): Unordered list font styling │ 1 mark │
│ - Times New Roman font-family rule │ │
│ │ │
│ 3. Part (c): Background image styling │ 1 mark │
│ - Background-image CSS rule │ │
│ - Correct URL syntax for Ocean.gif │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Multiple Equal Components (Section 1.2, Pattern 4)
Question 4 (3 marks)
Differentiate between Absolute Positioning and Relative Positioning.
Answer:
Absolute Positioning:
- Element is positioned relative to its nearest positioned ancestor (not static) or the document body if no positioned ancestor exists
- Removed from the normal document flow, meaning other elements behave as if it doesn't exist
- Does not leave any space where the element would have been in the normal flow
- Uses
position: absolutewithtop,right,bottom,leftproperties to specify exact position - Common use: Overlays, tooltips, dropdown menus that need precise positioning
Relative Positioning:
- Element is positioned relative to its normal position in the document flow
- Remains in the normal document flow, and space is reserved for it at its original position
- Other elements are not affected; they still respect the element's original position
- Uses
position: relativewithtop,right,bottom,leftproperties to offset from its normal position - Common use: Fine-tuning element positions, creating positioning context for absolutely positioned children
Example:
/* Absolute positioning */
.absolute-box {
position: absolute;
top: 50px;
left: 100px;
/* Positioned exactly 50px from top and 100px from left of positioned parent */
}
/* Relative positioning */
.relative-box {
position: relative;
top: 20px;
left: 30px;
/* Shifted 20px down and 30px right from its normal position */
}
Key Difference: Absolute removes the element from document flow while relative keeps it in the flow but allows offset adjustments.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Absolute Positioning Explanation │ 1.5 marks │
│ - Positioning reference (ancestor/body) │ │
│ - Document flow removal │ │
│ - Space behavior │ │
│ - CSS syntax (position: absolute) │ │
│ - Use cases │ │
│ │ │
│ 2. Relative Positioning Explanation │ 1.5 marks │
│ - Positioning reference (normal position) │ │
│ - Remains in document flow │ │
│ - Space reservation │ │
│ - CSS syntax (position: relative) │ │
│ - Use cases │ │
│ - Code examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Differentiate Two Concepts (Section 1.2, Pattern 1)
Question 5 (3 marks)
Write a PHP program to check whether the given number is Armstrong or not.
Answer:
An Armstrong number (also called narcissistic number) is a number that equals the sum of its digits each raised to the power of the number of digits.
Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
PHP Program:
<?php
function isArmstrong($number) {
$originalNumber = $number;
$sum = 0;
$numDigits = strlen((string)$number);
// Calculate sum of digits raised to power of number of digits
while ($number > 0) {
$digit = $number % 10;
$sum += pow($digit, $numDigits);
$number = (int)($number / 10);
}
// Check if sum equals original number
return ($sum == $originalNumber);
}
// Test the function
$num = 153;
if (isArmstrong($num)) {
echo "$num is an Armstrong number";
} else {
echo "$num is not an Armstrong number";
}
?>
Output:
153 is an Armstrong number
Explanation:
- Store the original number for comparison
- Count the number of digits using
strlen() - Extract each digit using modulo operation (
% 10) - Raise each digit to the power of total digits and add to sum
- Compare sum with original number
Test Cases:
- 153 → Armstrong (1³ + 5³ + 3³ = 153)
- 370 → Armstrong (3³ + 7³ + 0³ = 370)
- 9474 → Armstrong (9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474)
- 123 → Not Armstrong
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete PHP Program │ 3 marks │
│ - Armstrong number definition/logic │ │
│ - Function declaration (isArmstrong) │ │
│ - Count digits logic │ │
│ - Loop to extract and process digits │ │
│ - Power calculation (pow function) │ │
│ - Sum accumulation │ │
│ - Comparison with original number │ │
│ - Test case with output │ │
│ - Explanation of algorithm │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Pure Programming/Code (Section 1.2, Pattern 5)
Question 6 (3 marks)
Illustrate explode() and implode() functions in PHP with suitable examples.
Answer:
explode() Function:
- Splits a string into an array based on a delimiter
- Syntax:
array explode(string $delimiter, string $string, int $limit = PHP_INT_MAX) - Converts a string to an array
implode() Function:
- Joins array elements into a single string using a delimiter
- Syntax:
string implode(string $separator, array $array) - Also known as
join()- both are aliases - Converts an array to a string
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 )
// explode() with limit parameter
$text = "One-Two-Three-Four-Five";
$parts = explode("-", $text, 3);
print_r($parts);
// Output: Array ( [0] => One [1] => Two [2] => Three-Four-Five )
// implode() - Array to String
$colors = array("Red", "Green", "Blue", "Yellow");
$colorString = implode(", ", $colors);
echo $colorString;
// Output: Red, Green, Blue, Yellow
// implode() with different separator
$numbers = array(1, 2, 3, 4, 5);
$result = implode("-", $numbers);
echo $result;
// Output: 1-2-3-4-5
// Practical example: explode and implode together
$email = "john.doe@example.com";
$parts = explode("@", $email);
echo "Username: " . $parts[0] . "\n";
echo "Domain: " . $parts[1] . "\n";
// Output: Username: john.doe
// Domain: example.com
?>
Key Difference:
explode(): String → Array (breaks apart)implode(): Array → String (combines together)
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. explode() Function │ 1.5 marks │
│ - Definition and purpose │ │
│ - Syntax specification │ │
│ - Conversion explanation (String → Array) │ │
│ - Code examples with output │ │
│ - Limit parameter demonstration │ │
│ │ │
│ 2. implode() Function │ 1.5 marks │
│ - Definition and purpose │ │
│ - Syntax specification │ │
│ - Conversion explanation (Array → String) │ │
│ - Code examples with different separators │ │
│ - Practical usage demonstration │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Two Equal Concepts (Section 1.2, Pattern 1)
Question 7 (3 marks)
Differentiate between require and include in PHP with proper syntax.
Answer:
require:
- Includes and evaluates a specified file; if file is not found, produces a fatal error (E_COMPILE_ERROR) and stops script execution
- Script execution terminates immediately on failure
- Used when the file is essential for the application to run
- Best for including critical files like configuration files, database connections, or essential libraries
- Syntax:
require 'filename.php';orrequire('filename.php');
include:
- Includes and evaluates a specified file; if file is not found, produces a warning (E_WARNING) and continues script execution
- Script continues running even if file is not found
- Used when the file is optional or non-critical
- Best for including templates, optional modules, or non-essential components
- Syntax:
include 'filename.php';orinclude('filename.php');
Syntax Examples:
<?php
// require - Critical file inclusion
require 'config.php'; // Fatal error if not found
require 'database.php'; // Script stops if missing
// include - Optional file inclusion
include 'header.php'; // Warning if not found
include 'optional_module.php'; // Script continues if missing
// require_once - Includes file only once (prevents redeclaration errors)
require_once 'functions.php';
// include_once - Includes file only once (optional)
include_once 'utility.php';
?>
Comparison Table:
| Feature | require | include |
|---|---|---|
| Error on failure | Fatal Error (E_COMPILE_ERROR) | Warning (E_WARNING) |
| Script execution | Stops | Continues |
| Use case | Critical files | Optional files |
| Performance | Slightly faster (fails immediately) | Continues processing |
Example Demonstrating Difference:
<?php
// Using require
require 'essential.php'; // If missing: Fatal error, script stops here
echo "This line won't execute if file is missing";
// Using include
include 'optional.php'; // If missing: Warning, but script continues
echo "This line will execute even if file is missing";
?>
Best Practice: Use require for essential files and include for optional components.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. require Statement │ 1.5 marks │
│ - Error handling behavior (fatal error) │ │
│ - Script execution behavior (stops) │ │
│ - Use cases (critical files) │ │
│ - Syntax examples │ │
│ - require_once variant │ │
│ │ │
│ 2. include Statement │ 1.5 marks │
│ - Error handling behavior (warning) │ │
│ - Script execution behavior (continues) │ │
│ - Use cases (optional files) │ │
│ - Syntax examples │ │
│ - include_once variant │ │
│ - Comparison table and examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Differentiate Two Concepts (Section 1.2, Pattern 1)
Question 8 (3 marks)
Write PHP statements to insert data into MySQL table.
Answer:
Using PDO (PHP Data Objects) with Prepared Statements:
<?php
try {
// Database connection using PDO
$dsn = "mysql:host=localhost;dbname=student_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 SQL statement with named placeholders
$sql = "INSERT INTO students (name, email, age, course) VALUES (:name, :email, :age, :course)";
$stmt = $pdo->prepare($sql);
// Execute with parameter array
$stmt->execute([
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 21,
'course' => 'B.Tech CSE'
]);
echo "Record inserted successfully. ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
?>
Alternative using positional placeholders:
<?php
// Prepare statement with ? placeholders
$sql = "INSERT INTO students (name, email, age, course) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
// Execute with positional parameters
$stmt->execute(['John Doe', 'john@example.com', 21, 'B.Tech CSE']);
echo "Record inserted successfully";
?>
Key Points:
- PDO with prepared statements prevents SQL injection attacks
- Use named placeholders (
:name) or positional placeholders (?) - Never concatenate user input directly into SQL queries
lastInsertId()returns the auto-increment ID of the inserted row
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete PHP INSERT Statements │ 3 marks │
│ - PDO database connection setup │ │
│ - Connection options and error handling │ │
│ - Prepared statement creation │ │
│ - Named/positional placeholders │ │
│ - Execute with parameter binding │ │
│ - Success message and lastInsertId() │ │
│ - Exception handling (try-catch) │ │
│ - Alternative syntax demonstration │ │
│ - Security notes (SQL injection prevention) │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Pure Programming/Code (Section 1.2, Pattern 5)
Question 9 (3 marks)
Discuss the role of Resource controllers in Laravel.
Answer:
Resource Controllers in Laravel provide a convenient way to create controllers that handle all typical CRUD (Create, Read, Update, Delete) operations for a resource with predefined RESTful routes.
Role and Purpose:
- Automatically implement standard CRUD operations following REST conventions
- Reduce code duplication by providing structured method names
- Create consistent API endpoints with minimal configuration
- Follow RESTful naming conventions for routes and actions
Standard Resource Controller Methods:
| HTTP Method | URI | Controller Method | Purpose |
|---|---|---|---|
| GET | /resource | index() | Display all resources |
| GET | /resource/create | create() | Show form to create new resource |
| POST | /resource | store() | Store new resource in database |
| GET | /resource/{id} | show() | Display specific resource |
| GET | /resource/{id}/edit | edit() | Show form to edit resource |
| PUT/PATCH | /resource/{id} | update() | Update specific resource |
| DELETE | /resource/{id} | destroy() | Delete specific resource |
Creating a Resource Controller:
php artisan make:controller StudentController --resource
Registering Resource Routes:
// In routes/web.php
Route::resource('students', StudentController::class);
This single line automatically creates all 7 RESTful routes.
Example Resource Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
// Display all students
public function index() {
$students = Student::all();
return view('students.index', compact('students'));
}
// Show form to create new student
public function create() {
return view('students.create');
}
// Store new student
public function store(Request $request) {
Student::create($request->all());
return redirect()->route('students.index');
}
// Display specific student
public function show($id) {
$student = Student::findOrFail($id);
return view('students.show', compact('student'));
}
// Additional methods: edit(), update(), destroy()
}
?>
Benefits:
- Standardized structure for CRUD operations
- Automatic route generation
- RESTful best practices
- Cleaner and more maintainable code
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and Role │ 1.5 marks │
│ - Resource controller definition │ │
│ - Purpose in Laravel │ │
│ - CRUD operation management │ │
│ - RESTful conventions │ │
│ - Benefits and advantages │ │
│ │ │
│ 2. Implementation and Syntax │ 1.5 marks │
│ - Standard methods table (7 methods) │ │
│ - HTTP methods and URIs │ │
│ - Artisan command syntax │ │
│ - Route registration syntax │ │
│ - Example controller code │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Concept + Supporting Elements (Section 1.2, Pattern 6)
Question 10 (3 marks)
List and describe various data types used in JSON.
Answer:
JSON (JavaScript Object Notation) supports six fundamental data types:
1. String:
- Sequence of Unicode characters enclosed in double quotes
- Must use double quotes (not single quotes)
- Example:
"name": "John Doe","city": "New York"
2. Number:
- Integer or floating-point numbers
- No quotes around the value
- Can be positive, negative, or include decimal points
- Example:
"age": 25,"price": 99.99,"temperature": -15.5
3. Boolean:
- Logical values:
trueorfalse(lowercase only) - Used for binary conditions
- Example:
"isActive": true,"verified": false
4. Null:
- Represents empty or non-existent value
- Written as
null(lowercase) - Example:
"middleName": null,"comment": null
5. Object:
- Unordered collection of key-value pairs enclosed in curly braces
{} - Keys must be strings in double quotes
- Values can be any JSON data type
- Example:
"person": { "name": "John", "age": 30, "city": "Boston" }
6. Array:
- Ordered collection of values enclosed in square brackets
[] - Values can be of any JSON data type (including mixed types)
- Elements separated by commas
- Example:
"fruits": ["Apple", "Banana", "Orange"], "numbers": [1, 2, 3, 4, 5], "mixed": ["text", 123, true, null]
Complete Example Demonstrating All Data Types:
{
"name": "John Doe",
"age": 28,
"isStudent": false,
"spouse": null,
"address": {
"street": "123 Main St",
"city": "Boston",
"zipCode": 12345
},
"hobbies": ["reading", "gaming", "coding"],
"scores": [85.5, 90.0, 78.5]
}
Key Characteristics:
- JSON is language-independent but uses JavaScript syntax
- Data types are strictly defined and case-sensitive
- No support for undefined, functions, or date objects (must use strings for dates)
- Lightweight and easy to parse
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. String Data Type │ 0.5 marks │
│ - Definition and syntax rules │ │
│ - Examples │ │
│ │ │
│ 2. Number Data Type │ 0.5 marks │
│ - Integer and floating-point description │ │
│ - Examples │ │
│ │ │
│ 3. Boolean Data Type │ 0.5 marks │
│ - True/false values │ │
│ - Examples │ │
│ │ │
│ 4. Null Data Type │ 0.5 marks │
│ - Purpose and usage │ │
│ - Examples │ │
│ │ │
│ 5. Object Data Type │ 0.5 marks │
│ - Key-value pair structure │ │
│ - JSON object example │ │
│ │ │
│ 6. Array Data Type │ 0.5 marks │
│ - Ordered collection description │ │
│ - Array examples │ │
│ - Complete demonstration with all types │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Multiple Equal Components (Section 1.2, Pattern 4)
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) Describe the structure of an HTML document. Explain following html tags with proper example: 1. `<input>` 2. `<img>` 3. `<table>` 4. `<form>` 5. `<a href>` (8 marks)
a) Describe the structure of an HTML document. Explain following html tags with proper example: 1. <input> 2. <img> 3. <table> 4. <form> 5. <a href> (8 marks)
Answer:
Structure of an HTML Document:
An HTML document follows a hierarchical tree structure with specific elements that define the document's metadata and content. The basic structure consists of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Title</title>
<!-- Other meta tags, links to CSS, scripts -->
</head>
<body>
<!-- Visible content goes here -->
</body>
</html>
Components of HTML Structure:
-
<!DOCTYPE html>: Document Type Declaration- Tells the browser this is an HTML5 document
- Must be the first line of the document
- Not an HTML tag but an instruction to the browser
-
<html>: Root Element- Container for all HTML content
langattribute specifies the language (e.g., "en" for English)- All other elements are descendants of this element
-
<head>: Metadata Container- Contains metadata, title, links to stylesheets, and scripts
- Not displayed directly on the page
- Includes:
<title>,<meta>,<link>,<style>,<script>
-
<body>: Content Container- Contains all visible content displayed in the browser
- Includes text, images, links, forms, tables, multimedia, etc.
Explanation of HTML Tags:
1. <input> Tag:
The <input> tag is used to create interactive form controls where users can enter data.
Attributes:
type: Specifies the input type (text, password, email, number, checkbox, radio, submit, etc.)name: Identifies the input field when form is submittedvalue: Specifies the initial valueplaceholder: Displays hint textrequired: Makes field mandatory
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Input Examples</title>
</head>
<body>
<form>
<!-- Text input -->
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter username" required>
<br><br>
<!-- Password input -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<!-- Email input -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="user@example.com">
<br><br>
<!-- Number input -->
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1" max="120">
<br><br>
<!-- Checkbox -->
<input type="checkbox" id="subscribe" name="subscribe" value="yes">
<label for="subscribe">Subscribe to newsletter</label>
<br><br>
<!-- Radio buttons -->
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<br><br>
<!-- Submit button -->
<input type="submit" value="Submit Form">
</form>
</body>
</html>
2. <img> Tag:
The <img> tag embeds images in HTML documents. It is a self-closing (void) tag.
Attributes:
src: Specifies the image source URL (required)alt: Alternative text for accessibility and when image can't load (required)widthandheight: Specify dimensions in pixelstitle: Tooltip text displayed on hover
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Examples</title>
</head>
<body>
<h2>Image Examples</h2>
<!-- Basic image -->
<img src="photo.jpg" alt="A beautiful landscape">
<br><br>
<!-- Image with dimensions -->
<img src="logo.png" alt="Company Logo" width="200" height="100">
<br><br>
<!-- Image with title (tooltip) -->
<img src="product.jpg" alt="Product Image" title="Click to view details" width="300">
<br><br>
<!-- Image from external URL -->
<img src="https://www.example.com/images/banner.jpg" alt="Banner Image" width="800">
</body>
</html>
3. <table> Tag:
The <table> tag creates tabular data with rows and columns.
Related Tags:
<tr>: Table row<th>: Table header cell<td>: Table data cell<thead>: Groups header content<tbody>: Groups body content<tfoot>: Groups footer content
Attributes:
border: Border thickness (deprecated, use CSS)cellpadding,cellspacing: Cell spacing (deprecated, use CSS)
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table Example</title>
<style>
table {
border-collapse: collapse;
width: 60%;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h2>Student Information</h2>
<table>
<thead>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Course</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>101</td>
<td>John Doe</td>
<td>CST463</td>
<td>85</td>
</tr>
<tr>
<td>102</td>
<td>Jane Smith</td>
<td>CST463</td>
<td>92</td>
</tr>
<tr>
<td>103</td>
<td>Bob Johnson</td>
<td>CST463</td>
<td>78</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3"><strong>Average</strong></td>
<td><strong>85</strong></td>
</tr>
</tfoot>
</table>
</body>
</html>
4. <form> Tag:
The <form> tag creates an HTML form for user input, which can be submitted to a server for processing.
Attributes:
action: URL where form data is sentmethod: HTTP method (GET or POST)enctype: Encoding type for form datatarget: Where to display response (_self, _blank, etc.)
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form Example</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form action="submit.php" method="POST">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}">
<br><br>
<label for="course">Select Course:</label>
<select id="course" name="course">
<option value="btech">B.Tech</option>
<option value="mtech">M.Tech</option>
<option value="mca">MCA</option>
</select>
<br><br>
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<br><br>
<label for="message">Comments:</label><br>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
<br><br>
<input type="submit" value="Register">
<input type="reset" value="Clear Form">
</form>
</body>
</html>
5. <a href> Tag (Anchor Tag):
The <a> tag creates hyperlinks to other web pages, files, locations within the same page, email addresses, or any URL.
Attributes:
href: Specifies the link destination (required)target: Specifies where to open the link (_blank, _self, _parent, _top)title: Tooltip textdownload: Prompts to download the linked resource
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hyperlink Examples</title>
</head>
<body>
<h2>Different Types of Links</h2>
<!-- External link -->
<a href="https://www.google.com" target="_blank">Visit Google (opens in new tab)</a>
<br><br>
<!-- Internal link (same website) -->
<a href="about.html">About Us</a>
<br><br>
<!-- Link to a specific section on the same page -->
<a href="#section2">Jump to Section 2</a>
<br><br>
<!-- Email link -->
<a href="mailto:info@example.com">Send Email</a>
<br><br>
<!-- Telephone link -->
<a href="tel:+919876543210">Call Us: +91-9876543210</a>
<br><br>
<!-- Download link -->
<a href="document.pdf" download>Download PDF</a>
<br><br>
<!-- Link with title (tooltip) -->
<a href="https://www.example.com" title="Visit Example Website" target="_blank">
Example Website
</a>
<br><br>
<h3 id="section2">Section 2</h3>
<p>This is section 2 content.</p>
<a href="#top">Back to Top</a>
</body>
</html>
Summary:
<input>: Creates interactive form controls<img>: Embeds images<table>: Displays tabular data<form>: Collects user input for submission<a href>: Creates hyperlinks to navigate between pages or resources
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML Document Structure │ 2 marks │
│ - DOCTYPE declaration explanation │ │
│ - <html> root element │ │
│ - <head> metadata container │ │
│ - <body> content container │ │
│ - Basic structure code example │ │
│ │ │
│ 2. Five HTML Tags Explanation │ 6 marks │
│ │ │
│ a) <input> Tag (1.2 marks): │ │
│ - Purpose and usage │ │
│ - Attributes (type, name, value, etc.) │ │
│ - Complete code examples │ │
│ │ │
│ b) <img> Tag (1.2 marks): │ │
│ - Purpose as self-closing tag │ │
│ - Attributes (src, alt, width, height) │ │
│ - Multiple image examples │ │
│ │ │
│ c) <table> Tag (1.2 marks): │ │
│ - Table structure explanation │ │
│ - Related tags (tr, th, td, etc.) │ │
│ - Complete table example with styling │ │
│ │ │
│ d) <form> Tag (1.2 marks): │ │
│ - Form purpose and submission │ │
│ - Attributes (action, method, etc.) │ │
│ - Complete form example │ │
│ │ │
│ e) <a href> Tag (1.2 marks): │ │
│ - Hyperlink functionality │ │
│ - Attributes (href, target, title) │ │
│ - Various link type examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Concept Explanation + Multiple Equal Components
Reference: Section 3 (8-mark questions)
b) Explain HTTP and its significance. Describe the request and response phases in HTTP. (6 marks)
Answer:
HTTP (HyperText Transfer Protocol):
HTTP is an application-layer protocol used for transmitting hypermedia documents (such as HTML) between web browsers and web servers. It is the foundation of data communication on the World Wide Web.
Key Characteristics:
- Stateless Protocol: Each request is independent; the server doesn't retain information about previous requests
- Client-Server Model: Operates on request-response architecture
- Port: Default port is 80 (443 for HTTPS)
- Text-Based: Uses human-readable text format for messages
- Connection-Oriented: Uses TCP/IP for reliable data transmission
Significance of HTTP:
- Universal Standard: Enables communication between different systems and platforms
- Web Foundation: Powers all web browsing, making the internet accessible
- Platform Independence: Works across operating systems, devices, and browsers
- Flexibility: Supports various content types (HTML, images, videos, JSON, XML)
- Caching: Supports caching mechanisms for improved performance
- Extensibility: Can be extended with headers for additional functionality
- RESTful APIs: Foundation for modern web services and APIs
- Security: HTTPS variant provides encrypted communication
HTTP Request Phase:
The request phase is initiated by the client (web browser) to request a resource from the server.
Components of HTTP Request:
-
Request Line: Contains three parts
- HTTP Method: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- URI (Uniform Resource Identifier): Path to the resource
- HTTP Version: HTTP/1.1, HTTP/2, HTTP/3
-
Request Headers: Provide additional information
Host: Domain name of the serverUser-Agent: Information about the client browserAccept: Types of content the client can handleContent-Type: Type of data being sent (for POST/PUT)Cookie: Sends cookies to the serverAuthorization: Authentication credentials
-
Request Body (optional): Contains data sent to server (in POST, PUT, PATCH)
Example HTTP Request:
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Example POST Request with Body:
POST /submit-form HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 35
name=John+Doe&email=john@example.com
HTTP Response Phase:
The response phase is the server's reply to the client's request, containing the requested resource or an error message.
Components of HTTP Response:
-
Status Line: Contains three parts
- HTTP Version: HTTP/1.1
- Status Code: 3-digit code indicating request outcome
- Reason Phrase: Text description of status code
-
Response Headers: Provide metadata about the response
Content-Type: Type of content being returnedContent-Length: Size of the response body in bytesServer: Information about the web serverDate: Timestamp of the responseSet-Cookie: Instructs browser to store cookiesCache-Control: Caching directives
-
Response Body: The actual content (HTML, JSON, image, etc.)
Example HTTP Response:
HTTP/1.1 200 OK
Date: Wed, 15 Nov 2024 10:30:00 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
Connection: keep-alive
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
HTTP Status Codes:
| Code Range | Category | Examples |
|---|---|---|
| 1xx | Informational | 100 Continue, 101 Switching Protocols |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server Error | 500 Internal Server Error, 503 Service Unavailable |
Complete Request-Response Cycle:
1. Client (Browser) initiates request:
┌──────────────┐
│ Browser │──── HTTP Request ────┐
└──────────────┘ │
▼
Example: GET /page.html ┌──────────────┐
│ Web Server │
┌──────────────┐ └──────────────┘
│ Browser │◄─── HTTP Response ───┘
└──────────────┘
Receives HTML, renders page
Step-by-Step Process:
- User Action: User enters URL or clicks link
- DNS Resolution: Domain name resolved to IP address
- TCP Connection: Browser establishes TCP connection to server
- HTTP Request: Browser sends HTTP request with method, URI, headers
- Server Processing: Server processes request, accesses resources
- HTTP Response: Server sends response with status code, headers, body
- Rendering: Browser receives response and renders content
- Connection Close: Connection closes (or kept alive for subsequent requests)
Key Differences:
| Aspect | Request | Response |
|---|---|---|
| Initiator | Client (Browser) | Server |
| Purpose | Request resource | Provide resource |
| First Line | Method + URI + Version | Version + Status Code + Phrase |
| Body | Optional (POST/PUT) | Usually present (content) |
Modern Enhancements:
- HTTPS: Encrypted version using SSL/TLS for security
- HTTP/2: Multiplexing, server push, header compression
- HTTP/3: Uses QUIC protocol instead of TCP for better performance
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTTP Definition and Significance │ 3 marks │
│ - HTTP definition and purpose │ │
│ - Key characteristics (stateless, etc.) │ │
│ - Significance points (8 points covered) │ │
│ - Universal standard and web foundation │ │
│ - Platform independence and flexibility │ │
│ - Security with HTTPS │ │
│ │ │
│ 2. Request and Response Phases │ 3 marks │
│ - HTTP Request phase: │ │
│ * Request line components │ │
│ * Request headers │ │
│ * Request body (optional) │ │
│ * Example GET and POST requests │ │
│ - HTTP Response phase: │ │
│ * Status line components │ │
│ * Response headers │ │
│ * Response body │ │
│ * Status codes table │ │
│ * Example response │ │
│ - Complete request-response cycle diagram │ │
│ - Step-by-step process │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Two Equal Major Components (Section 2.2, Pattern 1)
Question 12 (14 marks) — #### a) Explain MIME and its types with examples. Describe why should MIME type information be essentially included in HTTP responses. (8 marks)
a) Explain MIME and its types with examples. Describe why should MIME type information be essentially included in HTTP responses. (8 marks)
Answer:
MIME (Multipurpose Internet Mail Extensions):
MIME is a standard that extends the format of email messages and, more broadly, specifies the nature and format of files being transmitted over the internet. MIME type is a label used to identify the type of data contained in a file, enabling applications to process it correctly.
MIME Type Format:
type/subtype
- Type: General category (text, image, audio, video, application, etc.)
- Subtype: Specific format within the category
Example: text/html means text type with HTML subtype
Types of MIME:
*1. Text Type (`text/`):**
Used for human-readable text content.
| MIME Type | Description | File Extension |
|---|---|---|
text/plain |
Plain text without formatting | .txt |
text/html |
HTML documents | .html, .htm |
text/css |
Cascading Style Sheets | .css |
text/javascript |
JavaScript code | .js |
text/csv |
Comma-Separated Values | .csv |
text/xml |
XML documents | .xml |
Example:
Content-Type: text/html; charset=UTF-8
*2. Image Type (`image/`):**
Used for image files and graphics.
| 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/bmp |
Bitmap images | .bmp |
image/x-icon |
Icon files | .ico |
Example:
Content-Type: image/jpeg
*3. Audio Type (`audio/`):**
Used for audio files and streams.
| MIME Type | Description | File Extension |
|---|---|---|
audio/mpeg |
MP3 audio files | .mp3 |
audio/wav |
WAV audio files | .wav |
audio/ogg |
Ogg audio files | .ogg |
audio/webm |
WebM audio | .webm |
audio/aac |
AAC audio files | .aac |
Example:
Content-Type: audio/mpeg
*4. Video Type (`video/`):**
Used for video files and streams.
| MIME Type | Description | File Extension |
|---|---|---|
video/mp4 |
MP4 video files | .mp4 |
video/mpeg |
MPEG video files | .mpeg, .mpg |
video/webm |
WebM video | .webm |
video/ogg |
Ogg video files | .ogv |
video/quicktime |
QuickTime video | .mov |
video/x-msvideo |
AVI video files | .avi |
Example:
Content-Type: video/mp4
*5. Application Type (`application/`):**
Used for binary data and application-specific formats.
| MIME Type | Description | File Extension |
|---|---|---|
application/json |
JSON data | .json |
application/xml |
XML data | .xml |
application/pdf |
PDF documents | |
application/zip |
ZIP archives | .zip |
application/x-www-form-urlencoded |
Form data | - |
application/octet-stream |
Generic binary data | .bin, .exe |
application/javascript |
JavaScript files | .js |
application/msword |
Microsoft Word | .doc |
application/vnd.ms-excel |
Microsoft Excel | .xls |
Example:
Content-Type: application/json
*6. Multipart Type (`multipart/`):**
Used when message contains multiple parts with different MIME types.
| MIME Type | Description |
|---|---|
multipart/form-data |
Form data with file uploads |
multipart/mixed |
Mixed content types |
multipart/alternative |
Alternative representations |
Example:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Why MIME Type Information Must Be Included in HTTP Responses:
1. Correct Content Interpretation:
- Browsers need to know how to process and display the received data
- Without MIME type, browser may misinterpret content (e.g., display HTML as plain text)
- Ensures proper rendering of web pages, images, videos, and documents
Example:
# Without proper MIME type, HTML might display as text
Content-Type: text/plain ❌
<!DOCTYPE html><html>...</html> # Displays as text
# With correct MIME type, HTML is rendered
Content-Type: text/html ✓
<!DOCTYPE html><html>...</html> # Renders as web page
2. Security:
- Prevents security vulnerabilities like content sniffing attacks
- Browser respects declared MIME type instead of guessing
- Prevents malicious files from being executed unexpectedly
X-Content-Type-Options: nosniffheader reinforces this
Example of Security Risk:
# Malicious scenario without MIME type:
# Browser might "sniff" content and execute JavaScript in a PNG file
# Secure scenario with explicit MIME type:
Content-Type: image/png # Browser treats strictly as image
3. Plugin/Application Selection:
- Operating system uses MIME type to determine which application to open a file
- Browser plugins (PDF viewer, media player) are selected based on MIME type
- Ensures correct handler for downloaded files
4. Caching and Performance:
- Caching mechanisms use MIME type to determine cacheable content
- Proxy servers and CDNs make caching decisions based on content type
- Different caching strategies for static resources vs. dynamic content
5. Content Negotiation:
- Server can send different formats based on client's
Acceptheader - Enables serving optimal content format for each client
- Supports internationalization and localization
Example:
# Client request
Accept: application/json, text/html
# Server can choose appropriate format to return
Content-Type: application/json # or Content-Type: text/html
6. Mobile and Responsive Design:
- Mobile browsers handle content differently based on MIME type
- Responsive images and videos rely on correct MIME types
- Progressive web apps depend on proper MIME type declarations
7. Character Encoding:
- MIME type can specify character encoding (UTF-8, ISO-8859-1)
- Prevents character display issues across different languages
- Essential for internationalization
Example:
Content-Type: text/html; charset=UTF-8
8. API Communication:
- RESTful APIs rely on MIME types for request/response format negotiation
- JSON, XML, and other data formats must be explicitly declared
- Enables automatic parsing by client libraries
Example API Response:
Content-Type: application/json; charset=UTF-8
{
"status": "success",
"data": {...}
}
9. File Downloads:
- Determines whether file is displayed in browser or downloaded
Content-Dispositionheader works in conjunction with MIME type- Controls download behavior and default file names
Example:
Content-Type: application/pdf
Content-Disposition: attachment; filename="document.pdf"
10. Standards Compliance:
- HTTP specification requires Content-Type header for many responses
- Ensures interoperability between different web technologies
- Maintains consistency across the web ecosystem
HTTP Response Example with MIME Type:
HTTP/1.1 200 OK
Date: Wed, 15 Nov 2024 10:30:00 GMT
Server: Apache/2.4.41
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
Cache-Control: max-age=3600
<!DOCTYPE html>
<html>
<head><title>Example</title></head>
<body><h1>Hello World</h1></body>
</html>
Consequences of Missing or Incorrect MIME Type:
| Issue | Impact |
|---|---|
| No MIME type | Browser guesses (content sniffing), security risk |
| Wrong MIME type | Content displayed incorrectly or not at all |
| Generic MIME type | application/octet-stream forces download |
| Mismatched encoding | Garbled text, special characters display incorrectly |
Best Practices:
- Always specify MIME type in HTTP responses
- Include character encoding for text-based content
- Use correct, specific MIME types (avoid generic types)
- Set
X-Content-Type-Options: nosnifffor security - Use
Content-Dispositionfor downloads - Test MIME types across different browsers
Conclusion:
MIME type information is essential in HTTP responses because it ensures correct content interpretation, maintains security, enables proper caching, facilitates content negotiation, and ensures standards compliance. Without it, web applications would be unreliable, insecure, and incompatible across different platforms and browsers.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. MIME Explanation and Types │ 4 marks │
│ - MIME definition and purpose │ │
│ - MIME type format (type/subtype) │ │
│ - Six types of MIME with examples: │ │
│ * Text type (text/*) │ │
│ * Image type (image/*) │ │
│ * Audio type (audio/*) │ │
│ * Video type (video/*) │ │
│ * Application type (application/*) │ │
│ * Multipart type (multipart/*) │ │
│ - Comprehensive tables with extensions │ │
│ │ │
│ 2. Importance in HTTP Responses │ 4 marks │
│ - Correct content interpretation │ │
│ - Security benefits │ │
│ - Plugin/application selection │ │
│ - Caching and performance │ │
│ - Content negotiation │ │
│ - Mobile and responsive design │ │
│ - Character encoding │ │
│ - API communication │ │
│ - File downloads │ │
│ - Standards compliance │ │
│ - HTTP response examples │ │
│ - Consequences table and best practices │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Two Equal Major Concepts (Section 3.2, Pattern 1)
b) Write HTML code to design a web page to create a table with 5 rows and 3 columns for entering the mark list of 4 students. Assume suitable headings for each column. (6 marks)
Answer:
HTML Code for Student Mark List Table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Mark List</title>
</head>
<body>
<h2>Student Mark List - CST463 Web Programming</h2>
<table border="1">
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
<tr>
<td>101</td>
<td>Rahul Kumar</td>
<td>85</td>
</tr>
<tr>
<td>102</td>
<td>Priya Sharma</td>
<td>92</td>
</tr>
<tr>
<td>103</td>
<td>Amit Patel</td>
<td>78</td>
</tr>
<tr>
<td>104</td>
<td>Sneha Reddy</td>
<td>88</td>
</tr>
</table>
</body>
</html>
Enhanced Version with Styling:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Mark List</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f5f5f5;
}
h2 {
color: #333;
text-align: center;
}
table {
width: 70%;
margin: 20px auto;
border-collapse: collapse;
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
th {
background-color: #4CAF50;
color: white;
padding: 12px;
text-align: left;
font-weight: bold;
}
td {
padding: 10px;
border: 1px solid #ddd;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<h2>Student Mark List - CST463 Web Programming</h2>
<table>
<thead>
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Rahul Kumar</td>
<td>85</td>
</tr>
<tr>
<td>102</td>
<td>Priya Sharma</td>
<td>92</td>
</tr>
<tr>
<td>103</td>
<td>Amit Patel</td>
<td>78</td>
</tr>
<tr>
<td>104</td>
<td>Sneha Reddy</td>
<td>88</td>
</tr>
</tbody>
</table>
</body>
</html>
Alternative Version with Additional Columns:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Detailed Student Mark List</title>
<style>
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse;
}
th, td {
border: 1px solid #333;
padding: 10px;
text-align: center;
}
th {
background-color: #2196F3;
color: white;
}
tr:nth-child(even) {
background-color: #e3f2fd;
}
</style>
</head>
<body>
<h2 style="text-align: center;">Student Mark List - May 2024 Examination</h2>
<table>
<tr>
<th>S.No</th>
<th>Roll Number</th>
<th>Student Name</th>
<th>Marks Obtained (Out of 100)</th>
<th>Grade</th>
</tr>
<tr>
<td>1</td>
<td>CS101</td>
<td>Arjun Menon</td>
<td>85</td>
<td>A</td>
</tr>
<tr>
<td>2</td>
<td>CS102</td>
<td>Diya Thomas</td>
<td>92</td>
<td>A+</td>
</tr>
<tr>
<td>3</td>
<td>CS103</td>
<td>Karthik Nair</td>
<td>78</td>
<td>B+</td>
</tr>
<tr>
<td>4</td>
<td>CS104</td>
<td>Meera Krishnan</td>
<td>88</td>
<td>A</td>
</tr>
</table>
</body>
</html>
Explanation:
- Table Structure: 5 rows total (1 header row + 4 data rows for students)
- Three Columns: Roll No, Student Name, Marks Obtained
- Header Row (
<th>): Defines column headings with bold text - Data Rows (
<td>): Contains student information - Styling: Internal CSS for professional appearance (alternating row colors, hover effects)
- Semantic HTML: Uses
<thead>and<tbody>for better structure
Output Display:
Student Mark List - CST463 Web Programming
┌──────────┬───────────────────┬──────────────────┐
│ Roll No │ Student Name │ Marks Obtained │
├──────────┼───────────────────┼──────────────────┤
│ 101 │ Rahul Kumar │ 85 │
├──────────┼───────────────────┼──────────────────┤
│ 102 │ Priya Sharma │ 92 │
├──────────┼───────────────────┼──────────────────┤
│ 103 │ Amit Patel │ 78 │
├──────────┼───────────────────┼──────────────────┤
│ 104 │ Sneha Reddy │ 88 │
└──────────┴───────────────────┴──────────────────┘
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete HTML Table Code │ 6 marks │
│ - HTML5 document structure (DOCTYPE, etc.) │ │
│ - Table creation with 5 rows │ │
│ * 1 header row with <th> tags │ │
│ * 4 data rows for students │ │
│ - 3 columns as specified │ │
│ * Roll No / Roll Number │ │
│ * Student Name │ │
│ * Marks Obtained │ │
│ - Proper table tags (<table>, <tr>, etc.) │ │
│ - Suitable headings for columns │ │
│ - Border attribute or CSS styling │ │
│ - Complete, runnable code │ │
│ - Enhanced version with internal CSS │ │
│ - Alternative version with more columns │ │
│ - Semantic HTML (thead, tbody) │ │
│ - Explanation and output display │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Question (Section 2.2, Pattern 5)
Module II — Module II
Question 13 (14 marks) — #### a) Explain CSS and its types. How can CSS be used to display a XML document? Illustrate with an example. (8 marks)
a) Explain CSS and its types. How can CSS be used to display a XML document? Illustrate with an example. (8 marks)
Answer:
CSS (Cascading Style Sheets):
CSS is a stylesheet language used to describe the presentation and formatting of HTML and XML documents. It controls the visual appearance of web pages, separating content (HTML) from presentation (CSS), which improves maintainability, flexibility, and accessibility.
Key Features of CSS:
- Separation of Concerns: Keeps content separate from presentation
- Reusability: Same styles can be applied to multiple elements
- Cascading Nature: Multiple stylesheets can be combined with a priority hierarchy
- Responsive Design: Supports media queries for different devices
- Cross-browser Compatibility: Works across all modern browsers
Types of CSS:
1. Inline CSS:
Styles are applied directly to HTML elements using the style attribute.
Advantages:
- Highest priority in cascading order
- Quick for testing single elements
- No external file needed
Disadvantages:
- Not reusable
- Difficult to maintain
- Mixes content with presentation
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Example</title>
</head>
<body>
<h1 style="color: blue; text-align: center;">Welcome</h1>
<p style="font-size: 18px; color: green;">This is a paragraph with inline CSS.</p>
<div style="background-color: yellow; padding: 10px; border: 2px solid black;">
This div has inline styles.
</div>
</body>
</html>
2. Internal CSS (Embedded CSS):
Styles are defined within the <style> tag in the <head> section of an HTML document.
Advantages:
- Styles can be reused within the same document
- No additional HTTP requests
- Good for single-page websites
Disadvantages:
- Cannot be shared across multiple pages
- Increases HTML file size
- Not cached separately
Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: navy;
text-align: center;
text-decoration: underline;
}
p {
font-size: 16px;
line-height: 1.6;
color: #333;
}
.highlight {
background-color: yellow;
font-weight: bold;
}
#main-content {
width: 80%;
margin: 0 auto;
padding: 20px;
background-color: white;
}
</style>
</head>
<body>
<div id="main-content">
<h1>Internal CSS Demo</h1>
<p>This paragraph uses internal CSS styling.</p>
<p class="highlight">This paragraph has the highlight class.</p>
</div>
</body>
</html>
3. External CSS:
Styles are defined in a separate .css file and linked to HTML documents using the <link> tag.
Advantages:
- Maximum reusability across multiple pages
- Separate file is cached by browser (faster loading)
- Easier maintenance and updates
- Keeps HTML clean and focused on content
- Follows best practices and industry standards
Disadvantages:
- Requires additional HTTP request
- Page may load with unstyled content briefly (FOUC - Flash of Unstyled Content)
Example:
styles.css file:
/* External CSS File: styles.css */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #e9ecef;
margin: 0;
padding: 0;
}
header {
background-color: #007bff;
color: white;
padding: 20px;
text-align: center;
}
nav {
background-color: #343a40;
padding: 10px;
}
nav a {
color: white;
text-decoration: none;
padding: 10px 15px;
display: inline-block;
}
nav a:hover {
background-color: #495057;
}
.container {
width: 90%;
max-width: 1200px;
margin: 20px auto;
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
footer {
background-color: #343a40;
color: white;
text-align: center;
padding: 15px;
position: fixed;
bottom: 0;
width: 100%;
}
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
<div class="container">
<h2>Welcome to My Website</h2>
<p>This page uses external CSS for styling.</p>
</div>
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
</body>
</html>
Comparison of CSS Types:
| Feature | Inline CSS | Internal CSS | External CSS |
|---|---|---|---|
| Location | Within HTML tag | <style> in <head> |
Separate .css file |
| Reusability | No | Within same page only | Across multiple pages |
| Maintenance | Difficult | Moderate | Easy |
| Performance | No extra request | No extra request | One extra HTTP request |
| Best for | Quick tests | Single-page sites | Multi-page websites |
| Priority | Highest | Medium | Lowest |
| Caching | No | No | Yes |
| Recommended | No | For specific cases | Yes (Best Practice) |
Using CSS to Display XML Documents:
XML (eXtensible Markup Language) stores data in a structured format but has no built-in presentation. CSS can be used to format and display XML data in a browser by defining styles for XML elements.
How it Works:
- XML file contains data with custom tags
- CSS file defines display properties for those tags
- XML file references the CSS file using a processing instruction
- Browser applies CSS rules to render the XML data
Complete Example:
Step 1: Create XML File (students.xml):
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="students.css"?>
<university>
<title>Student Information System</title>
<students>
<student>
<rollno>CS101</rollno>
<name>Arjun Menon</name>
<course>B.Tech Computer Science</course>
<marks>85</marks>
<grade>A</grade>
</student>
<student>
<rollno>CS102</rollno>
<name>Priya Sharma</name>
<course>B.Tech Computer Science</course>
<marks>92</marks>
<grade>A+</grade>
</student>
<student>
<rollno>CS103</rollno>
<name>Karthik Nair</name>
<course>B.Tech Computer Science</course>
<marks>78</marks>
<grade>B+</grade>
</student>
<student>
<rollno>CS104</rollno>
<name>Diya Thomas</name>
<course>B.Tech Computer Science</course>
<marks>88</marks>
<grade>A</grade>
</student>
</students>
</university>
Step 2: Create CSS File (students.css):
/* CSS for XML Display */
university {
display: block;
background-color: #f5f5f5;
padding: 20px;
font-family: Arial, sans-serif;
}
title {
display: block;
font-size: 28px;
font-weight: bold;
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
padding: 15px;
background-color: #3498db;
color: white;
border-radius: 5px;
}
students {
display: block;
margin: 20px auto;
width: 90%;
max-width: 800px;
}
student {
display: block;
background-color: white;
border: 2px solid #3498db;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
student:hover {
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
transform: translateY(-2px);
transition: all 0.3s ease;
}
rollno {
display: block;
font-size: 18px;
font-weight: bold;
color: #e74c3c;
margin-bottom: 10px;
}
rollno:before {
content: "Roll No: ";
color: #2c3e50;
font-weight: normal;
}
name {
display: block;
font-size: 20px;
color: #2c3e50;
font-weight: bold;
margin-bottom: 10px;
}
name:before {
content: "Name: ";
font-weight: normal;
color: #7f8c8d;
}
course {
display: block;
font-size: 16px;
color: #34495e;
margin-bottom: 10px;
}
course:before {
content: "Course: ";
font-weight: bold;
color: #2c3e50;
}
marks {
display: inline-block;
font-size: 16px;
color: #16a085;
font-weight: bold;
margin-right: 20px;
}
marks:before {
content: "Marks: ";
color: #2c3e50;
font-weight: normal;
}
marks:after {
content: "/100";
color: #7f8c8d;
font-weight: normal;
}
grade {
display: inline-block;
font-size: 16px;
background-color: #27ae60;
color: white;
padding: 5px 15px;
border-radius: 20px;
font-weight: bold;
}
grade:before {
content: "Grade: ";
}
How to View:
- Save both files in the same directory
- Open
students.xmlin a web browser - The browser will apply the CSS styles and display formatted data
Visual Output:
┌─────────────────────────────────────────────┐
│ Student Information System │
│ (Blue background, centered, white text) │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ Roll No: CS101 │
│ Name: Arjun Menon │
│ Course: B.Tech Computer Science │
│ Marks: 85/100 [Grade: A] │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ Roll No: CS102 │
│ Name: Priya Sharma │
│ Course: B.Tech Computer Science │
│ Marks: 92/100 [Grade: A+] │
└─────────────────────────────────────────────┘
[Additional students...]
Key Points:
- XML elements behave like HTML elements when styled with CSS
- Use
display: blockordisplay: inlineto control layout - CSS pseudo-elements (
:before,:after) can add labels - All standard CSS properties can be applied to XML elements
- Browser must support XML+CSS rendering (all modern browsers do)
Advantages of Using CSS with XML:
- Presentation Flexibility: Same XML data can have multiple CSS presentations
- Clean Separation: Data (XML) separate from presentation (CSS)
- Easy Updates: Change appearance without modifying data
- Reusability: Same CSS can style multiple XML documents
- No Server Processing: Direct browser rendering without XSLT
Limitations:
- Limited compared to XSLT for complex transformations
- Not all browsers display XML+CSS identically
- Cannot restructure or reorder XML elements
- Best for simple display requirements
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. CSS Explanation and Types │ 4 marks │
│ - CSS definition and purpose │ │
│ - Key features (separation, reusability) │ │
│ - Three types of CSS: │ │
│ * Inline CSS (advantages, disadvantages) │ │
│ * Internal CSS (advantages, disadvantages)│ │
│ * External CSS (advantages, disadvantages)│ │
│ - Complete code examples for each type │ │
│ - Priority hierarchy explanation │ │
│ │ │
│ 2. CSS for XML Display with Example │ 4 marks │
│ - Explanation of XML+CSS usage │ │
│ - Process/steps to apply CSS to XML │ │
│ - Complete XML document example │ │
│ - Complete CSS stylesheet example │ │
│ - Linking mechanism (xml-stylesheet) │ │
│ - Output description │ │
│ - Advantages and limitations │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Two Equal Major Concepts (Section 3.2, Pattern 1)
b) Explain the concept of Class selectors in CSS with examples. (6 marks)
Answer:
Class Selectors in CSS:
A class selector is a type of CSS selector that targets HTML elements based on their class attribute value. Class selectors are defined with a dot (.) followed by the class name and allow the same style to be applied to multiple elements across a webpage.
Syntax:
.classname {
property: value;
}
HTML Usage:
<element class="classname">Content</element>
Key Characteristics:
- Reusable: Same class can be applied to multiple elements
- Multiple Classes: An element can have multiple classes (space-separated)
- Case-Sensitive: Class names are case-sensitive
- Naming Rules: Can contain letters, digits, hyphens, underscores; must start with a letter
- Specificity: More specific than element selectors, less specific than ID selectors
Basic Class Selector Examples:
Example 1: Single Class Application
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
padding: 5px;
}
</style>
</head>
<body>
<p>This is a normal paragraph.</p>
<p class="highlight">This paragraph is highlighted.</p>
<p>Another normal paragraph.</p>
<p class="highlight">This paragraph is also highlighted.</p>
</body>
</html>
Output: The 2nd and 4th paragraphs will have yellow background and bold text.
Example 2: Multiple Classes on Same Element
<!DOCTYPE html>
<html>
<head>
<style>
.large {
font-size: 24px;
}
.bold {
font-weight: bold;
}
.blue {
color: blue;
}
.underline {
text-decoration: underline;
}
</style>
</head>
<body>
<p class="large">Large text</p>
<p class="large bold">Large and bold text</p>
<p class="large bold blue">Large, bold, and blue text</p>
<p class="large bold blue underline">Large, bold, blue, and underlined text</p>
</body>
</html>
Explanation: Each element can combine multiple classes, and all corresponding styles are applied.
Example 3: Class Selector with Element Selector
You can combine element selectors with class selectors to target specific elements with a class.
<!DOCTYPE html>
<html>
<head>
<style>
/* Applies to all elements with class 'important' */
.important {
color: red;
}
/* Applies only to <p> elements with class 'important' */
p.important {
font-size: 20px;
background-color: #ffe6e6;
padding: 10px;
}
/* Applies only to <span> elements with class 'important' */
span.important {
font-weight: bold;
border-bottom: 2px solid red;
}
</style>
</head>
<body>
<p class="important">This is an important paragraph with special styling.</p>
<p>This is a normal paragraph.</p>
<span class="important">This is an important span with different styling.</span>
<div class="important">This div has the important class but less specific styling.</div>
</body>
</html>
Example 4: Descendant Selector with Classes
<!DOCTYPE html>
<html>
<head>
<style>
.container {
border: 2px solid #333;
padding: 20px;
margin: 10px;
}
.container h2 {
color: darkblue;
border-bottom: 2px solid darkblue;
}
.container p {
line-height: 1.6;
color: #555;
}
.container .special {
background-color: lightblue;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h2>Section Title</h2>
<p>This is a regular paragraph inside the container.</p>
<p class="special">This is a special paragraph inside the container.</p>
</div>
<p class="special">This special paragraph is outside the container.</p>
</body>
</html>
Example 5: Practical Website Layout with Classes
<!DOCTYPE html>
<html>
<head>
<title>Class Selector Example</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
.header {
background-color: #35424a;
color: white;
padding: 20px;
text-align: center;
}
.nav {
background-color: #2c3e50;
padding: 10px;
}
.nav-link {
color: white;
text-decoration: none;
padding: 10px 15px;
display: inline-block;
}
.nav-link:hover {
background-color: #34495e;
border-radius: 5px;
}
.container {
width: 80%;
margin: 20px auto;
}
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.card-title {
color: #2c3e50;
font-size: 24px;
margin-bottom: 10px;
}
.card-content {
color: #555;
font-size: 16px;
}
.btn {
display: inline-block;
padding: 10px 20px;
text-decoration: none;
border-radius: 5px;
cursor: pointer;
}
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover {
background-color: #2980b9;
}
.btn-success {
background-color: #27ae60;
color: white;
}
.btn-success:hover {
background-color: #229954;
}
.footer {
background-color: #35424a;
color: white;
text-align: center;
padding: 20px;
margin-top: 40px;
}
</style>
</head>
<body>
<header class="header">
<h1>My Website</h1>
</header>
<nav class="nav">
<a href="#" class="nav-link">Home</a>
<a href="#" class="nav-link">About</a>
<a href="#" class="nav-link">Services</a>
<a href="#" class="nav-link">Contact</a>
</nav>
<div class="container">
<div class="card">
<h2 class="card-title">Service 1</h2>
<p class="card-content">Description of service 1 goes here.</p>
<a href="#" class="btn btn-primary">Learn More</a>
</div>
<div class="card">
<h2 class="card-title">Service 2</h2>
<p class="card-content">Description of service 2 goes here.</p>
<a href="#" class="btn btn-success">Get Started</a>
</div>
</div>
<footer class="footer">
<p>© 2024 My Website. All rights reserved.</p>
</footer>
</body>
</html>
Advantages of Class Selectors:
- Reusability: Apply same style to multiple elements
- Maintainability: Update one class definition to change all instances
- Flexibility: Combine multiple classes on single element
- Organization: Semantic class names make code readable
- Modularity: Create reusable style components
Comparison: Class vs ID vs Element Selectors:
| Feature | Class Selector | ID Selector | Element Selector |
|---|---|---|---|
| Syntax | .classname |
#idname |
element |
| Reusability | Multiple elements | One element only | All elements of that type |
| Specificity | Medium (10) | High (100) | Low (1) |
| Best Use | Styling groups | Unique elements | General styling |
| Example | .button |
#header |
p |
Best Practices:
- Use meaningful, descriptive class names
- Follow naming conventions (BEM, SMACSS, etc.)
- Avoid overly specific selectors
- Prefer classes over IDs for styling
- Use hyphens or underscores for multi-word names (
.nav-link,.nav_link)
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Class Selector Concept and Explanation │ 6 marks │
│ - Definition of class selectors │ │
│ - Syntax (.classname) │ │
│ - Key characteristics (reusable, multiple, │ │
│ case-sensitive, naming rules, specificity)│ │
│ - Multiple comprehensive examples: │ │
│ * Single class application │ │
│ * Multiple classes on one element │ │
│ * Class with element selector combination │ │
│ * Descendant selector with classes │ │
│ * Real-world examples (navigation, cards) │ │
│ - Complete HTML/CSS code demonstrations │ │
│ - Advantages over other selectors │ │
│ - Class vs ID comparison │ │
│ - Best practices for class usage │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept Explanation (Section 2.2, Pattern 5)
Question 14 (14 marks) — #### a) Describe Java Script. Discuss various types of control statements in JavaScript. (8 marks)
a) Describe Java Script. Discuss various types of control statements in JavaScript. (8 marks)
Answer:
JavaScript:
JavaScript is a high-level, interpreted, dynamically-typed programming language primarily used for creating interactive and dynamic content on web pages. It is one of the core technologies of the web, alongside HTML and CSS.
Key Characteristics:
- Client-Side Scripting: Runs in the user's browser without server interaction
- Event-Driven: Responds to user actions (clicks, key presses, mouse movements)
- Object-Oriented: Supports objects, prototypes, and classes
- Dynamic Typing: Variable types are determined at runtime
- Functional Programming: Functions are first-class objects
- Cross-Platform: Works on all modern browsers and platforms
Capabilities:
- Manipulate HTML and CSS (DOM manipulation)
- Handle user events (clicks, form submissions, keyboard inputs)
- Validate form data before submission
- Create animations and interactive effects
- Make asynchronous HTTP requests (AJAX, Fetch API)
- Store data locally (localStorage, sessionStorage, cookies)
- Build complete web applications (SPAs with frameworks like React, Angular, Vue)
JavaScript in HTML:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script>
// JavaScript code here
function greet() {
alert("Hello, JavaScript!");
}
</script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>
Control Statements in JavaScript:
Control statements direct the flow of program execution based on conditions and loops. They are categorized into three main types:
1. Conditional Statements:
Control flow based on boolean conditions.
a) if Statement:
Executes a block of code if a specified condition is true.
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
// Output: You are an adult.
b) if-else Statement:
Executes one block if condition is true, another if false.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
let marks = 45;
if (marks >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
// Output: Fail
c) if-else-if Ladder:
Tests multiple conditions sequentially.
Syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if all conditions are false
}
Example:
let score = 75;
if (score >= 90) {
console.log("Grade: A+");
} else if (score >= 80) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B+");
} else if (score >= 60) {
console.log("Grade: B");
} else if (score >= 50) {
console.log("Grade: C");
} else {
console.log("Grade: F (Fail)");
}
// Output: Grade: B+
d) switch Statement:
Selects one of many code blocks to execute based on a value.
Syntax:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
case value3:
// code for value3
break;
default:
// code if no case matches
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log("Today is: " + dayName);
// Output: Today is: Wednesday
Example with Fall-Through:
let month = 2;
let season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Fall";
break;
default:
season = "Invalid month";
}
console.log("Season: " + season);
// Output: Season: Winter
2. Looping Statements (Iteration Statements):
Execute a block of code repeatedly based on a condition.
a) for Loop:
Repeats code a specified number of times.
Syntax:
for (initialization; condition; increment/decrement) {
// code to repeat
}
Example:
// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
// Calculate sum of first 10 natural numbers
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("Sum: " + sum);
// Output: Sum: 55
// Print multiplication table
let num = 5;
for (let i = 1; i <= 10; i++) {
console.log(num + " x " + i + " = " + (num * i));
}
b) while Loop:
Repeats code while a condition is true. Condition is checked before each iteration.
Syntax:
while (condition) {
// code to repeat
}
Example:
// Print numbers 1 to 5
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1 2 3 4 5
// Find factorial
let n = 5;
let factorial = 1;
let count = n;
while (count > 0) {
factorial *= count;
count--;
}
console.log("Factorial of " + n + " = " + factorial);
// Output: Factorial of 5 = 120
c) do-while Loop:
Executes code at least once, then repeats while condition is true. Condition is checked after each iteration.
Syntax:
do {
// code to repeat
} while (condition);
Example:
// Print numbers 1 to 5
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
// Executes at least once even if condition is false
let x = 10;
do {
console.log("Executed once: x = " + x);
} while (x < 5);
// Output: Executed once: x = 10
Difference: while vs do-while
// while loop - may not execute at all
let a = 10;
while (a < 5) {
console.log("This won't print");
}
// Output: (nothing)
// do-while loop - executes at least once
let b = 10;
do {
console.log("This prints once");
} while (b < 5);
// Output: This prints once
d) for...in Loop:
Iterates over properties of an object.
Syntax:
for (variable in object) {
// code to execute
}
Example:
const person = {
name: "John",
age: 30,
city: "New York",
occupation: "Developer"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: John
// age: 30
// city: New York
// occupation: Developer
e) for...of Loop:
Iterates over iterable objects (arrays, strings, etc.).
Syntax:
for (variable of iterable) {
// code to execute
}
Example:
// Iterate over array
const fruits = ["Apple", "Banana", "Orange", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: Apple, Banana, Orange, Mango
// Iterate over string
const text = "Hello";
for (let char of text) {
console.log(char);
}
// Output: H e l l o (each on new line)
3. Jump Statements:
Alter the normal flow of control.
a) break Statement:
Exits a loop or switch statement immediately.
Example:
// Exit loop when i equals 5
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
// Output: 1 2 3 4
// Find first even number
const numbers = [1, 3, 7, 8, 9, 10];
for (let num of numbers) {
if (num % 2 === 0) {
console.log("First even number: " + num);
break;
}
}
// Output: First even number: 8
b) continue Statement:
Skips the current iteration and continues with the next.
Example:
// Skip even numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
// Output: 1 3 5 7 9
// Skip negative numbers
const numbers = [5, -2, 10, -7, 15, 20];
for (let num of numbers) {
if (num < 0) {
continue;
}
console.log(num);
}
// Output: 5 10 15 20
c) return Statement:
Exits a function and optionally returns a value.
Example:
function findMax(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
let result = findMax(15, 20);
console.log("Maximum: " + result);
// Output: Maximum: 20
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
Complete Example: Combining Control Statements
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Control Statements Demo</title>
</head>
<body>
<h2>Prime Number Checker</h2>
<script>
function isPrime(num) {
// Conditional statement
if (num <= 1) {
return false;
}
if (num === 2) {
return true;
}
if (num % 2 === 0) {
return false;
}
// Loop with break
for (let i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
// Test numbers from 1 to 20
console.log("Prime numbers from 1 to 20:");
for (let i = 1; i <= 20; i++) {
if (isPrime(i)) {
console.log(i);
}
}
// Output: 2, 3, 5, 7, 11, 13, 17, 19
// Grade calculator using switch
function getGrade(marks) {
let grade;
switch (true) {
case (marks >= 90):
grade = "A+";
break;
case (marks >= 80):
grade = "A";
break;
case (marks >= 70):
grade = "B+";
break;
case (marks >= 60):
grade = "B";
break;
case (marks >= 50):
grade = "C";
break;
default:
grade = "F";
}
return grade;
}
console.log("Grade for 85: " + getGrade(85));
// Output: Grade for 85: A
</script>
</body>
</html>
Summary Table:
| Control Statement | Purpose | When to Use |
|---|---|---|
| if | Execute code if condition is true | Single condition check |
| if-else | Choose between two blocks | Two alternatives |
| if-else-if | Test multiple conditions | Multiple alternatives |
| switch | Multi-way branch based on value | Many discrete values |
| for | Repeat known number of times | Counter-based loops |
| while | Repeat while condition is true | Unknown iterations, condition first |
| do-while | Execute at least once, then repeat | Execute first, check later |
| for...in | Iterate object properties | Object enumeration |
| for...of | Iterate iterable collections | Arrays, strings, etc. |
| break | Exit loop/switch immediately | Early termination |
| continue | Skip current iteration | Skip specific cases |
| return | Exit function with value | Function termination |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JavaScript Description │ 3 marks │
│ - Definition and purpose │ │
│ - Key characteristics (client-side, event- │ │
│ driven, object-oriented, dynamic typing) │ │
│ - Capabilities and use cases │ │
│ - JavaScript in HTML example │ │
│ - Role in modern web development │ │
│ │ │
│ 2. Control Statements in JavaScript │ 5 marks │
│ - Conditional statements: │ │
│ * if statement with syntax and example │ │
│ * if-else statement with example │ │
│ * if-else if-else with example │ │
│ * switch statement with example │ │
│ * Ternary operator │ │
│ - Loop statements: │ │
│ * for loop with syntax and example │ │
│ * while loop with example │ │
│ * do-while loop with example │ │
│ * for...in loop for objects │ │
│ * for...of loop for iterables │ │
│ - Jump statements: │ │
│ * break statement │ │
│ * continue statement │ │
│ * return statement │ │
│ - Complete code examples for each type │ │
│ - Summary comparison table │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Definition + Detailed Components (Section 3)
b) Explain the concept of Document Object Model with example. (6 marks)
Answer:
Document Object Model (DOM):
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects, where each node in the tree represents a part of the document (element, attribute, text, etc.). The DOM allows programs (particularly JavaScript) to access, modify, add, or delete elements and content dynamically.
Key Characteristics:
- Tree Structure: Represents HTML document as a hierarchical tree
- Cross-Platform: Works across different browsers and platforms
- Language-Independent: Can be used with any programming language (primarily JavaScript on web)
- Dynamic: Changes to DOM are reflected immediately in the browser
- Object-Oriented: Every element is an object with properties and methods
DOM Tree Structure:
Document
└── html (root element)
├── head
│ ├── title
│ │ └── text: "Page Title"
│ └── meta
└── body
├── h1
│ └── text: "Heading"
├── p
│ ├── text: "Paragraph "
│ ├── strong
│ │ └── text: "bold"
│ └── text: " text."
└── div
└── img
DOM Hierarchy:
- Document: Root of the DOM tree
- Element Nodes: HTML tags (
<div>,<p>,<h1>, etc.) - Attribute Nodes: Attributes of elements (
class,id,src, etc.) - Text Nodes: Text content within elements
- Comment Nodes: HTML comments
Accessing DOM Elements:
JavaScript provides several methods to access DOM elements:
| Method | Description | Example |
|---|---|---|
getElementById() |
Select element by ID | document.getElementById("myId") |
getElementsByClassName() |
Select elements by class name | document.getElementsByClassName("myClass") |
getElementsByTagName() |
Select elements by tag name | document.getElementsByTagName("p") |
querySelector() |
Select first element matching CSS selector | document.querySelector(".myClass") |
querySelectorAll() |
Select all elements matching CSS selector | document.querySelectorAll("p.intro") |
DOM Manipulation Methods:
| Operation | Method/Property | Description |
|---|---|---|
| Get Content | innerHTML |
Get/set HTML content |
textContent |
Get/set text content only | |
innerText |
Get/set visible text | |
| Modify Attributes | setAttribute() |
Set attribute value |
getAttribute() |
Get attribute value | |
removeAttribute() |
Remove attribute | |
| Modify Styles | style.property |
Change CSS styles |
| Create Elements | createElement() |
Create new element |
createTextNode() |
Create text node | |
| Add Elements | appendChild() |
Append child to parent |
insertBefore() |
Insert before specific element | |
| Remove Elements | removeChild() |
Remove child element |
remove() |
Remove element itself |
Comprehensive DOM Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f0f0f0;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
max-width: 600px;
margin: 0 auto;
}
.highlight {
background-color: yellow;
padding: 5px;
font-weight: bold;
}
.output {
background-color: #e9ecef;
padding: 15px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<h1 id="main-heading">DOM Manipulation Demo</h1>
<p id="intro-text">This is an introduction paragraph.</p>
<div class="output" id="output">
<p>Output will appear here...</p>
</div>
<h2>Actions:</h2>
<!-- Button to change heading -->
<button onclick="changeHeading()">Change Heading</button>
<!-- Button to modify paragraph -->
<button onclick="modifyParagraph()">Highlight Paragraph</button>
<!-- Button to add new element -->
<button onclick="addElement()">Add New Paragraph</button>
<!-- Button to get element info -->
<button onclick="getElementInfo()">Get Element Info</button>
<!-- Button to modify styles -->
<button onclick="changeStyles()">Change Styles</button>
<!-- Button to remove element -->
<button onclick="removeElement()">Remove Last Added</button>
<div id="dynamic-content"></div>
</div>
<script>
// 1. Accessing DOM Elements
function getElementInfo() {
const heading = document.getElementById("main-heading");
const output = document.getElementById("output");
let info = "<h3>Element Information:</h3>";
info += "<p><strong>Tag Name:</strong> " + heading.tagName + "</p>";
info += "<p><strong>ID:</strong> " + heading.id + "</p>";
info += "<p><strong>Text Content:</strong> " + heading.textContent + "</p>";
info += "<p><strong>Inner HTML:</strong> " + heading.innerHTML + "</p>";
output.innerHTML = info;
}
// 2. Modifying Content
function changeHeading() {
const heading = document.getElementById("main-heading");
heading.innerHTML = "<strong>Heading Changed!</strong> ✓";
heading.style.color = "green";
}
// 3. Modifying Attributes and Classes
function modifyParagraph() {
const para = document.getElementById("intro-text");
para.className = "highlight";
para.textContent = "This paragraph has been highlighted!";
}
// 4. Creating and Adding New Elements
let elementCounter = 0;
function addElement() {
elementCounter++;
// Create new paragraph element
const newPara = document.createElement("p");
// Create text node
const textNode = document.createTextNode("New paragraph #" + elementCounter + " added dynamically!");
// Append text to paragraph
newPara.appendChild(textNode);
// Set attributes
newPara.setAttribute("id", "dynamic-para-" + elementCounter);
newPara.style.backgroundColor = "#d4edda";
newPara.style.padding = "10px";
newPara.style.margin = "5px 0";
newPara.style.borderRadius = "5px";
// Append to container
document.getElementById("dynamic-content").appendChild(newPara);
// Update output
document.getElementById("output").innerHTML =
"<p style='color: green;'>✓ Element added successfully! Total: " + elementCounter + "</p>";
}
// 5. Modifying Styles
function changeStyles() {
const container = document.querySelector(".container");
container.style.backgroundColor = "#ffe6e6";
container.style.border = "3px solid #dc3545";
container.style.transition = "all 0.3s ease";
document.getElementById("output").innerHTML =
"<p style='color: red;'>Container styles modified!</p>";
}
// 6. Removing Elements
function removeElement() {
const dynamicContent = document.getElementById("dynamic-content");
const lastPara = dynamicContent.lastElementChild;
if (lastPara) {
dynamicContent.removeChild(lastPara);
elementCounter--;
document.getElementById("output").innerHTML =
"<p style='color: orange;'>Last element removed. Remaining: " + elementCounter + "</p>";
} else {
document.getElementById("output").innerHTML =
"<p style='color: red;'>No elements to remove!</p>";
}
}
// 7. Event Handling Example
document.getElementById("main-heading").addEventListener("click", function() {
this.style.transform = "scale(1.1)";
this.style.transition = "transform 0.3s ease";
setTimeout(() => {
this.style.transform = "scale(1)";
}, 300);
});
// 8. Traversing DOM
function demonstrateTraversal() {
const intro = document.getElementById("intro-text");
console.log("Parent Node:", intro.parentNode);
console.log("Next Sibling:", intro.nextElementSibling);
console.log("Previous Sibling:", intro.previousElementSibling);
console.log("First Child:", intro.firstChild);
console.log("Last Child:", intro.lastChild);
}
</script>
</body>
</html>
Explanation of Key DOM Operations:
1. Element Selection:
// By ID (fastest, returns single element)
const element = document.getElementById("myId");
// By class name (returns HTMLCollection)
const elements = document.getElementsByClassName("myClass");
// By tag name (returns HTMLCollection)
const paragraphs = document.getElementsByTagName("p");
// Using CSS selectors (most flexible)
const firstDiv = document.querySelector("div.container");
const allDivs = document.querySelectorAll("div");
2. Content Manipulation:
// innerHTML - includes HTML tags
element.innerHTML = "<strong>Bold Text</strong>";
// textContent - plain text only
element.textContent = "Plain Text";
// innerText - visible text only (considers CSS)
element.innerText = "Visible Text";
3. Attribute Manipulation:
// Set attribute
element.setAttribute("class", "highlight");
element.setAttribute("data-id", "123");
// Get attribute
const className = element.getAttribute("class");
// Remove attribute
element.removeAttribute("class");
// Direct property access
element.id = "newId";
element.className = "newClass";
4. Style Manipulation:
// Individual properties
element.style.color = "red";
element.style.backgroundColor = "#f0f0f0";
element.style.fontSize = "20px";
// Multiple properties
element.style.cssText = "color: red; background-color: yellow; font-size: 20px;";
// Get computed style
const styles = window.getComputedStyle(element);
const color = styles.color;
5. Creating and Adding Elements:
// Create element
const newDiv = document.createElement("div");
// Create text node
const text = document.createTextNode("Hello World");
// Append text to element
newDiv.appendChild(text);
// Add to document
document.body.appendChild(newDiv);
// Alternative: innerHTML
newDiv.innerHTML = "<p>Hello World</p>";
6. Removing Elements:
// Remove child from parent
const parent = document.getElementById("parent");
const child = document.getElementById("child");
parent.removeChild(child);
// Remove element itself (modern method)
child.remove();
7. Event Handling:
// Method 1: HTML attribute
<button onclick="myFunction()">Click</button>
// Method 2: DOM property
element.onclick = function() {
alert("Clicked!");
};
// Method 3: addEventListener (best practice)
element.addEventListener("click", function() {
alert("Clicked!");
});
Advantages of DOM:
- Dynamic Updates: Change page content without reloading
- Interactive: Respond to user actions in real-time
- Flexible: Full control over document structure and content
- Standard: Works consistently across browsers
- Powerful: Enable complex single-page applications
Common Use Cases:
- Form validation
- Dynamic content updates
- Animations and transitions
- AJAX-based data loading
- Single Page Applications (SPAs)
- Interactive games and visualizations
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. DOM Concept and Explanation with Examples │ 6 marks │
│ - DOM definition and purpose │ │
│ - Key characteristics (tree structure, │ │
│ cross-platform, dynamic, object-oriented) │ │
│ - DOM tree structure diagram │ │
│ - DOM hierarchy explanation │ │
│ - Node types (element, text, attribute) │ │
│ - DOM manipulation methods: │ │
│ * Element selection methods │ │
│ * Content manipulation methods │ │
│ * Attribute manipulation methods │ │
│ * Style manipulation methods │ │
│ * Creating and removing elements │ │
│ - Complete practical examples: │ │
│ * Accessing elements │ │
│ * Modifying content │ │
│ * Changing styles │ │
│ * Adding new elements │ │
│ * Event handling integration │ │
│ - Real-world applications and use cases │ │
│ - DOM vs HTML comparison │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept Explanation (Section 2.2, Pattern 5)
Module III — Module III
Question 15 (14 marks) — #### a) Illustrate with a sample PHP script, how functions are implemented in PHP. (8 marks)
a) Illustrate with a sample PHP script, how functions are implemented in PHP. (8 marks)
Answer:
Functions in PHP:
A function is a reusable block of code that performs a specific task. Functions help organize code, improve readability, reduce repetition, and make maintenance easier. PHP supports both built-in functions and user-defined functions.
Key Concepts:
- Function Declaration: Define a function once
- Function Call: Execute the function multiple times
- Parameters: Input values passed to functions
- Return Values: Output values returned from functions
- Scope: Variables inside functions are local by default
Basic Function Syntax:
function functionName($parameter1, $parameter2, ...) {
// Function body - code to execute
return $value; // Optional return statement
}
Types of Functions in PHP:
1. Function Without Parameters and Without Return Value:
<?php
// Function definition
function greet() {
echo "Hello, Welcome to PHP Programming!<br>";
echo "This is a simple function without parameters.<br>";
}
// Function call
greet();
greet(); // Can be called multiple times
/* Output:
Hello, Welcome to PHP Programming!
This is a simple function without parameters.
Hello, Welcome to PHP Programming!
This is a simple function without parameters.
*/
?>
2. Function With Parameters But Without Return Value:
<?php
function displayInfo($name, $age, $city) {
echo "Name: $name<br>";
echo "Age: $age<br>";
echo "City: $city<br>";
echo "-------------------<br>";
}
// Function calls with different arguments
displayInfo("Arjun", 25, "Kochi");
displayInfo("Priya", 23, "Bangalore");
displayInfo("Karthik", 27, "Chennai");
/* Output:
Name: Arjun
Age: 25
City: Kochi
-------------------
Name: Priya
Age: 23
City: Bangalore
-------------------
Name: Karthik
Age: 27
City: Chennai
-------------------
*/
?>
3. Function With Parameters and With Return Value:
<?php
function add($a, $b) {
$sum = $a + $b;
return $sum;
}
function multiply($x, $y) {
return $x * $y;
}
// Using returned values
$result1 = add(10, 20);
echo "Sum: $result1<br>";
$result2 = multiply(5, 6);
echo "Product: $result2<br>";
// Direct usage in expressions
echo "15 + 25 = " . add(15, 25) . "<br>";
echo "7 * 8 = " . multiply(7, 8) . "<br>";
/* Output:
Sum: 30
Product: 30
15 + 25 = 40
7 * 8 = 56
*/
?>
4. Function With Default Parameters:
<?php
function calculateDiscount($price, $discountPercent = 10) {
$discount = ($price * $discountPercent) / 100;
$finalPrice = $price - $discount;
return $finalPrice;
}
// Call with both parameters
echo "Price after 20% discount: Rs. " . calculateDiscount(1000, 20) . "<br>";
// Call with default discount (10%)
echo "Price after default discount: Rs. " . calculateDiscount(1000) . "<br>";
/* Output:
Price after 20% discount: Rs. 800
Price after default discount: Rs. 900
*/
?>
5. Function With Variable Number of Arguments:
<?php
// Using func_get_args()
function calculateSum() {
$args = func_get_args();
$total = 0;
foreach ($args as $arg) {
$total += $arg;
}
return $total;
}
echo "Sum of 5, 10, 15: " . calculateSum(5, 10, 15) . "<br>";
echo "Sum of 1, 2, 3, 4, 5: " . calculateSum(1, 2, 3, 4, 5) . "<br>";
echo "Sum of 100, 200: " . calculateSum(100, 200) . "<br>";
/* Output:
Sum of 5, 10, 15: 30
Sum of 1, 2, 3, 4, 5: 15
Sum of 100, 200: 300
*/
// PHP 5.6+ variadic functions with ... operator
function sumAll(...$numbers) {
return array_sum($numbers);
}
echo "Sum using variadic: " . sumAll(10, 20, 30, 40) . "<br>";
/* Output:
Sum using variadic: 100
*/
?>
6. Function With Pass by Value vs Pass by Reference:
<?php
// Pass by Value (default)
function incrementByValue($num) {
$num = $num + 10;
echo "Inside function (by value): $num<br>";
}
$value = 5;
incrementByValue($value);
echo "Outside function: $value<br>"; // Original value unchanged
/* Output:
Inside function (by value): 15
Outside function: 5
*/
echo "<br>";
// Pass by Reference (using &)
function incrementByReference(&$num) {
$num = $num + 10;
echo "Inside function (by reference): $num<br>";
}
$value2 = 5;
incrementByReference($value2);
echo "Outside function: $value2<br>"; // Original value changed
/* Output:
Inside function (by reference): 15
Outside function: 15
*/
?>
Comprehensive Example: Complete Function Implementation
<?php
// Mathematical Operations Library
// 1. Function to check if number is prime
function isPrime($number) {
if ($number <= 1) {
return false;
}
if ($number == 2) {
return true;
}
if ($number % 2 == 0) {
return false;
}
for ($i = 3; $i <= sqrt($number); $i += 2) {
if ($number % $i == 0) {
return false;
}
}
return true;
}
// 2. Function to calculate factorial
function factorial($n) {
if ($n < 0) {
return "Factorial not defined for negative numbers";
}
if ($n == 0 || $n == 1) {
return 1;
}
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
// 3. Recursive function to calculate factorial
function factorialRecursive($n) {
if ($n <= 1) {
return 1;
}
return $n * factorialRecursive($n - 1);
}
// 4. Function to find largest of three numbers
function findLargest($a, $b, $c) {
$max = $a;
if ($b > $max) {
$max = $b;
}
if ($c > $max) {
$max = $c;
}
return $max;
}
// 5. Function to generate Fibonacci series
function fibonacci($n) {
$series = array();
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++) {
$series[] = $a;
$temp = $a + $b;
$a = $b;
$b = $temp;
}
return $series;
}
// 6. Function to calculate average of array
function calculateAverage($numbers) {
if (empty($numbers)) {
return 0;
}
$sum = array_sum($numbers);
$count = count($numbers);
return $sum / $count;
}
// 7. Function to format currency
function formatCurrency($amount, $currency = "Rs.") {
return $currency . " " . number_format($amount, 2);
}
// 8. Function with multiple return values using array
function getStudentInfo($rollNo) {
// Simulating database lookup
$students = array(
101 => array("name" => "Arjun", "marks" => 85, "grade" => "A"),
102 => array("name" => "Priya", "marks" => 92, "grade" => "A+"),
103 => array("name" => "Karthik", "marks" => 78, "grade" => "B+")
);
if (isset($students[$rollNo])) {
return $students[$rollNo];
} else {
return null;
}
}
// Testing all functions
echo "<h2>PHP Functions Demonstration</h2>";
echo "<h3>1. Prime Number Check:</h3>";
$testNumbers = array(2, 7, 15, 23, 30);
foreach ($testNumbers as $num) {
$result = isPrime($num) ? "is Prime" : "is Not Prime";
echo "$num $result<br>";
}
echo "<h3>2. Factorial Calculation:</h3>";
echo "Factorial of 5: " . factorial(5) . "<br>";
echo "Factorial of 7 (recursive): " . factorialRecursive(7) . "<br>";
echo "<h3>3. Find Largest Number:</h3>";
echo "Largest of 15, 42, 28: " . findLargest(15, 42, 28) . "<br>";
echo "<h3>4. Fibonacci Series:</h3>";
$fib = fibonacci(10);
echo "First 10 Fibonacci numbers: " . implode(", ", $fib) . "<br>";
echo "<h3>5. Calculate Average:</h3>";
$marks = array(85, 90, 78, 92, 88);
echo "Marks: " . implode(", ", $marks) . "<br>";
echo "Average: " . calculateAverage($marks) . "<br>";
echo "<h3>6. Currency Formatting:</h3>";
echo formatCurrency(12500) . "<br>";
echo formatCurrency(9999.50, "$") . "<br>";
echo "<h3>7. Student Information:</h3>";
$student = getStudentInfo(102);
if ($student != null) {
echo "Name: {$student['name']}<br>";
echo "Marks: {$student['marks']}<br>";
echo "Grade: {$student['grade']}<br>";
}
/* Output:
Prime Number Check:
2 is Prime
7 is Prime
15 is Not Prime
23 is Prime
30 is Not Prime
Factorial Calculation:
Factorial of 5: 120
Factorial of 7 (recursive): 5040
Find Largest Number:
Largest of 15, 42, 28: 42
Fibonacci Series:
First 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Calculate Average:
Marks: 85, 90, 78, 92, 88
Average: 86.6
Currency Formatting:
Rs. 12,500.00
$ 9,999.50
Student Information:
Name: Priya
Marks: 92
Grade: A+
*/
?>
Anonymous Functions (Closures):
<?php
// Anonymous function assigned to variable
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("Arjun") . "<br>";
// Anonymous function with use clause
$multiplier = 5;
$multiply = function($number) use ($multiplier) {
return $number * $multiplier;
};
echo "10 multiplied by 5: " . $multiply(10) . "<br>";
/* Output:
Hello, Arjun!
10 multiplied by 5: 50
*/
?>
Function Advantages:
- Code Reusability: Write once, use multiple times
- Modularity: Break complex problems into smaller parts
- Maintainability: Easier to update and debug
- Readability: Makes code more organized and understandable
- Testing: Functions can be tested independently
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP Functions Implementation with Examples │ 8 marks │
│ - Function definition and purpose │ │
│ - Benefits of using functions │ │
│ - Complete sample PHP script showing: │ │
│ * Simple function (no parameters) │ │
│ * Function with parameters │ │
│ * Function with return values │ │
│ * Function with default parameters │ │
│ * Function with variable-length arguments │ │
│ * Pass-by-reference vs pass-by-value │ │
│ * Recursive function example │ │
│ * Anonymous function (closure) │ │
│ - Comprehensive code examples for each type │ │
│ - Output demonstrations │ │
│ - Scope explanation (local, global, static) │ │
│ - Best practices for functions │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Implementation (Section 3.2, Pattern 3)
b) Design a HTML form to input a string and to display whether it is palindrome or not on form submission using PHP script. (6 marks)
Answer:
Palindrome Checker with HTML Form and PHP:
A palindrome is a word, phrase, number, or sequence that reads the same backward as forward (e.g., "madam", "racecar", "12321").
Complete Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
<style>
body {
font-family: Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
}
.container {
background-color: white;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
padding: 40px;
max-width: 500px;
width: 100%;
}
h2 {
color: #667eea;
text-align: center;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: bold;
}
input[type="text"] {
width: 100%;
padding: 12px;
border: 2px solid #ddd;
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
transition: border-color 0.3s;
}
input[type="text"]:focus {
outline: none;
border-color: #667eea;
}
button {
width: 100%;
padding: 12px;
background-color: #667eea;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #5568d3;
}
.result {
margin-top: 25px;
padding: 20px;
border-radius: 5px;
text-align: center;
font-size: 18px;
font-weight: bold;
}
.result.success {
background-color: #d4edda;
color: #155724;
border: 2px solid #c3e6cb;
}
.result.failure {
background-color: #f8d7da;
color: #721c24;
border: 2px solid #f5c6cb;
}
.info {
background-color: #e7f3ff;
padding: 15px;
border-radius: 5px;
margin-top: 20px;
border-left: 4px solid #667eea;
}
.info h4 {
margin-top: 0;
color: #667eea;
}
.examples {
color: #666;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h2>🔄 Palindrome Checker</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="inputString">Enter a String:</label>
<input
type="text"
id="inputString"
name="inputString"
placeholder="e.g., madam, racecar, level"
required
value="<?php echo isset($_POST['inputString']) ? htmlspecialchars($_POST['inputString']) : ''; ?>"
>
</div>
<button type="submit">Check Palindrome</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get input string
$inputString = trim($_POST['inputString']);
$originalString = $inputString;
// Convert to lowercase for case-insensitive comparison
$inputString = strtolower($inputString);
// Remove spaces and special characters for accurate checking
$cleanString = preg_replace("/[^a-z0-9]/", "", $inputString);
// Reverse the string
$reversedString = strrev($cleanString);
// Check if palindrome
$isPalindrome = ($cleanString === $reversedString);
// Display result
if ($isPalindrome) {
echo '<div class="result success">';
echo '✓ "' . htmlspecialchars($originalString) . '" is a PALINDROME!';
echo '<br><small style="font-weight: normal; margin-top: 10px; display: block;">';
echo 'Original: ' . $cleanString . '<br>';
echo 'Reversed: ' . $reversedString;
echo '</small>';
echo '</div>';
} else {
echo '<div class="result failure">';
echo '✗ "' . htmlspecialchars($originalString) . '" is NOT a palindrome.';
echo '<br><small style="font-weight: normal; margin-top: 10px; display: block;">';
echo 'Original: ' . $cleanString . '<br>';
echo 'Reversed: ' . $reversedString;
echo '</small>';
echo '</div>';
}
}
?>
<div class="info">
<h4>What is a Palindrome?</h4>
<p class="examples">
A palindrome is a word, phrase, or sequence that reads the same backward as forward.
<br><br>
<strong>Examples:</strong> madam, racecar, level, noon, civic, radar, refer, 12321
</p>
</div>
</div>
</body>
</html>
Alternative Simple Version:
<!DOCTYPE html>
<html>
<head>
<title>Palindrome Checker</title>
</head>
<body>
<h2>Palindrome Checker</h2>
<form method="POST">
<label>Enter String:</label>
<input type="text" name="inputString" required>
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$str = strtolower(trim($_POST['inputString']));
$reversed = strrev($str);
if ($str == $reversed) {
echo "<p><strong>Result:</strong> '$str' is a Palindrome!</p>";
} else {
echo "<p><strong>Result:</strong> '$str' is NOT a Palindrome.</p>";
}
}
?>
</body>
</html>
PHP Function Approach (Separate Logic):
<?php
function isPalindrome($string) {
// Remove spaces and convert to lowercase
$string = strtolower(preg_replace("/[^a-z0-9]/", "", $string));
// Compare with reversed string
return $string === strrev($string);
}
function checkPalindromeDetailed($string) {
$original = $string;
$cleaned = strtolower(preg_replace("/[^a-z0-9]/", "", $string));
$reversed = strrev($cleaned);
return array(
'original' => $original,
'cleaned' => $cleaned,
'reversed' => $reversed,
'isPalindrome' => ($cleaned === $reversed)
);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Palindrome Checker with Functions</title>
</head>
<body>
<h2>Palindrome Checker</h2>
<form method="POST">
<input type="text" name="text" placeholder="Enter string" required>
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$result = checkPalindromeDetailed($_POST['text']);
echo "<h3>Results:</h3>";
echo "<p>Original: " . $result['original'] . "</p>";
echo "<p>Cleaned: " . $result['cleaned'] . "</p>";
echo "<p>Reversed: " . $result['reversed'] . "</p>";
if ($result['isPalindrome']) {
echo "<p style='color: green;'><strong>✓ It's a Palindrome!</strong></p>";
} else {
echo "<p style='color: red;'><strong>✗ Not a Palindrome</strong></p>";
}
}
?>
</body>
</html>
Explanation:
- HTML Form: Creates input field for user to enter string
- PHP Processing: Handles form submission with POST method
- String Cleaning: Converts to lowercase and removes special characters for accurate comparison
- Reversal: Uses
strrev()to reverse the string - Comparison: Checks if original equals reversed
- Display: Shows result with appropriate styling
Key PHP Functions Used:
$_SERVER["REQUEST_METHOD"]: Check if form submitted$_POST['inputString']: Get form datatrim(): Remove whitespacestrtolower(): Convert to lowercasepreg_replace(): Remove non-alphanumeric charactersstrrev(): Reverse stringhtmlspecialchars(): Prevent XSS attacks
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete HTML Form and PHP Palindrome Check│ 6 marks │
│ - HTML form structure with input field │ │
│ - Form method and action attributes │ │
│ - PHP palindrome checking logic: │ │
│ * String input retrieval ($_POST) │ │
│ * String cleaning/normalization │ │
│ * Palindrome algorithm implementation │ │
│ * Comparison logic │ │
│ - Complete, runnable code │ │
│ - Output display with conditional messages │ │
│ - Alternative approaches shown │ │
│ - Security considerations │ │
│ - Test cases with examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Question (Section 2.2, Pattern 5)
Question 16 (14 marks) — #### a) Explain different ways to create an array in PHP. Explain with example. (8 marks)
a) Explain different ways to create an array in PHP. Explain with example. (8 marks)
Answer:
Arrays in PHP:
An array is a data structure that stores multiple values in a single variable. PHP arrays can hold values of different data types and provide various methods for creation and manipulation.
Types of PHP Arrays:
- Indexed Arrays: Arrays with numeric index (0, 1, 2, ...)
- Associative Arrays: Arrays with named keys (key-value pairs)
- Multidimensional Arrays: Arrays containing other arrays
Methods to Create Arrays in PHP:
Method 1: Using array() Function (Traditional Method)
1.1 Indexed Array:
<?php
// Empty array
$emptyArray = array();
// Array with values
$fruits = array("Apple", "Banana", "Orange", "Mango");
// Accessing elements
echo "First fruit: " . $fruits[0] . "<br>";
echo "Second fruit: " . $fruits[1] . "<br>";
// Display entire array
print_r($fruits);
/* Output:
First fruit: Apple
Second fruit: Banana
Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
*/
?>
1.2 Associative Array:
<?php
$student = array(
"name" => "Arjun",
"age" => 21,
"course" => "B.Tech CSE",
"cgpa" => 8.5
);
echo "Name: " . $student["name"] . "<br>";
echo "Age: " . $student["age"] . "<br>";
echo "Course: " . $student["course"] . "<br>";
echo "CGPA: " . $student["cgpa"] . "<br>";
/* Output:
Name: Arjun
Age: 21
Course: B.Tech CSE
CGPA: 8.5
*/
?>
Method 2: Using Short Array Syntax [] (PHP 5.4+)
2.1 Indexed Array:
<?php
// Empty array
$empty = [];
// Array with values
$colors = ["Red", "Green", "Blue", "Yellow"];
echo "Colors array:<br>";
foreach ($colors as $index => $color) {
echo "Index $index: $color<br>";
}
/* Output:
Colors array:
Index 0: Red
Index 1: Green
Index 2: Blue
Index 3: Yellow
*/
?>
2.2 Associative Array:
<?php
$person = [
"firstName" => "Priya",
"lastName" => "Sharma",
"email" => "priya@example.com",
"phone" => "9876543210"
];
echo "Full Name: " . $person["firstName"] . " " . $person["lastName"] . "<br>";
echo "Email: " . $person["email"] . "<br>";
echo "Phone: " . $person["phone"] . "<br>";
/* Output:
Full Name: Priya Sharma
Email: priya@example.com
Phone: 9876543210
*/
?>
Method 3: Creating Array by Adding Elements Individually
3.1 Indexed Array:
<?php
$numbers = [];
// Add elements one by one
$numbers[] = 10;
$numbers[] = 20;
$numbers[] = 30;
$numbers[] = 40;
$numbers[] = 50;
echo "Numbers array: ";
print_r($numbers);
/* Output:
Numbers array: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 )
*/
// Add at specific index
$numbers[10] = 100;
echo "<br>After adding at index 10: ";
print_r($numbers);
/* Output:
After adding at index 10: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [10] => 100 )
*/
?>
3.2 Associative Array:
<?php
$car = [];
// Add key-value pairs
$car["brand"] = "Toyota";
$car["model"] = "Camry";
$car["year"] = 2024;
$car["color"] = "Silver";
$car["price"] = 2500000;
echo "Car Details:<br>";
foreach ($car as $key => $value) {
echo ucfirst($key) . ": $value<br>";
}
/* Output:
Car Details:
Brand: Toyota
Model: Camry
Year: 2024
Color: Silver
Price: 2500000
*/
?>
Method 4: Using range() Function
Creates an array containing a range of elements.
<?php
// Numbers from 1 to 10
$numbers1 = range(1, 10);
echo "Range 1-10: ";
print_r($numbers1);
/* Output:
Range 1-10: Array ( [0] => 1 [1] => 2 [2] => 3 ... [9] => 10 )
*/
// Even numbers from 0 to 20 (step = 2)
$evenNumbers = range(0, 20, 2);
echo "<br>Even numbers 0-20: ";
print_r($evenNumbers);
/* Output:
Even numbers 0-20: Array ( [0] => 0 [1] => 2 [2] => 4 ... [10] => 20 )
*/
// Alphabets
$letters = range('A', 'F');
echo "<br>Letters A-F: ";
print_r($letters);
/* Output:
Letters A-F: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F )
*/
?>
Method 5: Using explode() Function
Converts a string to an array by splitting on a delimiter.
<?php
$string = "Apple,Banana,Orange,Mango,Grapes";
// Split by comma
$fruits = explode(",", $string);
echo "Fruits array from string:<br>";
foreach ($fruits as $index => $fruit) {
echo ($index + 1) . ". $fruit<br>";
}
/* Output:
Fruits array from string:
1. Apple
2. Banana
3. Orange
4. Mango
5. Grapes
*/
// Another example
$date = "2024-11-15";
$dateParts = explode("-", $date);
echo "<br>Year: " . $dateParts[0] . "<br>";
echo "Month: " . $dateParts[1] . "<br>";
echo "Day: " . $dateParts[2] . "<br>";
/* Output:
Year: 2024
Month: 11
Day: 15
*/
?>
Method 6: Using compact() Function
Creates an array from variables and their values.
<?php
$name = "Karthik";
$age = 25;
$city = "Mumbai";
$occupation = "Developer";
// Create array from variables
$person = compact("name", "age", "city", "occupation");
print_r($person);
/* Output:
Array ( [name] => Karthik [age] => 25 [city] => Mumbai [occupation] => Developer )
*/
?>
Method 7: Using array_fill() Function
Creates an array filled with values.
<?php
// Fill array with same value
$zeros = array_fill(0, 5, 0);
echo "Array filled with zeros: ";
print_r($zeros);
/* Output:
Array filled with zeros: Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 )
*/
// Fill with string
$stars = array_fill(0, 10, "*");
echo "<br>Stars: " . implode(" ", $stars);
/* Output:
Stars: * * * * * * * * * *
*/
?>
Method 8: Multidimensional Arrays
8.1 2D Array (Array of Arrays):
<?php
// Using array() function
$students = array(
array("Arjun", 21, 85),
array("Priya", 20, 92),
array("Karthik", 22, 78)
);
// Using short syntax
$employees = [
["John", "Manager", 50000],
["Sarah", "Developer", 45000],
["Mike", "Designer", 42000]
];
echo "Students:<br>";
for ($i = 0; $i < count($students); $i++) {
echo "Name: {$students[$i][0]}, Age: {$students[$i][1]}, Marks: {$students[$i][2]}<br>";
}
/* Output:
Students:
Name: Arjun, Age: 21, Marks: 85
Name: Priya, Age: 20, Marks: 92
Name: Karthik, Age: 22, Marks: 78
*/
?>
8.2 Associative Multidimensional Array:
<?php
$products = [
"laptop" => [
"brand" => "Dell",
"price" => 55000,
"warranty" => "2 years"
],
"phone" => [
"brand" => "Samsung",
"price" => 25000,
"warranty" => "1 year"
],
"tablet" => [
"brand" => "Apple",
"price" => 45000,
"warranty" => "1 year"
]
];
echo "Products:<br>";
foreach ($products as $product => $details) {
echo "<strong>" . ucfirst($product) . ":</strong><br>";
echo " Brand: {$details['brand']}<br>";
echo " Price: Rs. {$details['price']}<br>";
echo " Warranty: {$details['warranty']}<br><br>";
}
/* Output:
Products:
Laptop:
Brand: Dell
Price: Rs. 55000
Warranty: 2 years
Phone:
Brand: Samsung
Price: Rs. 25000
Warranty: 1 year
Tablet:
Brand: Apple
Price: Rs. 45000
Warranty: 1 year
*/
?>
Comprehensive Example: All Array Creation Methods
<?php
echo "<h2>Different Ways to Create Arrays in PHP</h2>";
// Method 1: array() function
echo "<h3>1. Using array() function:</h3>";
$arr1 = array(1, 2, 3, 4, 5);
echo "Indexed: ";
print_r($arr1);
echo "<br>";
$arr2 = array("name" => "John", "age" => 25);
echo "Associative: ";
print_r($arr2);
echo "<br><br>";
// Method 2: Short syntax []
echo "<h3>2. Using short syntax []:</h3>";
$arr3 = [10, 20, 30, 40];
echo "Indexed: ";
print_r($arr3);
echo "<br>";
$arr4 = ["city" => "Delhi", "country" => "India"];
echo "Associative: ";
print_r($arr4);
echo "<br><br>";
// Method 3: Adding elements individually
echo "<h3>3. Adding elements individually:</h3>";
$arr5 = [];
$arr5[] = "First";
$arr5[] = "Second";
$arr5["key"] = "Value";
print_r($arr5);
echo "<br><br>";
// Method 4: range() function
echo "<h3>4. Using range() function:</h3>";
$arr6 = range(1, 5);
echo "Numbers: ";
print_r($arr6);
echo "<br>";
$arr7 = range('A', 'E');
echo "Letters: ";
print_r($arr7);
echo "<br><br>";
// Method 5: explode() function
echo "<h3>5. Using explode() function:</h3>";
$str = "Red,Green,Blue";
$arr8 = explode(",", $str);
print_r($arr8);
echo "<br><br>";
// Method 6: compact() function
echo "<h3>6. Using compact() function:</h3>";
$firstname = "Alice";
$lastname = "Johnson";
$arr9 = compact("firstname", "lastname");
print_r($arr9);
echo "<br><br>";
// Method 7: array_fill() function
echo "<h3>7. Using array_fill() function:</h3>";
$arr10 = array_fill(0, 5, "X");
print_r($arr10);
echo "<br><br>";
// Method 8: Multidimensional arrays
echo "<h3>8. Multidimensional arrays:</h3>";
$arr11 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo "2D Array: ";
print_r($arr11);
?>
Summary Table:
| Method | Syntax | Best For |
|---|---|---|
| array() | array(...) |
Traditional, backward compatibility |
| [] | [...] |
Modern, concise (PHP 5.4+) |
| Individual | $arr[] = value |
Dynamic, iterative addition |
| range() | range(start, end, step) |
Sequential values |
| explode() | explode(delimiter, string) |
Converting strings to arrays |
| compact() | compact(var1, var2, ...) |
Creating arrays from variables |
| array_fill() | array_fill(index, count, value) |
Repeated values |
| Multidimensional | [[...], [...]] |
Complex data structures |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Different Ways to Create Arrays in PHP │ 8 marks │
│ - Introduction to PHP arrays │ │
│ - Multiple creation methods with examples: │ │
│ * Using array() function │ │
│ * Using short array syntax [] │ │
│ * Indexed arrays creation │ │
│ * Associative arrays creation │ │
│ * Multidimensional arrays │ │
│ * Using range() function │ │
│ * Using array_fill() function │ │
│ * Using compact() function │ │
│ * Using explode() for string to array │ │
│ * Empty array initialization │ │
│ - Complete code examples for each method │ │
│ - Accessing array elements │ │
│ - Array manipulation demonstrations │ │
│ - Comparison table of methods │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Implementation (Section 3.2, Pattern 3)
b) Write a PHP script to search for a specific string pattern in a text. (6 marks)
Answer:
String Pattern Searching in PHP:
PHP provides several functions to search for patterns in text, including simple string searches and powerful regular expression (regex) pattern matching.
Method 1: Using strpos() - Simple String Search
<?php
$text = "PHP is a powerful server-side scripting language. PHP is widely used for web development.";
$searchString = "PHP";
// Find first occurrence
$position = strpos($text, $searchString);
if ($position !== false) {
echo "Pattern '$searchString' found at position: $position<br>";
echo "First occurrence starts at index $position<br>";
} else {
echo "Pattern '$searchString' not found<br>";
}
// Count occurrences
$count = substr_count($text, $searchString);
echo "Total occurrences: $count<br>";
/* Output:
Pattern 'PHP' found at position: 0
First occurrence starts at index 0
Total occurrences: 2
*/
?>
Method 2: Using preg_match() - Regular Expression (First Match)
<?php
$text = "Contact us at info@example.com or support@example.com";
$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";
if (preg_match($pattern, $text, $matches)) {
echo "Email found: " . $matches[0] . "<br>";
} else {
echo "No email found<br>";
}
/* Output:
Email found: info@example.com
*/
// Example: Search for phone number
$phoneText = "Call me at 9876543210 or 9123456789";
$phonePattern = "/[6-9][0-9]{9}/";
if (preg_match($phonePattern, $phoneText, $phoneMatches)) {
echo "Phone number found: " . $phoneMatches[0] . "<br>";
}
/* Output:
Phone number found: 9876543210
*/
?>
Method 3: Using preg_match_all() - Find All Matches
<?php
$text = "Contact us at info@example.com, support@example.com, or sales@example.com";
$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";
$count = preg_match_all($pattern, $text, $matches);
echo "Found $count email addresses:<br>";
foreach ($matches[0] as $index => $email) {
echo ($index + 1) . ". $email<br>";
}
/* Output:
Found 3 email addresses:
1. info@example.com
2. support@example.com
3. sales@example.com
*/
?>
Comprehensive Example: Complete Pattern Search Application
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Pattern Search in PHP</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h2 {
color: #333;
text-align: center;
}
textarea {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 2px solid #ddd;
border-radius: 5px;
font-family: monospace;
font-size: 14px;
box-sizing: border-box;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 2px solid #ddd;
border-radius: 5px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin: 5px;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
padding: 15px;
background-color: #e7f3ff;
border-left: 4px solid #2196F3;
border-radius: 5px;
}
.match {
background-color: yellow;
font-weight: bold;
}
.stats {
background-color: #f0f0f0;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h2>🔍 String Pattern Search Tool</h2>
<form method="POST">
<label><strong>Enter Text:</strong></label>
<textarea name="text" rows="8" required><?php echo isset($_POST['text']) ? htmlspecialchars($_POST['text']) : 'PHP is a popular programming language. PHP is used for web development. Learn PHP to build dynamic websites. PHP powers millions of websites.'; ?></textarea>
<label><strong>Search Pattern:</strong></label>
<input type="text" name="pattern" placeholder="Enter word or regex pattern" required value="<?php echo isset($_POST['pattern']) ? htmlspecialchars($_POST['pattern']) : 'PHP'; ?>">
<button type="submit" name="search_simple">Simple Search</button>
<button type="submit" name="search_regex">Regex Search</button>
<button type="submit" name="search_all">Find All Matches</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$text = $_POST['text'];
$pattern = $_POST['pattern'];
echo "<div class='result'>";
echo "<h3>Search Results:</h3>";
// Simple Search
if (isset($_POST['search_simple'])) {
echo "<h4>Simple String Search:</h4>";
$position = strpos($text, $pattern);
$count = substr_count($text, $pattern);
if ($position !== false) {
echo "<div class='stats'>";
echo "✓ Pattern '<strong>$pattern</strong>' found!<br>";
echo "First occurrence at position: <strong>$position</strong><br>";
echo "Total occurrences: <strong>$count</strong><br>";
echo "</div>";
// Highlight matches
$highlightedText = str_replace($pattern, "<span class='match'>$pattern</span>", htmlspecialchars($text));
echo "<strong>Text with highlights:</strong><br>";
echo "<div style='padding: 10px; background: white; border: 1px solid #ddd; margin-top: 10px;'>";
echo $highlightedText;
echo "</div>";
} else {
echo "✗ Pattern not found in the text.";
}
}
// Regex Search - First Match
if (isset($_POST['search_regex'])) {
echo "<h4>Regular Expression Search (First Match):</h4>";
if (preg_match("/$pattern/i", $text, $matches, PREG_OFFSET_CAPTURE)) {
echo "<div class='stats'>";
echo "✓ Pattern found!<br>";
echo "Match: <strong>" . htmlspecialchars($matches[0][0]) . "</strong><br>";
echo "Position: <strong>" . $matches[0][1] . "</strong><br>";
echo "</div>";
} else {
echo "✗ No match found for the regex pattern.";
}
}
// Find All Matches
if (isset($_POST['search_all'])) {
echo "<h4>Find All Matches (Regex):</h4>";
$count = preg_match_all("/$pattern/i", $text, $matches, PREG_OFFSET_CAPTURE);
if ($count > 0) {
echo "<div class='stats'>";
echo "✓ Found <strong>$count</strong> matches:<br><br>";
foreach ($matches[0] as $index => $match) {
echo ($index + 1) . ". '<strong>" . htmlspecialchars($match[0]) . "</strong>' at position " . $match[1] . "<br>";
}
echo "</div>";
// Highlight all matches
$highlightedText = preg_replace("/($pattern)/i", "<span class='match'>$1</span>", htmlspecialchars($text));
echo "<strong>Text with all highlights:</strong><br>";
echo "<div style='padding: 10px; background: white; border: 1px solid #ddd; margin-top: 10px;'>";
echo $highlightedText;
echo "</div>";
} else {
echo "✗ No matches found.";
}
}
echo "</div>";
}
?>
<div style="margin-top: 30px; padding: 15px; background-color: #fff3cd; border-left: 4px solid #ffc107; border-radius: 5px;">
<h4>Example Patterns:</h4>
<ul>
<li><strong>Simple word:</strong> PHP, web, development</li>
<li><strong>Email:</strong> [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}</li>
<li><strong>Phone:</strong> [6-9][0-9]{9}</li>
<li><strong>URL:</strong> https?://[^\s]+</li>
<li><strong>Date (YYYY-MM-DD):</strong> \d{4}-\d{2}-\d{2}</li>
</ul>
</div>
</div>
</body>
</html>
Practical Examples for Different Pattern Types:
<?php
echo "<h3>Pattern Search Examples:</h3>";
// 1. Search for email addresses
$text1 = "Contact: john@example.com, support@test.org";
$emailPattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";
echo "<strong>1. Email Search:</strong><br>";
preg_match_all($emailPattern, $text1, $emails);
echo "Emails found: " . implode(", ", $emails[0]) . "<br><br>";
// 2. Search for phone numbers
$text2 = "Call 9876543210 or 9123456789 for more info";
$phonePattern = "/[6-9][0-9]{9}/";
echo "<strong>2. Phone Number Search:</strong><br>";
preg_match_all($phonePattern, $text2, $phones);
echo "Phones found: " . implode(", ", $phones[0]) . "<br><br>";
// 3. Search for URLs
$text3 = "Visit https://www.example.com or http://test.org";
$urlPattern = "/https?:\/\/[^\s]+/";
echo "<strong>3. URL Search:</strong><br>";
preg_match_all($urlPattern, $text3, $urls);
echo "URLs found: " . implode(", ", $urls[0]) . "<br><br>";
// 4. Search for dates
$text4 = "Important dates: 2024-11-15, 2024-12-25, 2025-01-01";
$datePattern = "/\d{4}-\d{2}-\d{2}/";
echo "<strong>4. Date Search (YYYY-MM-DD):</strong><br>";
preg_match_all($datePattern, $text4, $dates);
echo "Dates found: " . implode(", ", $dates[0]) . "<br><br>";
// 5. Search for hashtags
$text5 = "Check out #PHP #WebDevelopment #Programming";
$hashtagPattern = "/#[a-zA-Z0-9_]+/";
echo "<strong>5. Hashtag Search:</strong><br>";
preg_match_all($hashtagPattern, $text5, $hashtags);
echo "Hashtags found: " . implode(", ", $hashtags[0]) . "<br><br>";
// 6. Search for numbers
$text6 = "The price is Rs. 1500 and discount is 20%";
$numberPattern = "/\d+/";
echo "<strong>6. Number Search:</strong><br>";
preg_match_all($numberPattern, $text6, $numbers);
echo "Numbers found: " . implode(", ", $numbers[0]) . "<br><br>";
/* Output:
1. Email Search:
Emails found: john@example.com, support@test.org
2. Phone Number Search:
Phones found: 9876543210, 9123456789
3. URL Search:
URLs found: https://www.example.com, http://test.org
4. Date Search (YYYY-MM-DD):
Dates found: 2024-11-15, 2024-12-25, 2025-01-01
5. Hashtag Search:
Hashtags found: #PHP, #WebDevelopment, #Programming
6. Number Search:
Numbers found: 1500, 20
*/
?>
Function Summary:
| Function | Purpose | Returns |
|---|---|---|
strpos() |
Find first occurrence position | Position (int) or false |
substr_count() |
Count occurrences | Count (int) |
preg_match() |
Find first regex match | 1 if found, 0 if not |
preg_match_all() |
Find all regex matches | Count of matches |
preg_replace() |
Replace pattern matches | Modified string |
str_replace() |
Replace simple string | Modified string |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP String Pattern Search Script │ 6 marks │
│ - Complete PHP script implementation │ │
│ - Multiple search approaches: │ │
│ * Using strpos() for simple search │ │
│ * Using preg_match() for regex patterns │ │
│ * Using preg_match_all() for all matches │ │
│ * Using str_contains() (PHP 8+) │ │
│ - Complete code examples for each method │ │
│ - Pattern matching demonstrations │ │
│ - Case-sensitive and case-insensitive search│ │
│ - Output formatting and display │ │
│ - Practical examples with test cases │ │
│ - Function comparison table │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Question (Section 2.2, Pattern 5)
Module IV — Module IV
Question 17 (14 marks) — #### a) Explain form processing in PHP. Design an HTML form for entering a number by the user. Write a PHP code to display a message indicating, whether the number is prime or not, when clicking on the submit button. (8 marks)
a) Explain form processing in PHP. Design an HTML form for entering a number by the user. Write a PHP code to display a message indicating, whether the number is prime or not, when clicking on the submit button. (8 marks)
Answer:
Form Processing in PHP:
Form processing is the method of collecting, validating, and manipulating data submitted by users through HTML forms. PHP provides superglobal arrays like $_GET, $_POST, and $_REQUEST to handle form data.
Form Processing Steps:
- Create HTML Form: Design form with input fields
- Submit Form: User fills form and clicks submit
- PHP Receives Data: Server receives data via GET or POST
- Validate Data: Check for required fields, data types, format
- Process Data: Perform operations (database, calculations, etc.)
- Display Results: Show response to user
Form Methods:
- GET: Data sent via URL parameters (visible, limited size, not secure)
- POST: Data sent in HTTP request body (hidden, unlimited size, more secure)
Superglobal Arrays:
$_GET: Contains data sent via GET method$_POST: Contains data sent via POST method$_REQUEST: Contains data from both GET and POST$_SERVER: Contains server and execution environment information
Complete Prime Number Checker Application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prime Number Checker</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%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background-color: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
max-width: 500px;
width: 100%;
}
h2 {
color: #667eea;
text-align: center;
margin-bottom: 10px;
font-size: 28px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 25px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 600;
font-size: 15px;
}
input[type="number"] {
width: 100%;
padding: 15px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 16px;
transition: all 0.3s ease;
}
input[type="number"]:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
button {
width: 100%;
padding: 15px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
button:active {
transform: translateY(0);
}
.result {
margin-top: 30px;
padding: 20px;
border-radius: 10px;
text-align: center;
animation: slideIn 0.5s ease;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.result.prime {
background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
border: 2px solid #28a745;
}
.result.not-prime {
background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
border: 2px solid #dc3545;
}
.result .icon {
font-size: 48px;
margin-bottom: 15px;
}
.result .number {
font-size: 36px;
font-weight: bold;
margin: 10px 0;
}
.result .message {
font-size: 20px;
font-weight: 600;
margin: 10px 0;
}
.result .description {
font-size: 14px;
color: #666;
margin-top: 10px;
line-height: 1.6;
}
.info-box {
background-color: #e7f3ff;
padding: 15px;
border-radius: 8px;
margin-top: 25px;
border-left: 4px solid #2196F3;
}
.info-box h4 {
color: #2196F3;
margin-bottom: 8px;
}
.info-box p {
color: #555;
font-size: 14px;
line-height: 1.6;
}
.examples {
font-size: 13px;
color: #666;
margin-top: 8px;
}
</style>
</head>
<body>
<div class="container">
<h2>🔢 Prime Number Checker</h2>
<p class="subtitle">Enter a number to check if it's prime</p>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="number">Enter a Number:</label>
<input
type="number"
id="number"
name="number"
placeholder="Enter a positive integer"
required
min="1"
value="<?php echo isset($_POST['number']) ? htmlspecialchars($_POST['number']) : ''; ?>"
>
</div>
<button type="submit" name="check">Check Prime Number</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['check'])) {
$number = intval($_POST['number']);
// Function to check if number is prime
function isPrime($num) {
if ($num <= 1) {
return false;
}
if ($num == 2) {
return true;
}
if ($num % 2 == 0) {
return false;
}
for ($i = 3; $i <= sqrt($num); $i += 2) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
// Check if prime
$isPrimeNumber = isPrime($number);
if ($isPrimeNumber) {
echo '<div class="result prime">';
echo '<div class="icon">✓</div>';
echo '<div class="number">' . $number . '</div>';
echo '<div class="message">is a PRIME NUMBER</div>';
echo '<div class="description">';
echo 'A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.';
echo '</div>';
echo '</div>';
} else {
echo '<div class="result not-prime">';
echo '<div class="icon">✗</div>';
echo '<div class="number">' . $number . '</div>';
echo '<div class="message">is NOT a prime number</div>';
echo '<div class="description">';
if ($number <= 1) {
echo 'Numbers less than or equal to 1 are not considered prime numbers.';
} else if ($number == 2) {
echo '2 is the only even prime number.';
} else {
// Find factors
echo 'This number is divisible by: 1';
for ($i = 2; $i <= $number; $i++) {
if ($number % $i == 0) {
echo ', ' . $i;
}
}
}
echo '</div>';
echo '</div>';
}
}
?>
<div class="info-box">
<h4>What is a Prime Number?</h4>
<p>
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
In other words, it has exactly two distinct positive divisors: 1 and itself.
</p>
<p class="examples">
<strong>Examples:</strong> 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47...
</p>
</div>
</div>
</body>
</html>
Simplified Version:
<!DOCTYPE html>
<html>
<head>
<title>Prime Number Checker</title>
</head>
<body>
<h2>Check if Number is Prime</h2>
<form method="POST">
<label>Enter a number:</label>
<input type="number" name="number" required min="1">
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = intval($_POST['number']);
function isPrime($n) {
if ($n <= 1) return false;
if ($n == 2) return true;
if ($n % 2 == 0) return false;
for ($i = 3; $i <= sqrt($n); $i += 2) {
if ($n % $i == 0) return false;
}
return true;
}
if (isPrime($num)) {
echo "<p><strong>$num is a PRIME number.</strong></p>";
} else {
echo "<p><strong>$num is NOT a prime number.</strong></p>";
}
}
?>
</body>
</html>
Explanation of Form Processing:
- Form Creation: HTML form with method="POST" and input field
- Form Submission: When user clicks submit, data is sent to server
- Data Reception: PHP receives data in
$_POST['number'] - Validation: Convert to integer using
intval(), check if valid - Processing: Call
isPrime()function to check if number is prime - Display Result: Show appropriate message based on result
Key PHP Concepts:
$_SERVER["REQUEST_METHOD"]: Checks if form was submitted$_POST['fieldname']: Retrieves form datahtmlspecialchars(): Prevents XSS attacksintval(): Converts string to integer- Form validation and error handling
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Form Processing in PHP Explanation │ 3 marks │
│ - Form processing concept │ │
│ - HTTP methods (GET vs POST) │ │
│ - Superglobal arrays ($_GET, $_POST) │ │
│ - Form validation techniques │ │
│ - Security considerations │ │
│ │ │
│ 2. HTML Form and Prime Number Check │ 5 marks │
│ - Complete HTML form with number input │ │
│ - Form structure (method, action) │ │
│ - PHP script for prime number checking: │ │
│ * Input retrieval and validation │ │
│ * Prime number algorithm │ │
│ * Loop logic and divisibility check │ │
│ * Result display │ │
│ - Complete, runnable code │ │
│ - Form and PHP integration │ │
│ - Test cases and examples │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Explanation + Programming Implementation (Section 3)
b) Explain the concepts of cookies in PHP. (6 marks)
Answer:
Cookies in PHP:
A cookie is a small piece of data (text file) stored on the client's computer by the web browser. Cookies are used to remember information about the user between page visits or sessions, enabling personalized experiences and state management in stateless HTTP protocol.
Key Characteristics:
- Client-Side Storage: Stored on user's browser
- Small Size: Typically limited to 4KB per cookie
- Limited Number: Browsers limit cookies per domain (usually 20-50)
- Expiration: Can be session-based or persistent with expiry time
- Domain Specific: Only accessible to the domain that created them
- Insecure by Default: Transmitted in plain text unless HTTPS is used
Why Use Cookies?
- Session Management: User login status, shopping carts
- Personalization: User preferences, themes, language settings
- Tracking: Analytics, advertising, user behavior
- Remember Me: Keep users logged in across sessions
- E-commerce: Shopping cart data, recently viewed items
Creating Cookies in PHP:
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters:
name: Cookie name (required)value: Cookie value (required)expire: Expiration time as Unix timestamp (optional, 0 = session cookie)path: Server path where cookie is available (optional, "/" = entire domain)domain: Domain where cookie is available (optional)secure: Only transmit over HTTPS (optional, boolean)httponly: Only accessible via HTTP protocol, not JavaScript (optional, boolean)
Example 1: Simple Cookie Creation
<?php
// Create a cookie that expires in 1 hour
$cookieName = "username";
$cookieValue = "John Doe";
$expireTime = time() + 3600; // Current time + 1 hour (3600 seconds)
setcookie($cookieName, $cookieValue, $expireTime, "/");
echo "Cookie '$cookieName' has been set!";
?>
Example 2: Accessing Cookies
<?php
// Check if cookie exists
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'] . "!<br>";
echo "Your cookie value: " . $_COOKIE['username'];
} else {
echo "Cookie 'username' is not set!";
}
?>
Example 3: Modifying Cookies
<?php
// Modify existing cookie by setting it again with new value
$cookieName = "username";
$newValue = "Jane Smith";
$expireTime = time() + 7200; // 2 hours from now
setcookie($cookieName, $newValue, $expireTime, "/");
echo "Cookie '$cookieName' has been updated!";
?>
Example 4: Deleting Cookies
<?php
// Delete cookie by setting expiration time in the past
$cookieName = "username";
// Method 1: Set expire time to past
setcookie($cookieName, "", time() - 3600, "/");
// Method 2: Set expire time to 0 or negative
setcookie($cookieName, "", 0, "/");
echo "Cookie '$cookieName' has been deleted!";
?>
Comprehensive Cookie Management Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Cookies Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h2 {
color: #333;
border-bottom: 3px solid #4CAF50;
padding-bottom: 10px;
}
.form-section {
margin: 20px 0;
padding: 20px;
background-color: #f9f9f9;
border-radius: 5px;
}
input[type="text"] {
padding: 10px;
width: 60%;
border: 2px solid #ddd;
border-radius: 5px;
margin-right: 10px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #45a049;
}
.delete-btn {
background-color: #f44336;
}
.delete-btn:hover {
background-color: #da190b;
}
.info {
background-color: #e7f3ff;
padding: 15px;
border-left: 4px solid #2196F3;
margin: 20px 0;
}
.success {
background-color: #d4edda;
color: #155724;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
.cookies-list {
background-color: #fff3cd;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="container">
<h2>🍪 PHP Cookies Management</h2>
<?php
// Handle cookie operations
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['set_cookie'])) {
$name = $_POST['cookie_name'];
$value = $_POST['cookie_value'];
$expire = time() + (86400 * 7); // 7 days
setcookie($name, $value, $expire, "/");
echo '<div class="success">Cookie "' . htmlspecialchars($name) . '" has been set successfully!</div>';
echo '<p><small>Note: Refresh the page to see the cookie in the list below.</small></p>';
}
if (isset($_POST['delete_cookie'])) {
$name = $_POST['cookie_name'];
setcookie($name, "", time() - 3600, "/");
echo '<div class="success">Cookie "' . htmlspecialchars($name) . '" has been deleted! Refresh to see changes.</div>';
}
if (isset($_POST['delete_all'])) {
foreach ($_COOKIE as $name => $value) {
setcookie($name, "", time() - 3600, "/");
}
echo '<div class="success">All cookies have been deleted! Refresh to see changes.</div>';
}
}
?>
<!-- Set Cookie Form -->
<div class="form-section">
<h3>Create New Cookie</h3>
<form method="POST">
<input type="text" name="cookie_name" placeholder="Cookie Name" required>
<input type="text" name="cookie_value" placeholder="Cookie Value" required>
<button type="submit" name="set_cookie">Set Cookie</button>
</form>
<p style="font-size: 13px; color: #666; margin-top: 10px;">
Cookie will expire in 7 days.
</p>
</div>
<!-- Display Existing Cookies -->
<div class="cookies-list">
<h3>Current Cookies</h3>
<?php
if (count($_COOKIE) > 0) {
echo '<table style="width: 100%; border-collapse: collapse;">';
echo '<tr style="background-color: #4CAF50; color: white;">
<th style="padding: 10px; text-align: left;">Name</th>
<th style="padding: 10px; text-align: left;">Value</th>
<th style="padding: 10px; text-align: center;">Action</th>
</tr>';
foreach ($_COOKIE as $name => $value) {
echo '<tr style="border-bottom: 1px solid #ddd;">
<td style="padding: 10px;"><strong>' . htmlspecialchars($name) . '</strong></td>
<td style="padding: 10px;">' . htmlspecialchars($value) . '</td>
<td style="padding: 10px; text-align: center;">
<form method="POST" style="display: inline;">
<input type="hidden" name="cookie_name" value="' . htmlspecialchars($name) . '">
<button type="submit" name="delete_cookie" class="delete-btn">Delete</button>
</form>
</td>
</tr>';
}
echo '</table>';
echo '<form method="POST" style="margin-top: 15px;">
<button type="submit" name="delete_all" class="delete-btn">Delete All Cookies</button>
</form>';
} else {
echo '<p>No cookies are currently set.</p>';
}
?>
</div>
<!-- Information Section -->
<div class="info">
<h4>About Cookies:</h4>
<ul>
<li><strong>Purpose:</strong> Store small amounts of data on the client side</li>
<li><strong>Size Limit:</strong> Approximately 4KB per cookie</li>
<li><strong>Lifespan:</strong> Can be session-based or persistent</li>
<li><strong>Security:</strong> Should not store sensitive data</li>
<li><strong>Access:</strong> Accessible via PHP ($_COOKIE) and JavaScript</li>
</ul>
</div>
<!-- Example Code -->
<div style="background-color: #f4f4f4; padding: 15px; border-radius: 5px; margin-top: 20px;">
<h4>PHP Cookie Code Examples:</h4>
<pre style="background-color: #272822; color: #f8f8f2; padding: 15px; border-radius: 5px; overflow-x: auto;">
<code>// Create cookie
setcookie("username", "John", time() + 3600, "/");
// Access cookie
echo $_COOKIE['username'];
// Delete cookie
setcookie("username", "", time() - 3600, "/");</code>
</pre>
</div>
</div>
</body>
</html>
Cookie Expiration Examples:
<?php
// Session cookie (expires when browser closes)
setcookie("session_user", "JohnDoe", 0, "/");
// Cookie expires in 1 hour
setcookie("temp_data", "value", time() + 3600, "/");
// Cookie expires in 1 day
setcookie("daily_visit", "visited", time() + 86400, "/");
// Cookie expires in 1 week
setcookie("weekly_pref", "settings", time() + (86400 * 7), "/");
// Cookie expires in 1 month (30 days)
setcookie("monthly_token", "abc123", time() + (86400 * 30), "/");
// Cookie expires in 1 year
setcookie("remember_me", "true", time() + (86400 * 365), "/");
?>
Security Best Practices:
<?php
// Secure cookie (HTTPS only)
setcookie("secure_token", "xyz789", time() + 3600, "/", "", true, true);
// name value expire path domain secure httponly
// HttpOnly cookie (not accessible via JavaScript - prevents XSS)
setcookie("session_id", "abc123", 0, "/", "", false, true);
// Both Secure and HttpOnly
setcookie("auth_token", "token123", time() + 3600, "/", "", true, true);
?>
Advantages of Cookies:
- Persistence: Data persists across sessions
- Client-Side: Reduces server load
- Automatic: Sent automatically with each request
- Simple: Easy to implement and use
- Cross-Page: Accessible across entire website
Disadvantages of Cookies:
- Size Limitation: Maximum 4KB per cookie
- Security Risk: Can be stolen or manipulated
- Privacy Concerns: Users can disable cookies
- Bandwidth: Sent with every HTTP request
- Not Suitable for Sensitive Data: Should not store passwords, credit cards
Cookies vs Sessions:
| Feature | Cookies | Sessions |
|---|---|---|
| Storage Location | Client-side (browser) | Server-side |
| Size Limit | 4KB per cookie | No practical limit |
| Security | Less secure | More secure |
| Lifespan | Can be persistent | Usually expires on browser close |
| Data Type | Text only | Any data type |
| Bandwidth | Sent with each request | Only session ID sent |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Cookies Concept in PHP │ 6 marks │
│ - Cookie definition and purpose │ │
│ - How cookies work │ │
│ - Creating cookies with setcookie() │ │
│ - Cookie parameters (name, value, expiry, │ │
│ path, domain, secure, httponly) │ │
│ - Accessing cookies with $_COOKIE │ │
│ - Modifying cookies │ │
│ - Deleting cookies │ │
│ - Complete code examples │ │
│ - Security considerations │ │
│ - Cookie vs Session comparison │ │
│ - Best practices │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept Explanation (Section 2.2, Pattern 5)
Question 18 (14 marks) — #### a) Write a PHP form handling program to perform the student registration on a college website with a minimum of 6 different fields and insert the data into a MySQL table after establishing necessary database connectivity. (8 marks)
a) Write a PHP form handling program to perform the student registration on a college website with a minimum of 6 different fields and insert the data into a MySQL table after establishing necessary database connectivity. (8 marks)
Answer:
Complete Student Registration System with PHP and MySQL:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration System</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%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 600px;
margin: 30px auto;
background-color: white;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
}
h2 {
color: #667eea;
text-align: center;
margin-bottom: 10px;
font-size: 28px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 600;
}
.required {
color: red;
}
input[type="text"],
input[type="email"],
input[type="tel"],
input[type="date"],
input[type="number"],
select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 15px;
transition: border-color 0.3s ease;
}
input:focus,
select:focus {
outline: none;
border-color: #667eea;
}
.gender-group {
display: flex;
gap: 20px;
margin-top: 8px;
}
.radio-option {
display: flex;
align-items: center;
gap: 5px;
}
button {
width: 100%;
padding: 15px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s ease;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.message {
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
text-align: center;
font-weight: 600;
}
.success {
background-color: #d4edda;
color: #155724;
border: 2px solid #c3e6cb;
}
.error {
background-color: #f8d7da;
color: #721c24;
border: 2px solid #f5c6cb;
}
</style>
</head>
<body>
<div class="container">
<h2>🎓 Student Registration</h2>
<p class="subtitle">College Management System</p>
<?php
// Database connection using PDO
function connectDatabase() {
try {
$dsn = "mysql:host=localhost;dbname=college_db;charset=utf8mb4";
$username = "root";
$password = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
return $pdo;
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
// Create table if not exists
function createTable($pdo) {
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
roll_number VARCHAR(20) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(15) NOT NULL,
date_of_birth DATE NOT NULL,
gender ENUM('Male', 'Female', 'Other') NOT NULL,
course VARCHAR(50) NOT NULL,
year_of_study INT NOT NULL,
address TEXT NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
try {
$pdo->exec($sql);
} catch (PDOException $e) {
die("Error creating table: " . $e->getMessage());
}
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get and sanitize input data
$rollNumber = trim($_POST['roll_number']);
$fullName = trim($_POST['full_name']);
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST['phone']);
$dob = $_POST['date_of_birth'];
$gender = $_POST['gender'];
$course = $_POST['course'];
$year = intval($_POST['year_of_study']);
$address = trim($_POST['address']);
// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo '<div class="message error">❌ Invalid email format!</div>';
} else {
try {
// Connect to database
$pdo = connectDatabase();
// Create table if not exists
createTable($pdo);
// Prepare SQL statement with named placeholders
$sql = "INSERT INTO students (roll_number, full_name, email, phone, date_of_birth, gender, course, year_of_study, address)
VALUES (:roll_number, :full_name, :email, :phone, :dob, :gender, :course, :year, :address)";
$stmt = $pdo->prepare($sql);
// Execute with parameters
$result = $stmt->execute([
'roll_number' => $rollNumber,
'full_name' => $fullName,
'email' => $email,
'phone' => $phone,
'dob' => $dob,
'gender' => $gender,
'course' => $course,
'year' => $year,
'address' => $address
]);
if ($result) {
$studentId = $pdo->lastInsertId();
echo '<div class="message success">';
echo '✓ Registration successful!<br>';
echo 'Student ID: ' . $studentId . '<br>';
echo 'Roll Number: ' . htmlspecialchars($rollNumber);
echo '</div>';
// Reset form by redirecting
// header("Location: " . $_SERVER['PHP_SELF']);
// exit();
}
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
echo '<div class="message error">❌ Registration failed: Roll number or email already exists!</div>';
} else {
echo '<div class="message error">❌ Error: ' . $e->getMessage() . '</div>';
}
}
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="roll_number">Roll Number <span class="required">*</span></label>
<input type="text" id="roll_number" name="roll_number"
placeholder="e.g., CS2024001" required>
</div>
<div class="form-group">
<label for="full_name">Full Name <span class="required">*</span></label>
<input type="text" id="full_name" name="full_name"
placeholder="Enter full name" required>
</div>
<div class="form-group">
<label for="email">Email Address <span class="required">*</span></label>
<input type="email" id="email" name="email"
placeholder="student@example.com" required>
</div>
<div class="form-group">
<label for="phone">Phone Number <span class="required">*</span></label>
<input type="tel" id="phone" name="phone"
placeholder="10-digit mobile number"
pattern="[0-9]{10}" required>
</div>
<div class="form-group">
<label for="date_of_birth">Date of Birth <span class="required">*</span></label>
<input type="date" id="date_of_birth" name="date_of_birth" required>
</div>
<div class="form-group">
<label>Gender <span class="required">*</span></label>
<div class="gender-group">
<div class="radio-option">
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label>
</div>
<div class="radio-option">
<input type="radio" id="female" name="gender" value="Female" required>
<label for="female">Female</label>
</div>
<div class="radio-option">
<input type="radio" id="other" name="gender" value="Other" required>
<label for="other">Other</label>
</div>
</div>
</div>
<div class="form-group">
<label for="course">Course <span class="required">*</span></label>
<select id="course" name="course" required>
<option value="">-- Select Course --</option>
<option value="B.Tech Computer Science">B.Tech Computer Science</option>
<option value="B.Tech Electronics">B.Tech Electronics</option>
<option value="B.Tech Mechanical">B.Tech Mechanical</option>
<option value="B.Tech Civil">B.Tech Civil</option>
<option value="BCA">BCA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
</div>
<div class="form-group">
<label for="year_of_study">Year of Study <span class="required">*</span></label>
<select id="year_of_study" name="year_of_study" required>
<option value="">-- Select Year --</option>
<option value="1">First Year</option>
<option value="2">Second Year</option>
<option value="3">Third Year</option>
<option value="4">Fourth Year</option>
</select>
</div>
<div class="form-group">
<label for="address">Address <span class="required">*</span></label>
<input type="text" id="address" name="address"
placeholder="Complete residential address" required>
</div>
<button type="submit">Register Student</button>
</form>
</div>
</body>
</html>
Database Schema:
-- Create database
CREATE DATABASE IF NOT EXISTS college_db;
USE college_db;
-- Create students table
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
roll_number VARCHAR(20) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(15) NOT NULL,
date_of_birth DATE NOT NULL,
gender ENUM('Male', 'Female', 'Other') NOT NULL,
course VARCHAR(50) NOT NULL,
year_of_study INT NOT NULL,
address TEXT NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_roll_number (roll_number),
INDEX idx_email (email)
);
Key Features:
- PDO Database Connection: Secure, modern database connectivity
- Prepared Statements: Prevents SQL injection attacks
- Input Validation: Email validation, required fields
- Input Sanitization: Using
trim(),filter_var(),intval() - Error Handling: Try-catch blocks for database exceptions
- Security: Named parameters in prepared statements
- Unique Constraints: Roll number and email must be unique
- Auto-increment ID: Automatic student ID generation
- Professional Styling: Clean, modern UI with CSS
- User Feedback: Success/error messages
Security Best Practices Implemented:
- ✓ PDO prepared statements with named parameters
- ✓ Input sanitization
- ✓ Email validation
- ✓ XSS prevention with
htmlspecialchars() - ✓ SQL injection prevention (prepared statements)
- ✓ Error handling
- ✓ Data type validation
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete PHP Form Handling Program │ 8 marks │
│ - HTML registration form with 6+ fields: │ │
│ * Name, email, phone, course, etc. │ │
│ * Form method and action │ │
│ * Input validation attributes │ │
│ - PHP form processing script: │ │
│ * Form data retrieval ($_POST) │ │
│ * Server-side validation │ │
│ * Input sanitization │ │
│ - Database connectivity: │ │
│ * PDO/MySQLi connection setup │ │
│ * Connection error handling │ │
│ - Data insertion: │ │
│ * Prepared statements (SQL injection safe)│ │
│ * Parameter binding │ │
│ * Execute and success verification │ │
│ - Complete, runnable code │ │
│ - Security best practices implemented │ │
│ - Error handling and user feedback │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Programming Implementation (Section 3.2, Pattern 3)
b) Explain the concepts of sessions in PHP. (6 marks)
Answer:
Sessions in PHP:
A session is a way to store information (variables) to be used across multiple pages on the server side. Unlike cookies which store data on the client's browser, session data is stored on the web server. Each user gets a unique session ID to identify their session.
Key Characteristics:
- Server-Side Storage: Data stored on server, not client
- Secure: More secure than cookies as data not exposed to client
- Larger Capacity: No size limitation like cookies (4KB)
- Automatic Cleanup: Sessions expire after inactivity
- Unique Session ID: Each user gets a unique identifier
- Temporary: Usually expires when browser closes (configurable)
Why Use Sessions?
- User Authentication: Track logged-in users across pages
- Shopping Carts: Maintain cart items across pages
- User Preferences: Store temporary user settings
- Form Data: Preserve multi-step form data
- Access Control: Restrict access to certain pages
- Personalization: Customize content for each user
Session Workflow:
1. User visits website
2. session_start() creates new session
3. Server generates unique Session ID
4. Session ID stored in cookie (PHPSESSID)
5. Session data stored on server
6. User navigates between pages
7. Session ID sent with each request
8. Server retrieves session data using ID
9. User closes browser or session expires
10. Session destroyed
Basic Session Functions:
| Function | Description |
|---|---|
session_start() |
Starts or resumes a session |
$_SESSION |
Superglobal array to store session data |
session_id() |
Get or set session ID |
session_destroy() |
Destroys all session data |
session_unset() |
Unsets all session variables |
session_regenerate_id() |
Regenerates session ID (security) |
Example 1: Starting a Session and Storing Data
<?php
// Start the session (must be at the beginning, before any output)
session_start();
// Store data in session
$_SESSION['username'] = "John Doe";
$_SESSION['user_id'] = 123;
$_SESSION['email'] = "john@example.com";
$_SESSION['role'] = "admin";
$_SESSION['login_time'] = time();
echo "Session started and data stored successfully!<br>";
echo "Session ID: " . session_id();
?>
Example 2: Accessing Session Data
<?php
// Start session (required on every page that uses sessions)
session_start();
// Check if session variables exist
if (isset($_SESSION['username'])) {
echo "Welcome back, " . $_SESSION['username'] . "!<br>";
echo "User ID: " . $_SESSION['user_id'] . "<br>";
echo "Email: " . $_SESSION['email'] . "<br>";
echo "Role: " . $_SESSION['role'] . "<br>";
} else {
echo "No session data found. Please login.";
}
?>
Example 3: Modifying Session Data
<?php
session_start();
// Modify existing session variable
$_SESSION['username'] = "Jane Smith";
// Add new session variable
$_SESSION['last_activity'] = time();
$_SESSION['page_views'] = isset($_SESSION['page_views']) ? $_SESSION['page_views'] + 1 : 1;
echo "Session updated!<br>";
echo "Page views: " . $_SESSION['page_views'];
?>
Example 4: Destroying Sessions
<?php
session_start();
// Method 1: Unset specific session variable
unset($_SESSION['username']);
// Method 2: Unset all session variables
session_unset();
// Method 3: Destroy the session completely
session_destroy();
echo "Session destroyed!";
// Note: After session_destroy(), you need to start a new session
// if you want to use sessions again
?>
Comprehensive Session Management Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Session Management Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #f0f0f0;
}
.container {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h2 {
color: #333;
border-bottom: 3px solid #4CAF50;
padding-bottom: 10px;
}
.session-info {
background-color: #e7f3ff;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
border-left: 4px solid #2196F3;
}
.form-section {
margin: 20px 0;
padding: 20px;
background-color: #f9f9f9;
border-radius: 5px;
}
input[type="text"], input[type="email"] {
padding: 10px;
width: 70%;
border: 2px solid #ddd;
border-radius: 5px;
margin-right: 10px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #45a049;
}
.logout-btn {
background-color: #f44336;
}
.logout-btn:hover {
background-color: #da190b;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #4CAF50;
color: white;
}
.success {
background-color: #d4edda;
color: #155724;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<h2>🔐 PHP Session Management</h2>
<?php
// Start session
session_start();
// Handle form submissions
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['login'])) {
// Simulate login
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['login_time'] = date('Y-m-d H:i:s');
$_SESSION['page_views'] = 1;
echo '<div class="success">✓ Login successful! Session created.</div>';
}
if (isset($_POST['increment'])) {
if (isset($_SESSION['page_views'])) {
$_SESSION['page_views']++;
echo '<div class="success">✓ Page view count incremented!</div>';
}
}
if (isset($_POST['logout'])) {
session_unset();
session_destroy();
echo '<div class="success">✓ Logged out successfully!</div>';
// Restart session for continued use
session_start();
}
}
?>
<!-- Session Status -->
<div class="session-info">
<h3>Current Session Status</h3>
<?php
if (isset($_SESSION['username'])) {
echo "<p><strong>Status:</strong> <span style='color: green;'>Active Session</span></p>";
echo "<p><strong>Session ID:</strong> " . session_id() . "</p>";
echo "<p><strong>Username:</strong> " . htmlspecialchars($_SESSION['username']) . "</p>";
echo "<p><strong>Email:</strong> " . htmlspecialchars($_SESSION['email']) . "</p>";
echo "<p><strong>Login Time:</strong> " . $_SESSION['login_time'] . "</p>";
echo "<p><strong>Page Views:</strong> " . $_SESSION['page_views'] . "</p>";
} else {
echo "<p><strong>Status:</strong> <span style='color: red;'>No Active Session</span></p>";
echo "<p>Please login to create a session.</p>";
}
?>
</div>
<?php if (!isset($_SESSION['username'])): ?>
<!-- Login Form -->
<div class="form-section">
<h3>Login (Create Session)</h3>
<form method="POST">
<input type="text" name="username" placeholder="Enter username" required>
<input type="email" name="email" placeholder="Enter email" required>
<button type="submit" name="login">Login</button>
</form>
</div>
<?php else: ?>
<!-- Session Actions -->
<div class="form-section">
<h3>Session Actions</h3>
<form method="POST" style="display: inline;">
<button type="submit" name="increment">Increment Page Views</button>
</form>
<form method="POST" style="display: inline;">
<button type="submit" name="logout" class="logout-btn">Logout (Destroy Session)</button>
</form>
</div>
<!-- All Session Variables -->
<div style="margin: 20px 0;">
<h3>All Session Variables</h3>
<table>
<tr>
<th>Variable Name</th>
<th>Value</th>
</tr>
<?php
foreach ($_SESSION as $key => $value) {
echo "<tr>";
echo "<td><strong>" . htmlspecialchars($key) . "</strong></td>";
echo "<td>" . htmlspecialchars($value) . "</td>";
echo "</tr>";
}
?>
</table>
</div>
<?php endif; ?>
<!-- Information Section -->
<div style="background-color: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px; border-left: 4px solid #ffc107;">
<h4>Session Information:</h4>
<ul>
<li><strong>Storage:</strong> Server-side (more secure than cookies)</li>
<li><strong>Duration:</strong> Until browser closes or manual destroy</li>
<li><strong>Size:</strong> No practical limit (unlike cookies)</li>
<li><strong>Security:</strong> Data not exposed to client</li>
<li><strong>Access:</strong> Via $_SESSION superglobal array</li>
</ul>
</div>
<!-- Code Examples -->
<div style="background-color: #f4f4f4; padding: 15px; border-radius: 5px; margin-top: 20px;">
<h4>PHP Session Code Examples:</h4>
<pre style="background-color: #272822; color: #f8f8f2; padding: 15px; border-radius: 5px; overflow-x: auto;">
<code>// Start session
session_start();
// Store data
$_SESSION['username'] = "John";
// Access data
echo $_SESSION['username'];
// Destroy session
session_destroy();</code>
</pre>
</div>
</div>
</body>
</html>
Session Configuration (php.ini):
; Session save path
session.save_path = "/tmp"
; Session name (cookie name)
session.name = PHPSESSID
; Session lifetime (seconds)
session.gc_maxlifetime = 1440
; Session cookie lifetime (0 = until browser closes)
session.cookie_lifetime = 0
; Session auto-start
session.auto_start = 0
Session vs Cookies Comparison:
| Feature | Sessions | Cookies |
|---|---|---|
| Storage | Server-side | Client-side (browser) |
| Security | More secure | Less secure |
| Size | No limit | 4KB limit |
| Lifespan | Until browser close | Can be persistent |
| Speed | Slightly slower | Faster |
| Bandwidth | Only ID transmitted | All data transmitted |
| Data Types | Any PHP data type | String only |
| Best For | Sensitive data, login | User preferences |
Security Best Practices:
<?php
// 1. Regenerate session ID on login (prevent session fixation)
session_start();
session_regenerate_id(true);
// 2. Set session timeout
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();
// 3. Store user IP and check for consistency
if (!isset($_SESSION['USER_IP'])) {
$_SESSION['USER_IP'] = $_SERVER['REMOTE_ADDR'];
} else if ($_SESSION['USER_IP'] != $_SERVER['REMOTE_ADDR']) {
session_destroy();
die("Security violation!");
}
// 4. Use HTTPS for sensitive sessions
// 5. Set httponly and secure flags for session cookies
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
?>
Common Use Cases:
-
User Login System:
// Login page session_start(); $_SESSION['user_id'] = $userId; $_SESSION['username'] = $username; $_SESSION['logged_in'] = true; -
Shopping Cart:
session_start(); if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); } $_SESSION['cart'][] = $productId; -
Multi-step Form:
session_start(); $_SESSION['step1_data'] = $_POST; $_SESSION['step2_data'] = $_POST;
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Sessions Concept in PHP │ 6 marks │
│ - Session definition and purpose │ │
│ - How sessions work │ │
│ - Session lifecycle │ │
│ - Starting sessions (session_start()) │ │
│ - Storing data in $_SESSION │ │
│ - Accessing session variables │ │
│ - Modifying session data │ │
│ - Destroying sessions │ │
│ - Complete code examples: │ │
│ * Login system implementation │ │
│ * Shopping cart example │ │
│ * Multi-step form data persistence │ │
│ - Session vs Cookie comparison │ │
│ - Security considerations │ │
│ - Best practices │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept Explanation (Section 2.2, Pattern 5)
Module V — Module V
Question 19 (14 marks) — #### a) Differentiate between JSON and XML with suitable examples. (8 marks)
a) Differentiate between JSON and XML with suitable examples. (8 marks)
Answer:
JSON (JavaScript Object Notation) vs XML (eXtensible Markup Language):
Both JSON and XML are widely used formats for storing and transmitting data, especially in web applications and APIs. However, they have significant differences in syntax, structure, and use cases.
JSON (JavaScript Object Notation):
JSON is a lightweight, human-readable data interchange format based on JavaScript object syntax. It represents data as key-value pairs and arrays.
Characteristics:
- Lightweight and compact
- Easy to read and write
- Native JavaScript support
- Faster parsing
- Less verbose
- No metadata support
- Data-oriented
XML (eXtensible Markup Language):
XML is a markup language that defines rules for encoding documents in a format that is both human-readable and machine-readable. It uses tags to describe data structure.
Characteristics:
- More verbose
- Supports metadata (attributes)
- Document-oriented
- Schema validation (XSD, DTD)
- Namespace support
- XSLT for transformation
- Better for complex documents
Detailed Comparison:
| Feature | JSON | XML |
|---|---|---|
| Syntax | Uses curly braces {}, square brackets [] |
Uses angle brackets < > for tags |
| Data Types | String, Number, Boolean, Null, Object, Array | All values are strings by default |
| File Size | Smaller (20-30% less) | Larger due to closing tags |
| Parsing | Faster (native in JavaScript) | Slower (requires parser) |
| Readability | More readable, less clutter | More verbose, repetitive tags |
| Comments | No support for comments | Supports comments <!-- --> |
| Metadata | No attribute support | Supports attributes |
| Arrays | Native array support [] |
No direct array representation |
| Namespaces | No namespace support | Full namespace support |
| Schema | JSON Schema | XSD, DTD |
| Use Cases | APIs, web services, config files | Documents, complex data, legacy systems |
| Security | Safer (no external entity attacks) | Vulnerable (XML external entities) |
| Extensibility | Limited | Highly extensible |
| MIME Type | application/json |
application/xml or text/xml |
Example 1: Simple Student Data
JSON Format:
{
"student": {
"id": 101,
"name": "Arjun Menon",
"age": 21,
"email": "arjun@example.com",
"courses": ["PHP", "JavaScript", "MySQL"],
"active": true,
"gpa": 8.5
}
}
XML Format:
<?xml version="1.0" encoding="UTF-8"?>
<student>
<id>101</id>
<name>Arjun Menon</name>
<age>21</age>
<email>arjun@example.com</email>
<courses>
<course>PHP</course>
<course>JavaScript</course>
<course>MySQL</course>
</courses>
<active>true</active>
<gpa>8.5</gpa>
</student>
Comparison:
- JSON: 157 characters
- XML: 268 characters
- JSON is 41% more compact
Example 2: Multiple Students with Arrays
JSON Format:
{
"university": "APJ Abdul Kalam Technological University",
"students": [
{
"id": 101,
"name": "Arjun Menon",
"course": "B.Tech CSE",
"marks": 85,
"grade": "A"
},
{
"id": 102,
"name": "Priya Sharma",
"course": "B.Tech CSE",
"marks": 92,
"grade": "A+"
},
{
"id": 103,
"name": "Karthik Nair",
"course": "B.Tech CSE",
"marks": 78,
"grade": "B+"
}
],
"total_students": 3
}
XML Format:
<?xml version="1.0" encoding="UTF-8"?>
<university name="APJ Abdul Kalam Technological University">
<students>
<student id="101">
<name>Arjun Menon</name>
<course>B.Tech CSE</course>
<marks>85</marks>
<grade>A</grade>
</student>
<student id="102">
<name>Priya Sharma</name>
<course>B.Tech CSE</course>
<marks>92</marks>
<grade>A+</grade>
</student>
<student id="103">
<name>Karthik Nair</name>
<course>B.Tech CSE</course>
<marks>78</marks>
<grade>B+</grade>
</student>
</students>
<total_students>3</total_students>
</university>
Note: XML uses attributes (id="101") which JSON doesn't support. XML also allows both element content and attributes for the same data.
Example 3: Nested Complex Data
JSON Format:
{
"company": {
"name": "Tech Solutions Inc.",
"founded": 2020,
"employees": [
{
"id": 1,
"name": "John Doe",
"position": "CEO",
"department": "Management",
"salary": 150000,
"skills": ["Leadership", "Strategy", "Management"]
},
{
"id": 2,
"name": "Jane Smith",
"position": "CTO",
"department": "Technology",
"salary": 140000,
"skills": ["PHP", "Python", "Architecture"]
}
],
"locations": {
"headquarters": "Mumbai",
"branches": ["Delhi", "Bangalore", "Hyderabad"]
}
}
}
XML Format:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<name>Tech Solutions Inc.</name>
<founded>2020</founded>
<employees>
<employee id="1">
<name>John Doe</name>
<position>CEO</position>
<department>Management</department>
<salary>150000</salary>
<skills>
<skill>Leadership</skill>
<skill>Strategy</skill>
<skill>Management</skill>
</skills>
</employee>
<employee id="2">
<name>Jane Smith</name>
<position>CTO</position>
<department>Technology</department>
<salary>140000</salary>
<skills>
<skill>PHP</skill>
<skill>Python</skill>
<skill>Architecture</skill>
</skills>
</employee>
</employees>
<locations>
<headquarters>Mumbai</headquarters>
<branches>
<branch>Delhi</branch>
<branch>Bangalore</branch>
<branch>Hyderabad</branch>
</branches>
</locations>
</company>
Example 4: Using in PHP
Working with JSON in PHP:
<?php
// Create JSON
$data = array(
"name" => "Arjun",
"age" => 21,
"courses" => array("PHP", "MySQL", "JavaScript")
);
$jsonString = json_encode($data);
echo $jsonString;
// Output: {"name":"Arjun","age":21,"courses":["PHP","MySQL","JavaScript"]}
// Parse JSON
$jsonData = '{"name":"Priya","age":20,"grade":"A+"}';
$parsedData = json_decode($jsonData, true);
echo $parsedData['name']; // Output: Priya
// Pretty print JSON
echo json_encode($data, JSON_PRETTY_PRINT);
?>
Working with XML in PHP:
<?php
// Create XML
$xml = new SimpleXMLElement('<student></student>');
$xml->addChild('name', 'Arjun');
$xml->addChild('age', 21);
$xml->addChild('grade', 'A');
echo $xml->asXML();
// Output: <?xml version="1.0"?>
// <student><name>Arjun</name><age>21</age><grade>A</grade></student>
// Parse XML
$xmlString = '<?xml version="1.0"?><student><name>Priya</name><age>20</age></student>';
$xmlData = simplexml_load_string($xmlString);
echo $xmlData->name; // Output: Priya
?>
Advantages and Disadvantages:
JSON Advantages:
- ✓ Lightweight and compact
- ✓ Faster to parse
- ✓ Native JavaScript support
- ✓ Easy to read and write
- ✓ Better for APIs and web services
- ✓ Less bandwidth consumption
- ✓ Direct array support
JSON Disadvantages:
- ✗ No comment support
- ✗ No metadata (attributes)
- ✗ Limited data types
- ✗ No namespace support
- ✗ No schema validation standard (JSON Schema less popular)
XML Advantages:
- ✓ Supports comments
- ✓ Metadata via attributes
- ✓ Robust schema validation (XSD)
- ✓ Namespace support
- ✓ XSLT for transformations
- ✓ Better for document markup
- ✓ Widely adopted standard
XML Disadvantages:
- ✗ Verbose and bulky
- ✗ Slower parsing
- ✗ More bandwidth
- ✗ More complex
- ✗ No native array support
- ✗ Security vulnerabilities (XXE attacks)
When to Use JSON:
- RESTful APIs
- Web services
- Configuration files
- Data exchange in web applications
- Mobile applications
- NoSQL databases (MongoDB)
- Real-time applications
When to Use XML:
- SOAP web services
- Document-oriented applications
- Complex data structures with metadata
- Legacy systems
- Enterprise applications
- RSS/Atom feeds
- SVG graphics
Real-World Example: API Response
JSON API Response:
{
"status": "success",
"code": 200,
"message": "Data retrieved successfully",
"data": {
"user": {
"id": 12345,
"username": "john_doe",
"email": "john@example.com",
"verified": true
},
"posts": [
{"id": 1, "title": "First Post", "likes": 100},
{"id": 2, "title": "Second Post", "likes": 150}
]
},
"timestamp": "2024-11-15T10:30:00Z"
}
XML API Response:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>success</status>
<code>200</code>
<message>Data retrieved successfully</message>
<data>
<user>
<id>12345</id>
<username>john_doe</username>
<email>john@example.com</email>
<verified>true</verified>
</user>
<posts>
<post>
<id>1</id>
<title>First Post</title>
<likes>100</likes>
</post>
<post>
<id>2</id>
<title>Second Post</title>
<likes>150</likes>
</post>
</posts>
</data>
<timestamp>2024-11-15T10:30:00Z</timestamp>
</response>
Conclusion:
- JSON is preferred for modern web applications, APIs, and mobile apps due to its simplicity, speed, and native JavaScript support
- XML remains relevant for document-centric applications, enterprise systems, and scenarios requiring metadata, namespaces, or complex validation
In most web development scenarios today, JSON has become the de facto standard for data interchange, while XML is still used in specific domains and legacy systems.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON vs XML Differentiation │ 8 marks │
│ - Definition of both formats │ │
│ - Key differences across multiple aspects: │ │
│ * Syntax and structure │ │
│ * Readability │ │
│ * Data types support │ │
│ * File size and verbosity │ │
│ * Parsing speed │ │
│ * Schema validation │ │
│ * Namespace support │ │
│ * Comments support │ │
│ - Complete examples of same data in both │ │
│ - Detailed comparison table │ │
│ - Advantages and disadvantages │ │
│ - Use cases for each format │ │
│ - Real-world API examples │ │
│ - Conclusion on when to use each │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Comprehensive Differentiation (Section 3.2, Pattern 1)
b) Explain the structure of JSON Schema with suitable examples (6 marks)
Answer:
JSON Schema:
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It provides a contract for JSON data, defining the structure, data types, constraints, and validation rules for JSON objects.
Purpose:
- Validation: Ensure data conforms to expected structure
- Documentation: Self-documenting API contracts
- Code Generation: Auto-generate code from schema
- Data Integrity: Enforce data quality and consistency
- API Design: Define request/response formats
Basic Structure of JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/schema-id",
"title": "Schema Title",
"description": "Schema Description",
"type": "object",
"properties": {
// Define object properties here
},
"required": ["field1", "field2"]
}
Key Components:
$schema: Specifies JSON Schema version$id: Unique identifier for the schematitle: Human-readable titledescription: Detailed descriptiontype: Data type (object, array, string, number, boolean, null)properties: Object property definitionsrequired: Array of required field names
Example 1: Simple Student Schema
JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/student.schema.json",
"title": "Student",
"description": "A student record",
"type": "object",
"properties": {
"id": {
"description": "Student unique identifier",
"type": "integer",
"minimum": 1
},
"name": {
"description": "Student full name",
"type": "string",
"minLength": 2,
"maxLength": 100
},
"email": {
"description": "Student email address",
"type": "string",
"format": "email"
},
"age": {
"description": "Student age",
"type": "integer",
"minimum": 15,
"maximum": 100
},
"grade": {
"description": "Student grade",
"type": "string",
"enum": ["A+", "A", "B+", "B", "C", "F"]
},
"active": {
"description": "Whether student is currently active",
"type": "boolean"
}
},
"required": ["id", "name", "email", "age"],
"additionalProperties": false
}
Valid JSON Data:
{
"id": 101,
"name": "Arjun Menon",
"email": "arjun@example.com",
"age": 21,
"grade": "A",
"active": true
}
Example 2: Complex Schema with Nested Objects
JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/employee.schema.json",
"title": "Employee",
"description": "Employee information with nested address",
"type": "object",
"properties": {
"employeeId": {
"type": "integer",
"description": "Unique employee identifier"
},
"fullName": {
"type": "string",
"minLength": 3,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"phone": {
"type": "string",
"pattern": "^[0-9]{10}$"
},
"department": {
"type": "string",
"enum": ["IT", "HR", "Finance", "Marketing", "Operations"]
},
"salary": {
"type": "number",
"minimum": 10000,
"maximum": 1000000
},
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
},
"pincode": {
"type": "string",
"pattern": "^[0-9]{6}$"
}
},
"required": ["city", "state", "pincode"]
},
"skills": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
},
"joinDate": {
"type": "string",
"format": "date"
}
},
"required": ["employeeId", "fullName", "email", "department", "salary"]
}
Valid JSON Data:
{
"employeeId": 1001,
"fullName": "Priya Sharma",
"email": "priya.sharma@company.com",
"phone": "9876543210",
"department": "IT",
"salary": 75000,
"address": {
"street": "123 MG Road",
"city": "Bangalore",
"state": "Karnataka",
"pincode": "560001"
},
"skills": ["PHP", "JavaScript", "MySQL", "Laravel"],
"joinDate": "2024-01-15"
}
Example 3: Array Schema
JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/students-list.schema.json",
"title": "Students List",
"description": "Collection of students",
"type": "object",
"properties": {
"university": {
"type": "string"
},
"students": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"marks": {
"type": "number",
"minimum": 0,
"maximum": 100
}
},
"required": ["id", "name", "marks"]
},
"minItems": 1
},
"totalStudents": {
"type": "integer",
"minimum": 0
}
},
"required": ["university", "students", "totalStudents"]
}
Valid JSON Data:
{
"university": "APJ Abdul Kalam Technological University",
"students": [
{
"id": 101,
"name": "Arjun Menon",
"marks": 85
},
{
"id": 102,
"name": "Priya Sharma",
"marks": 92
}
],
"totalStudents": 2
}
JSON Schema Data Types:
| Type | Description | Example |
|---|---|---|
string |
Text data | "Hello World" |
number |
Numeric data (integer or float) | 42, 3.14 |
integer |
Whole numbers only | 42 |
boolean |
True or false | true, false |
object |
Key-value pairs | {"name": "John"} |
array |
Ordered list | [1, 2, 3] |
null |
Null value | null |
Common Validation Keywords:
String Validation:
{
"type": "string",
"minLength": 5,
"maxLength": 50,
"pattern": "^[A-Za-z]+$",
"format": "email" // or "date", "time", "uri", "ipv4", etc.
}
Number Validation:
{
"type": "number",
"minimum": 0,
"maximum": 100,
"multipleOf": 5
}
Array Validation:
{
"type": "array",
"items": {"type": "string"},
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}
Object Validation:
{
"type": "object",
"properties": {...},
"required": ["field1", "field2"],
"additionalProperties": false,
"minProperties": 2,
"maxProperties": 10
}
Enum (Fixed Values):
{
"type": "string",
"enum": ["small", "medium", "large"]
}
Complete Real-World Example: Product Schema
JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/product.schema.json",
"title": "Product",
"description": "E-commerce product schema",
"type": "object",
"properties": {
"productId": {
"description": "Unique product identifier",
"type": "string",
"pattern": "^PROD-[0-9]{6}$"
},
"name": {
"description": "Product name",
"type": "string",
"minLength": 3,
"maxLength": 100
},
"description": {
"description": "Product description",
"type": "string",
"maxLength": 500
},
"price": {
"description": "Product price in INR",
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"category": {
"description": "Product category",
"type": "string",
"enum": ["Electronics", "Clothing", "Books", "Home", "Sports"]
},
"inStock": {
"description": "Availability status",
"type": "boolean"
},
"quantity": {
"description": "Available quantity",
"type": "integer",
"minimum": 0
},
"tags": {
"description": "Product tags",
"type": "array",
"items": {
"type": "string"
},
"uniqueItems": true
},
"ratings": {
"type": "object",
"properties": {
"average": {
"type": "number",
"minimum": 0,
"maximum": 5
},
"count": {
"type": "integer",
"minimum": 0
}
},
"required": ["average", "count"]
},
"seller": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"rating": {
"type": "number",
"minimum": 0,
"maximum": 5
}
},
"required": ["name"]
}
},
"required": ["productId", "name", "price", "category", "inStock"],
"additionalProperties": false
}
Valid JSON Data:
{
"productId": "PROD-123456",
"name": "Wireless Bluetooth Headphones",
"description": "High-quality wireless headphones with noise cancellation",
"price": 2999.99,
"category": "Electronics",
"inStock": true,
"quantity": 50,
"tags": ["audio", "wireless", "bluetooth", "headphones"],
"ratings": {
"average": 4.5,
"count": 230
},
"seller": {
"name": "TechStore India",
"rating": 4.8
}
}
Using JSON Schema in PHP:
<?php
// Using opis/json-schema library
require 'vendor/autoload.php';
use Opis\JsonSchema\Validator;
// Define schema
$schema = (object)[
"type" => "object",
"properties" => (object)[
"name" => (object)[
"type" => "string",
"minLength" => 2
],
"age" => (object)[
"type" => "integer",
"minimum" => 18
]
],
"required" => ["name", "age"]
];
// Data to validate
$data = (object)[
"name" => "John",
"age" => 25
];
// Validate
$validator = new Validator();
$result = $validator->validate($data, $schema);
if ($result->isValid()) {
echo "Valid data!";
} else {
echo "Invalid data: " . $result->error()->message();
}
?>
Benefits of JSON Schema:
- Validation: Automatic data validation
- Documentation: Self-documenting API contracts
- Consistency: Ensures data consistency across systems
- Error Prevention: Catches data errors early
- Type Safety: Enforces data types
- Code Generation: Tools can generate code from schema
- API Testing: Validate API requests/responses
Use Cases:
- REST API documentation
- Configuration file validation
- Database schema definitions
- Form validation
- Data migration
- Microservices communication
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Schema Structure and Examples │ 6 marks │
│ - JSON Schema definition and purpose │ │
│ - Schema structure components: │ │
│ * $schema keyword │ │
│ * $id keyword │ │
│ * type keyword │ │
│ * properties keyword │ │
│ * required keyword │ │
│ * additionalProperties │ │
│ - Data type specifications │ │
│ - Validation rules (minimum, maximum, etc.) │ │
│ - Complete schema examples │ │
│ - Corresponding valid/invalid JSON data │ │
│ - Nested objects and arrays in schema │ │
│ - PHP implementation example │ │
│ - Benefits and use cases │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept Explanation (Section 2.2, Pattern 5)
Question 20 (14 marks) — #### a) Explain Route Model Binding in Laravel and describe types of route model binding supported in Laravel. (8 marks)
a) Explain Route Model Binding in Laravel and describe types of route model binding supported in Laravel. (8 marks)
Answer:
Route Model Binding in Laravel:
Route Model Binding is a convenient feature in Laravel that automatically injects model instances into routes based on route parameters. Instead of manually retrieving models from the database using IDs, Laravel does this automatically, making code cleaner and more expressive.
Purpose:
- Simplifies controller logic
- Reduces boilerplate code
- Automatic model injection
- Built-in 404 handling
- Type-hinted dependencies
How It Works:
Without Route Model Binding:
// Route
Route::get('/students/{id}', [StudentController::class, 'show']);
// Controller
public function show($id) {
$student = Student::findOrFail($id);
return view('student.show', compact('student'));
}
With Route Model Binding:
// Route
Route::get('/students/{student}', [StudentController::class, 'show']);
// Controller
public function show(Student $student) {
// $student is automatically injected
return view('student.show', compact('student'));
}
Types of Route Model Binding:
1. Implicit Binding
Laravel automatically resolves models based on route parameter names that match the model variable name in the controller method.
Example 1: Basic Implicit Binding
Route:
Route::get('/students/{student}', [StudentController::class, 'show']);
Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function show(Student $student)
{
// Laravel automatically finds student by ID
// If not found, returns 404
return view('students.show', compact('student'));
}
}
View (students/show.blade.php):
<h1>Student Details</h1>
<p>Name: {{ $student->name }}</p>
<p>Roll No: {{ $student->roll_number }}</p>
<p>Email: {{ $student->email }}</p>
Usage:
URL: /students/5
Laravel automatically executes: Student::findOrFail(5)
Example 2: Multiple Model Binding
Route:
Route::get('/courses/{course}/students/{student}', [StudentController::class, 'showCourseStudent']);
Controller:
public function showCourseStudent(Course $course, Student $student)
{
// Both models are automatically injected
return view('courses.student', compact('course', 'student'));
}
Example 3: Custom Column for Implicit Binding
By default, Laravel uses the id column. You can customize this in the model:
Model (App/Models/Student.php):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'roll_number'; // Use roll_number instead of id
}
}
Route:
Route::get('/students/{student}', [StudentController::class, 'show']);
Usage:
URL: /students/CS2024001
Laravel executes: Student::where('roll_number', 'CS2024001')->firstOrFail()
Example 4: Scoped Implicit Binding
Ensure a child model belongs to a parent model:
Route:
Route::get('/courses/{course}/students/{student}', [StudentController::class, 'show'])
->scopeBindings();
Controller:
public function show(Course $course, Student $student)
{
// Laravel ensures $student belongs to $course
// SQL: SELECT * FROM students WHERE id = ? AND course_id = ?
return view('courses.student', compact('course', 'student'));
}
2. Explicit Binding
Define custom resolution logic in RouteServiceProvider. Useful for complex queries or custom logic.
RouteServiceProvider (app/Providers/RouteServiceProvider.php):
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use App\Models\Student;
use App\Models\Course;
class RouteServiceProvider extends ServiceProvider
{
public function boot()
{
// Explicit binding for students
Route::model('student', Student::class);
// Custom resolution logic
Route::bind('student', function ($value) {
return Student::where('roll_number', $value)->firstOrFail();
});
// Binding with relationships
Route::bind('course_student', function ($value) {
return Student::with('course')->findOrFail($value);
});
parent::boot();
}
}
Route:
Route::get('/students/{student}', [StudentController::class, 'show']);
Controller:
public function show(Student $student)
{
// Uses custom resolution logic from RouteServiceProvider
return view('students.show', compact('student'));
}
Example: Explicit Binding with Custom Logic
RouteServiceProvider:
public function boot()
{
// Find by slug instead of ID
Route::bind('post', function ($value) {
return \App\Models\Post::where('slug', $value)->firstOrFail();
});
// With additional query constraints
Route::bind('active_student', function ($value) {
return \App\Models\Student::where('id', $value)
->where('status', 'active')
->firstOrFail();
});
parent::boot();
}
Complete Example: Student Management System
Model (App/Models/Student.php):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['roll_number', 'name', 'email', 'course', 'year'];
// Use roll_number for route binding
public function getRouteKeyName()
{
return 'roll_number';
}
// Relationship
public function course()
{
return $this->belongsTo(Course::class);
}
}
Routes (routes/web.php):
<?php
use App\Http\Controllers\StudentController;
// Implicit binding with ID
Route::get('/students/{student}', [StudentController::class, 'show']);
// Implicit binding with custom key (roll_number)
Route::get('/students/roll/{student}', [StudentController::class, 'showByRoll']);
// Edit student
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']);
// Scoped binding - student must belong to course
Route::get('/courses/{course}/students/{student}', [StudentController::class, 'showCourseStudent'])
->scopeBindings();
Controller (App/Http/Controllers/StudentController.php):
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use App\Models\Course;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// Show student details
public function show(Student $student)
{
return view('students.show', compact('student'));
}
// Show by roll number
public function showByRoll(Student $student)
{
return view('students.show', compact('student'));
}
// Edit student
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
// Update student
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email',
]);
$student->update($validated);
return redirect()->route('students.show', $student)
->with('success', 'Student updated successfully');
}
// Delete student
public function destroy(Student $student)
{
$student->delete();
return redirect()->route('students.index')
->with('success', 'Student deleted successfully');
}
// Show student within course (scoped binding)
public function showCourseStudent(Course $course, Student $student)
{
// Laravel ensures student belongs to course
return view('courses.student', compact('course', 'student'));
}
}
Comparison Table:
| Feature | Implicit Binding | Explicit Binding |
|---|---|---|
| Definition | Automatic | Manual in RouteServiceProvider |
| Configuration | Model method | Route::bind() |
| Flexibility | Limited | Highly flexible |
| Custom Logic | Via model method | Full control |
| Use Case | Simple lookups | Complex queries |
| Example | getRouteKeyName() |
Route::bind() |
Benefits of Route Model Binding:
- Cleaner Code: Eliminates repetitive
findOrFail()calls - Automatic 404: Returns 404 if model not found
- Type Safety: Type-hinted model injection
- Readability: More expressive route definitions
- Consistency: Standard approach across application
- Less Code: Reduces boilerplate in controllers
Best Practices:
- Use implicit binding for simple lookups
- Use explicit binding for complex queries
- Customize
getRouteKeyName()for non-ID columns - Use scoped bindings for parent-child relationships
- Always type-hint models in controller methods
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Route Model Binding Explanation │ 4 marks │
│ - Definition and purpose │ │
│ - How it works │ │
│ - Benefits of using route model binding │ │
│ - Problem it solves │ │
│ │ │
│ 2. Types of Route Model Binding │ 4 marks │
│ - Implicit Binding: │ │
│ * Explanation and mechanism │ │
│ * Route syntax │ │
│ * Controller method example │ │
│ * Custom key binding │ │
│ - Explicit Binding: │ │
│ * Explanation and mechanism │ │
│ * RouteServiceProvider setup │ │
│ * Custom logic implementation │ │
│ * Complete code examples │ │
│ - Scoped Binding explanation │ │
│ - Comparison table │ │
│ - Complete practical examples │ │
│ - Best practices │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Definition + Types/Components (Section 3.2, Pattern 1)
b) With a neat diagram, explain about Laravel MVC Framework. (6 marks)
Answer:
Laravel MVC Framework:
Laravel follows the Model-View-Controller (MVC) architectural pattern, which separates application logic into three interconnected components. This separation promotes organized code, easier maintenance, and better scalability.
MVC Components:
1. Model (M):
- Represents data and business logic
- Interacts with database
- Eloquent ORM for database operations
- Defines relationships between tables
- Location:
app/Models/
2. View (V):
- Presentation layer
- Displays data to users
- Blade templating engine
- HTML, CSS, JavaScript
- Location:
resources/views/
3. Controller (C):
- Request handling logic
- Bridge between Model and View
- Processes user input
- Returns responses
- Location:
app/Http/Controllers/
Laravel MVC Architecture Diagram:
┌─────────────────────────────────────────────────────────────┐
│ USER / BROWSER │
└──────────────────────────┬──────────────────────────────────┘
│ HTTP Request
▼
┌─────────────────────────────────────────────────────────────┐
│ ROUTING │
│ (routes/web.php) │
│ Maps URL to Controller │
└──────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ CONTROLLER │
│ (app/Http/Controllers/) │
│ • Receives request │
│ • Validates input │
│ • Calls Model for data │
│ • Returns View with data │
└─────────────┬────────────────────────────┬──────────────────┘
│ │
│ Fetch/Store Data │ Pass Data
▼ ▼
┌──────────────────────────┐ ┌─────────────────────────────┐
│ MODEL │ │ VIEW │
│ (app/Models/) │ │ (resources/views/) │
│ │ │ │
│ • Eloquent ORM │ │ • Blade Templates │
│ • Database queries │ │ • HTML Structure │
│ • Business logic │ │ • Display data │
│ • Relationships │ │ • User Interface │
│ • Validation rules │ │ │
└─────────────┬────────────┘ └─────────────┬───────────────┘
│ │
▼ │
┌──────────────────────────┐ │
│ DATABASE │ │
│ (MySQL/PostgreSQL) │ │
│ │ │
│ • Tables │ │
│ • Data Storage │ │
│ • Relationships │ │
└──────────────────────────┘ │
│ Rendered HTML
▼
┌─────────────────────────────────┐
│ HTTP Response │
│ (HTML/JSON/Redirect) │
└─────────────────────────────────┘
│
▼
┌─────────────────────────────────┐
│ USER / BROWSER │
│ (Display Result) │
└─────────────────────────────────┘
Detailed Flow Explanation:
Step 1: User Request
User enters URL: http://example.com/students
Browser sends HTTP GET request to Laravel application
Step 2: Routing
// routes/web.php
Route::get('/students', [StudentController::class, 'index']);
- Laravel router matches URL pattern
- Directs request to appropriate controller method
Step 3: Controller
// app/Http/Controllers/StudentController.php
<?php
namespace App\Http\Controllers;
use App\Models\Student;
class StudentController extends Controller
{
public function index()
{
// Call Model to fetch data
$students = Student::all();
// Pass data to View
return view('students.index', compact('students'));
}
}
- Receives request
- Calls Model to retrieve data
- Passes data to View
Step 4: Model
// app/Models/Student.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['name', 'email', 'course'];
// Eloquent automatically handles database queries
// Student::all() executes: SELECT * FROM students
}
- Eloquent ORM handles database operations
- Returns data to Controller
Step 5: View
<!-- resources/views/students/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Students List</title>
</head>
<body>
<h1>All Students</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
@foreach($students as $student)
<tr>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->course }}</td>
</tr>
@endforeach
</table>
</body>
</html>
- Blade engine renders template
- Displays data in HTML format
Step 6: Response
Rendered HTML sent back to user's browser
Browser displays the page
Complete Example: CRUD Operations
1. Model (app/Models/Student.php):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['roll_number', 'name', 'email', 'course', 'marks'];
// Relationship with Course model
public function course()
{
return $this->belongsTo(Course::class);
}
}
2. Controller (app/Http/Controllers/StudentController.php):
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// Display all students
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
// Show create form
public function create()
{
return view('students.create');
}
// Store new student
public function store(Request $request)
{
$validated = $request->validate([
'roll_number' => 'required|unique:students',
'name' => 'required|string|max:100',
'email' => 'required|email|unique:students',
'course' => 'required|string',
'marks' => 'required|integer|min:0|max:100'
]);
Student::create($validated);
return redirect()->route('students.index')
->with('success', 'Student created successfully');
}
// Show single student
public function show(Student $student)
{
return view('students.show', compact('student'));
}
// Show edit form
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
// Update student
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email',
'marks' => 'required|integer|min:0|max:100'
]);
$student->update($validated);
return redirect()->route('students.show', $student)
->with('success', 'Student updated successfully');
}
// Delete student
public function destroy(Student $student)
{
$student->delete();
return redirect()->route('students.index')
->with('success', 'Student deleted successfully');
}
}
3. Routes (routes/web.php):
<?php
use App\Http\Controllers\StudentController;
// Resource route (creates all CRUD routes automatically)
Route::resource('students', StudentController::class);
// Equivalent to:
// 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');
4. Views:
Index View (resources/views/students/index.blade.php):
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Students List</h1>
<a href="{{ route('students.create') }}" class="btn btn-primary">Add New Student</a>
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
<table class="table">
<thead>
<tr>
<th>Roll Number</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
<th>Marks</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->roll_number }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->course }}</td>
<td>{{ $student->marks }}</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>
</div>
@endsection
Benefits of Laravel MVC:
- Separation of Concerns: Each component has specific responsibility
- Maintainability: Easier to update and maintain code
- Reusability: Models and Views can be reused
- Testability: Components can be tested independently
- Scalability: Easy to add features without breaking existing code
- Team Collaboration: Different team members can work on different layers
- Code Organization: Structured and organized codebase
Laravel MVC Advantages:
- Eloquent ORM: Powerful database abstraction
- Blade Templating: Clean, expressive syntax
- Routing: Simple and intuitive
- Middleware: Request filtering
- Validation: Built-in validation system
- Authentication: Ready-to-use auth system
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Laravel MVC Framework with Diagram │ 6 marks │
│ - MVC pattern explanation │ │
│ - Model component details (Eloquent ORM) │ │
│ - View component details (Blade templates) │ │
│ - Controller component details │ │
│ - Complete architecture diagram showing: │ │
│ * User/Browser │ │
│ * Routing layer │ │
│ * Controller processing │ │
│ * Model and database interaction │ │
│ * View rendering │ │
│ * Response flow │ │
│ - Detailed flow explanation (step-by-step) │ │
│ - Complete code examples for each component │ │
│ - Benefits of Laravel MVC │ │
│ - Laravel-specific advantages │ │
└────────────────────────────────────────────────┴────────────┘
Pattern: Complete Concept with Diagram (Section 2.2, Pattern 5)
End of Answer Key