Web Tech 5 Unit q&b
Web Tech 5 Unit q&b
SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Define session.
Ans:
8.
A session is a server-side storage mechanism used to persist stateful user identity variables across
multiple page requests, tracking users via a temporary session ID token stored in cookies or URLs.
What are cookies?
Ans:
9. Cookies are small text configuration files saved directly on the client side by the user's web browser,
transmitted along with every HTTP request to store preferences or login tracking tokens.
Part B
Explain the features and architecture of PHP.
Ans:
Features of PHP:
- Open-Source & Multi-Platform: Free deployment across Linux, Windows, or macOS systems.
- Embedded Engine: Runs alongside standard HTML layouts within standard web views.
- Dynamic Typing: Variables adapt to metadata states automatically.
Client-Side Scripting:PHP can generate dynamicHTMLthat is sent to the browser.
While it runs on the server, the content it generates can be displayed in the client’s
browser.
Database Handling: PHP easily connects to
11. databaseslikeMySQL,PostgreSQLandSQLite, allowing for efficient data management
and storage in web applications.
Simple Learning Curve: PHP’s syntax is easy to learn, especially for those with basic
knowledge of HTML and programming concepts.
Rich Ecosystem:PHP offers many libraries and frameworks like Laravel and Symfony,
which make development faster and more efficient.
Scalability: PHP is highly scalable, allowing developers to create websites that can grow
in terms of traffic and functionality.
Asynchronous Support: PHP, through the use of libraries and frameworks like
ReactPHP, supports asynchronous programming, allowing developers to handle multiple
requests concurrently.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Discuss variables, data types, arrays, and strings in PHP with examples.
Ans:
PHP Variables
Variables are "containers" for storing information.
A variable can have a short name (like$xand$y) or a more descriptive name ($age,$carname,
$total_volume).
Rules for PHP variables:
A variable must start with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Example
echo "<br>";
echo $y;
?>
</body>
</html>
Data Types
Variables can store data of different types, and different data types can do different
things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
Example: The var_dump() function returns the data type and the value:
<!DOCTYPE html>
<html>
<body>
<?php
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
?>
</body>
</html>
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes:
Example:
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
<!DOCTYPE html>
<html>
<body>
</body>
</html>
PHP Arrays
In PHP, an array is a special variable that can hold many values under a single name, and you
can access the values by referring to an index number or a name.
In PHP, there are three types of arrays:
Indexed arrays- Arrays with a numeric index
Associative arrays- Arrays with named keys
Multidimensional arrays- Arrays containing one or more arrays
<?php
// create array
$myArr = array("Volvo", 15, ["apples", "bananas"]);
echo "$myArr[0]<br>";
echo "$myArr[1]<br>";
echo "$myArr[2]";
?>
</body>
</html>
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Describe control structures in PHP.
Ans:
PHP supports foundational logical branches and loop iteration sequences:
1. Conditional Branches: if-else statements and switch-case patterns for routing operations based
on data comparisons.
Conditional statements are used to perform different actions based on different conditions.
In PHP, we have the following conditional statements:
if statement - executes some code if one condition is true
a) if...else statement - executes some code if a condition is true and another code if
13.
that condition is false
if...elseif...else statement - executes different codes for more than two
conditions
switch statement - selects one of many blocks of code to be executed
Example:
<?php
$t = 14;
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
Use the switch statement to select one of many blocks of code to be executed.
Example:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
2. Iteration Loops:
- for loops for executing code blocks a predetermined number of times.
- while and do-while loops for repeating tasks based on boolean status conditions.
- foreach loops, designed for looping through array sets: foreach($arr as $key => $val).
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
Example for for loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example for for..each loop
<?php
$colors = array("red", "green", "blue", "yellow");
b) The opening curly brace{indicates the beginning of the function code, and the closing curly
brace}indicates the end of the function.
Note: A function name is not case-sensitive, and it must start with a letter or an underscore.
The following example creates a function named myMessage():
function myMessage()
{
echo "Hello world!";
}
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Call a Function
To call a function, just write its name followed by parentheses().
The function below outputs "Hello world!":
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
PHP Function Parameters
Information can be passed to functions through parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
setHeight(350);
setHeight();
?>
This standard script demonstrates how to configure credentials, safely open a connection,
execute a data-fetching query, and close the resource properly.
<?php
// 1. Define Database Credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Credential Initialization: Sets up variables holding the target server hostname, administrative
username, security password, and the specific database layout.
Instance Instantiation: Invoking new mysqli() fires up the native driver to bridge
communications with the database layer.
Error Verification: Checking $conn->connect_error catches authorization or network errors
early, halting execution via die() before compiling broken operations.
Data Loop Processing: The fetch_assoc() mechanism acts as a cursor, outputting one mapped
data row at a time until the query array empties out.
Resource Cleanup: Explicitly calling $conn->close() terminates the connection thread
immediately, preventing connection pool leaks on the server host.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Cookies are small text files limited to roughly 4KB of data stored directly on the user’s computer.
Because clients can view and modify cookie data, they must never store sensitive information like
passwords
1. Setting a Cookie
To create a cookie, use the setcookie() function. This function must be executed before any
HTML or text output is sent to the browser
setcookie("user_preference", "dark_mode", [
15. a) 'expires' => $expire_time,
'path' => '/',
'domain' => '',
'secure' => true, // Sent only over HTTPS
'httponly' => true, // Inaccessible to JavaScript (prevents XSS cookie theft)
'samesite' => 'Lax' // Mitigates CSRF attacks
]);
2. Reading a Cookie
You can read browser cookies via the $_COOKIE superglobal associative array. Always verify
its existence using isset()
if (isset($_COOKIE['user_preference'])) {
$theme = $_COOKIE['user_preference'];
echo "Your theme is: " . htmlspecialchars($theme);
}
3. Deleting a Cookie
To delete a cookie, use setcookie() with the exact same configuration parameters but set the
expiration time to a past date
<?php
session_start(); // Initializes or resumes the session
Once a session is active, variables are instantly readable across any script on the server.
<?php
session_start();
if (isset($_SESSION['user_id'])) {
echo "Welcome back, " . htmlspecialchars($_SESSION['username']);
}
3. Destroying Sessions
To clear a session completely (e.g., during a user logout), free all array entries and wipe the server
file
<?php
session_start();
Discuss form handling in PHP using textboxes, radio buttons, and list controls.
b) Ans:
Form handling in PHP relies on capturing data submitted via HTML elements using the
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
superglobal arrays $_POST or $_GET . The interaction between HTML input fields and server-side
PHP scripts depends directly on the element's name attribute
The Request Method: Use method="POST" in your HTML <form> tag for data security and
handling larger sets of information.
Superglobal Collection: PHP instantly populates $_POST['element_name'] with the user's
choices once submitted.
Data Validation & Security: Always run data through htmlspecialchars() to sanitize inputs
against Cross-Site Scripting (XSS) injections
The table below breaks down the design syntax and data handling models for textboxes, radio
buttons, and list controls.
List Control (Multiple) <select name="skills[]" Indexed Array Requires array notation
multiple>... (Array of chosen [] in the name
entries) attribute. Loops are
needed to iterate
through choices.
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
This unified layout showcases both the front-end interface structure and the back-end extraction
script required to safely process all three inputs.
<?php
// Initialize output and error monitoring vars
$errors = [];
$formData = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 1. Textbox Processing
if (!empty($_POST["username"])) {
$formData['username'] = htmlspecialchars(trim($_POST["username"]));
} else {
$errors[] = "Username textbox is required.";
}
}
}
}
?>
<!-- Radio Buttons (Shared group name creates mutual exclusivity) -->
<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>
<!-- List Control (Using bracket arrays to support multiple item selection) -->
<label for="skills">Skills:</label>
<select id="skills" name="skills[]" multiple size="3">
<option value="PHP">PHP Development</option>
<option value="SQL">SQL Database</option>
<option value="HTML">HTML Structure</option>
</select><br><br>
What is JSON?
Ans:
8.
JavaScript Object Notation (JSON) is a lightweight, text-based, human-readable data interchange
format used to transmit structured key-value data structures between servers and client applications.
Differentiate between JavaScript and PHP.
Ans:
9.
JavaScript runs directly on the user's client-side browser to handle UI interaction logic, whereas PHP
is a server-side language that executes on backend web servers to process database storage queries.
What is DOM manipulation?
Ans:
10.
DOM manipulation is the process of using JavaScript APIs to add, remove, modify, or reorder HTML
elements, attributes, or CSS classes on a live web page
Part B
11. Explain JavaScript event handling with suitable examples.
Ans:
JavaScript event handling is the process of capturing and responding to user actions or
browser occurrences—such as clicks, keystrokes, or page loads—by executing specific code
blocks
You assign an event handler function directly to the object property of the DOM element using
JavaScript.
Drawback: You can attach only one function per event type; subsequent definitions overwrite
prior ones.
Javascript:
const btn = [Link]("myBtn");
[Link] = function() {
[Link]("DOM property execution!");
};
This approach attaches an event listener to an element without wiping existing listeners. It
supports multiple functions on a single event type and offers granular control over propagation
javascript
const btn = [Link]("myBtn");
[Link]("click", () => {
[Link]("Standard event listener executed!");
});
<form id="loginForm">
<input type="text" required>
<button type="submit">Submit</button>
</form>
<script>
const form = [Link]("#loginForm");
[Link]("submit", (e) => {
[Link](); // Stops page refresh
[Link]("Form validated via JS!");
});
</script>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
Variables are named containers used to store data values. Modern JavaScript offers three distinct
keywords for variable declaration, differentiated by reassignability and scoping rules
Example:
// var: Function-scoped, can be redeclared and reassigned
var city = "New York";
var city = "London";
2. Scope
Scope dictates the accessibility and visibility of your variables across different regions of your
code.
Global Scope
Variables declared outside any function or block live in the global scope. They are accessible
from absolutely anywhere in your script
Example:
const globalBonus = 500;
function calculateTotal() {
return 1000 + globalBonus; // Accessible inside functions
}
Function Scope
Variables declared using var inside a function belong strictly to that function. They cannot be
referenced outside of it
Example:
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
function greet() {
var message = "Hello Friend";
[Link](message); // Works
}
greet();
// [Link](message); // Throws ReferenceError
Block Scope
Introduced in ES6, variables declared with let and const inside curly braces {} (such as
ifstatements or loops) are isolated to that block.
Example:
if (true) {
var statusVar = "Visible";
let statusLet = "Hidden Outside";
}
[Link](statusVar); // Logs: "Visible"
// [Link](statusLet); // Throws ReferenceError
3. Functions
Functions are structured, reusable blocks of code engineered to perform isolated actions. They
can take inputs (parameters) and return an explicit output value.
Function Declaration
Traditional named functions that benefit from hoisting (can be called before they are written in
the file).
Example:
function multiply(a, b) {
return a * b; // Exits function and outputs value
}
const result = multiply(5, 4); // result is 20
Function Expression
Functions assigned directly to a variable. These are not hoisted and cannot be called before
definition.
Example:
A modern, concise syntax variant introduced in ES6 that lacks its own bindings to the this
keyword.
Example:
This unified example highlights how variables, scope, and functions interact natively in a
runtime context:
[Link](elementToRemove);
Changing Element Styles and Properties:
We can change the CSS style properties and other properties of the elements.
var element = [Link]("myElementId");
[Link] = "red";
Discuss client-side form validation with examples.
b)
Ans:
Client-side form validation is the process of checking user-entered data inside the web
browser before it is transmitted to a web server. Its primary goals are providing instant
feedback to users, improving data quality, and reducing server load by blocking
malformed requests
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<small class="error-msg" id="emailError"></small>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required minlength="6">
<small class="error-msg" id="passwordError"></small>
</div>
<button type="submit">Register</button>
</form>
[Link]('registrationForm').addEventListener('submit', function(event) {
// 1. Always halt initial submission to run evaluations
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
[Link]();
1. A user generates an event on the client. This results in a JavaScript technology call.
Code Implementation
A functional AJAX setup requires two primary components: the Frontend Client
(HTML/JavaScript) and the Backend Server Target (Data File/Script).
1. Frontend: [Link]
This file builds the basic layout and executes the asynchronous vanilla JavaScript logic
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple AJAX Application</title>
</head>
<body>
<h2>AJAX Demonstration</h2>
<!-- This div will be updated dynamically without refreshing -->
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
<div id="content-box">
<p>Original content loaded from the initial page load.</p>
</div>
<script>
function loadServerData() {
// Step 1: Instantiate the browser's built-in request object
var xhttp = new XMLHttpRequest();
// Step 3: Open the request connection (GET method, target URL, Asynchronous=true)
[Link]("GET", "[Link]", true);
// Step 4: Disconnect from the main process thread and send the request
[Link]();
}
</script>
M.A.M. SCHOOL OF ENGINEERING
(An Autonomous Institution)
Accredited by NAAC & Approved by AICTE, New Delhi
Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105. [Link]
</body>
</html>
2. Backend: [Link]
Create a plain text file named [Link] in the exact same directory as your HTML file. This acts
as the server-side resource containing the data you want to retrieve
<h4>Success!</h4>
<p>This paragraph was securely fetched from the web server via an AJAX request without
reloading the entire page.</p>