[Go to site: main page, start]

0% found this document useful (0 votes)
5 views39 pages

JavaScript Client-Side Scripting Lab

The document outlines a series of JavaScript and PHP tasks for web development, including client-side scripting with HTML forms, validation, dynamic content creation, and server-side scripting with PHP for handling user input. Each task is accompanied by example code snippets demonstrating how to implement the required functionality. The document serves as a practical guide for beginners to learn and apply essential web programming skills.

Uploaded by

phoneseller821
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views39 pages

JavaScript Client-Side Scripting Lab

The document outlines a series of JavaScript and PHP tasks for web development, including client-side scripting with HTML forms, validation, dynamic content creation, and server-side scripting with PHP for handling user input. Each task is accompanied by example code snippets demonstrating how to implement the required functionality. The document serves as a practical guide for beginners to learn and apply essential web programming skills.

Uploaded by

phoneseller821
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

💻 Lab 1: Client Side Scripting (JavaScript)

Lab 1.1: JavaScript Introduction


1. Task: Create an HTML page with a button. Write JavaScript code to display
"Hello, World!" in an alert box when the button is clicked.

<!DOCTYPE html>​
<html>​
<head>​
<title>Hello World</title>​
</head>​
<body>​
<button Me</button>​

<script>​
function showAlert() {​
alert("Hello, World!");​
}​
</script>​
</body>​
</html>​

2. Task: Build a form with input fields for name and email. Write JavaScript to
validate the email format when the form is submitted. Alert the user if the email
format is incorrect.

<!DOCTYPE html>​
<html>​
<head>​
<title>Form Validation</title>​
<style>​
.error { color: red; }​
</style>​
</head>​
<body>​
<form validateForm()">​
<label for="name">Name:</label>​
<input type="text" id="name" name="name" required><br><br>​

<label for="email">Email:</label>​
<input type="text" id="email" name="email" required>​
<p id="emailError" class="error"></p><br>​

<input type="submit" value="Submit">​
</form>​

<script>​
function validateForm() {​
const emailInput = [Link]("email").value;​
const errorElement =
[Link]("emailError");​

// Simple regex for email validation​
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; ​

if (![Link](emailInput)) {​
[Link] = "Error: Invalid email
format!";​
alert("Please correct the email format.");​
return false; // Prevent form submission​
} else {​
[Link] = ""; // Clear error​
alert("Form submitted successfully!");​
return true; // Allow form submission​
}​
}​
</script>​
</body>​
</html>​

3. Task: Develop a web page with a dropdown menu containing color options. Use
JavaScript to change the background color of the page dynamically when a
different color is selected from the dropdown.

<!DOCTYPE html>​
<html>​
<head>​
<title>Dynamic Background Color</title>​
</head>​
<body>​
<h1>Select a Background Color</h1>​
<select id="colorSelect" > <option value="white">White</option>​
<option value="lightgreen">Light Green</option>​
<option value="lightblue">Light Blue</option>​
<option value="lightcoral">Light Coral</option>​
</select>​

<script>​
function changeBackground() {​
const selectElement =
[Link]("colorSelect");​
const selectedColor = [Link];​
// Target the <body> element to change the page's
background​
[Link] = selectedColor; ​
}​
</script>​
</body>​
</html>​

Lab 1.2: Operators and Control Structures


1. Task: Implement a JavaScript function that takes a number as input and
determines if it's even or odd. Display the result on the webpage when a button is
clicked.

<!DOCTYPE html>​
<html>​
<head>​
<title>Even or Odd</title>​
</head>​
<body>​
<h1>Check Even or Odd</h1>​
<label for="numberInput">Enter a number:</label>​
<input type="number" id="numberInput"><br><br>​
<button > <p id="result"></p>​

<script>​
function checkEvenOdd() {​
const number =
parseInt([Link]("numberInput").value);​
const resultElement = [Link]("result");​

if (isNaN(number)) {​
[Link] = "Please enter a valid
number.";​
} else if (number % 2 === 0) {​
[Link] = `The number ${number} is
**Even**!`;​
} else {​
[Link] = `The number ${number} is
**Odd**!`;​
}​
}​
</script>​
</body>​
</html>​

2. Task: Write JavaScript code to create a simple calculator that performs


addition, subtraction, multiplication, and division operations based on user input.

<!DOCTYPE html>​
<html>​
<head>​
<title>Simple Calculator</title>​
</head>​
<body>​
<h1>Simple Calculator</h1>​
<label for="num1">Number 1:</label>​
<input type="number" id="num1"><br><br>​

<label for="num2">Number 2:</label>​
<input type="number" id="num2"><br><br>​

<label for="operation">Operation:</label>​
<select id="operation">​
<option value="add">+</option>​
<option value="subtract">-</option>​
<option value="multiply">*</option>​
<option value="divide">/</option>​
</select><br><br>​

<button > <p id="calcResult">Result:</p>​

<script>​
function calculate() {​
const num1 =
parseFloat([Link]("num1").value);​
const num2 =
parseFloat([Link]("num2").value);​
const operation =
[Link]("operation").value;​
let result;​

if (isNaN(num1) || isNaN(num2)) {​
[Link]("calcResult").textContent =
"Result: Invalid input.";​
return;​
}​

switch (operation) {​
case 'add':​
result = num1 + num2;​
break;​
case 'subtract':​
result = num1 - num2;​
break;​
case 'multiply':​
result = num1 * num2;​
break;​
case 'divide':​
if (num2 === 0) {​
result = "Cannot divide by zero!";​
} else {​
result = num1 / num2;​
}​
break;​
default:​
result = "Invalid operation.";​
}​

[Link]("calcResult").textContent =
`Result: ${result}`;​
}​
</script>​
</body>​
</html>​

3. Task: Create a JavaScript array of numbers. Use JavaScript to find and display
the largest number in the array when a button is clicked.

<!DOCTYPE html>​
<html>​
<head>​
<title>Find Largest Number</title>​
</head>​
<body>​
<h1>Largest Number Finder</h1>​
<p>The array is: **[12, 45, 6, 88, 23, 71]**</p>​
<button Largest</button>​
<p id="largestResult"></p>​

<script>​
const numbers = [12, 45, 6, 88, 23, 71];​

function findLargest() {​
const largest = [Link](...numbers); // Use spread
operator and [Link]()​
// Alternative using a loop:​
/*​
let largest = numbers[0];​
for (let i = 1; i < [Link]; i++) {​
if (numbers[i] > largest) {​
largest = numbers[i];​
}​
}​
*/​
[Link]("largestResult").textContent =
`The largest number in the array is: **${largest}**`;​
}​
</script>​
</body>​
</html>​

Lab 1.3: Document Object Model (DOM) Manipulation


1. Task: Develop a webpage with a button. Write JavaScript to dynamically create
and add a new paragraph element to the page when the button is clicked.

<!DOCTYPE html>​
<html>​
<head>​
<title>DOM Manipulation - Add Element</title>​
</head>​
<body>​
<div id="content">​
<p>This is the original paragraph.</p>​
</div>​
<button New Paragraph</button>​

<script>​
let count = 1;​
function addParagraph() {​
// 1. Create the new element​
const newParagraph = [Link]("p");​
// 2. Set its content​
[Link] = `Dynamically created paragraph
#${count}`;​
// 3. Append it to an existing container element​

[Link]("content").appendChild(newParagraph);​
count++;​
}​
</script>​
</body>​
</html>​

2. Task: Build a form with input fields for first name, last name, and age. Use
JavaScript to validate the form fields and display appropriate error messages
beside each field.

(This is similar to Lab 1.1, Task 2, but requires inline error messages.)
<!DOCTYPE html>​
<html>​
<head>​
<title>DOM Manipulation - Inline Validation</title>​
<style>​
.error { color: red; font-size: 0.8em; }​
.form-group { margin-bottom: 10px; }​
</style>​
</head>​
<body>​
<form validateUserDetails()">​
<div class="form-group">​
<label for="firstName">First Name:</label>​
<input type="text" id="firstName" name="firstName">​
<span id="firstNameError" class="error"></span>​
</div>​

<div class="form-group">​
<label for="lastName">Last Name:</label>​
<input type="text" id="lastName" name="lastName">​
<span id="lastNameError" class="error"></span>​
</div>​

<div class="form-group">​
<label for="age">Age:</label>​
<input type="number" id="age" name="age">​
<span id="ageError" class="error"></span>​
</div>​

<input type="submit" value="Submit">​
</form>​

<script>​
function validateUserDetails() {​
let isValid = true;​

// Validate First Name (must not be empty)​
const fName =
[Link]("firstName").[Link]();​
const fNameError =
[Link]("firstNameError");​
if (fName === "") {​
[Link] = "First name is required.";​
isValid = false;​
} else {​
[Link] = "";​
}​

// Validate Last Name (must not be empty)​
const lName =
[Link]("lastName").[Link]();​
const lNameError =
[Link]("lastNameError");​
if (lName === "") {​
[Link] = "Last name is required.";​
isValid = false;​
} else {​
[Link] = "";​
}​

// Validate Age (must be a number > 0)​
const age =
parseInt([Link]("age").value);​
const ageError = [Link]("ageError");​
if (isNaN(age) || age <= 0) {​
[Link] = "Age must be a positive
number.";​
isValid = false;​
} else {​
[Link] = "";​
}​

if (isValid) {​
alert("Form is valid and ready to submit!");​
}​
return isValid; // Return false to stop submission if
invalid​
}​
</script>​
</body>​
</html>​

3. Task: Create an HTML table with some data. Write JavaScript to sort the table
rows alphabetically based on a specific column when a button is clicked.
<!DOCTYPE html>​
<html>​
<head>​
<title>DOM Manipulation - Table Sorting</title>​
</head>​
<body>​
<h1>Sortable Table</h1>​
<button by Name</button>​
<button by Country</button>​

<table id="myTable" border="1">​
<thead>​
<tr>​
<th>Name</th>​
<th>Country</th>​
</tr>​
</thead>​
<tbody>​
<tr><td>Charlie</td><td>USA</td></tr>​
<tr><td>Alice</td><td>Canada</td></tr>​
<tr><td>David</td><td>Germany</td></tr>​
<tr><td>Bob</td><td>France</td></tr>​
</tbody>​
</table>​

<script>​
function sortTable(columnIndex) {​
const table = [Link]("myTable");​
const tbody = [Link]("tbody");​
const rows = [Link]([Link]("tr")); //
Convert NodeList to Array​

// Sort the array of rows​
[Link]((a, b) => {​
// Get the cell content for the specified column index
(0-based)​
const aText =
[Link][columnIndex].[Link]().toUpperCase();​
const bText =
[Link][columnIndex].[Link]().toUpperCase();​

if (aText < bText) return -1;​
if (aText > bText) return 1;​
return 0; // names are equal​
});​

// Re-append the sorted rows to the table body​
[Link](row => [Link](row));​
}​
</script>​
</body>​
</html>​

🚀 Lab 2: Server Scripting with Database Connectivity


To execute these tasks, you'll need a local web server environment (like
XAMPP/WAMP/MAMP) with PHP and MySQL running. The PHP files must be placed in the
server's document root (e.g., htdocs in XAMPP).

Lab 2.1: PHP Introduction and Syntax


1. Task: Create a PHP script that takes user input (name and email) from a form
and displays it on the webpage.

File 1: input_form.html
<!DOCTYPE html>​
<html>​
<head>​
<title>PHP Form Input</title>​
</head>​
<body>​
<form method="POST" action="display_data.php">​
<label for="name">Name:</label>​
<input type="text" id="name" name="userName" required><br><br>​

<label for="email">Email:</label>​
<input type="email" id="email" name="userEmail"
required><br><br>​

<input type="submit" value="Submit">​
</form>​
</body>​
</html>​

File 2: display_data.php
<!DOCTYPE html>​
<html>​
<head>​
<title>Display Data</title>​
</head>​
<body>​
<?php​
// Check if the form was submitted using the POST method​
if ($_SERVER["REQUEST_METHOD"] == "POST") {​
// Retrieve the data from the $_POST superglobal array​
$name = htmlspecialchars($_POST['userName']);​
$email = htmlspecialchars($_POST['userEmail']);​

echo "<h2>Submitted Information:</h2>";​
echo "<p>Name: **$name**</p>";​
echo "<p>Email: **$email**</p>";​
} else {​
echo "<p>No data submitted.</p>";​
}​
?>​
</body>​
</html>​

2. Task: Create a PHP script to generate a random password when a button is


clicked and display it on the webpage.

File 1: password_generator.php
<!DOCTYPE html>​
<html>​
<head>​
<title>Random Password Generator</title>​
</head>​
<body>​
<h1>Random Password Generator</h1>​
<form method="POST" action="">​
<input type="submit" name="generate" value="Generate
Password">​
</form>​

<?php​
function generateRandomPassword($length = 10) {​
$chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&
*()';​
$password = '';​
$max_index = strlen($chars) - 1;​

for ($i = 0; $i < $length; $i++) {​
// Select a random character from the string​
$password .= $chars[rand(0, $max_index)]; ​
}​
return $password;​
}​

// Check if the button was clicked​
if (isset($_POST['generate'])) {​
$newPassword = generateRandomPassword(12); // Generate a
12-character password​
echo "<br><h3>Generated Password:</h3>";​
echo "<p style='font-weight: bold; color:
green;'>$newPassword</p>";​
}​
?>​
</body>​
</html>​

3. Task: Develop a PHP program that calculates the factorial of a number entered
by the user and displays the result.

File 1: factorial_calculator.php
<!DOCTYPE html>​
<html>​
<head>​
<title>Factorial Calculator</title>​
</head>​
<body>​
<h1>Factorial Calculator</h1>​
<form method="POST" action="">​
<label for="number">Enter a non-negative integer:</label>​
<input type="number" id="number" name="number" required
min="0"><br><br>​
<input type="submit" value="Calculate Factorial">​
</form>​

<?php​
function calculateFactorial($n) {​
if (!is_numeric($n) || $n < 0 || $n != floor($n)) {​
return "Invalid input. Please enter a non-negative
integer.";​
}​

if ($n == 0) {​
return 1;​
} else {​
$factorial = 1;​
for ($i = 1; $i <= $n; $i++) {​
$factorial *= $i;​
}​
return $factorial;​
}​
}​

// Check if the form was submitted and the 'number' is set​
if (isset($_POST['number'])) {​
$inputNumber = $_POST['number'];​
$result = calculateFactorial($inputNumber);​

echo "<br><h3>Result:</h3>";​
echo "<p>The factorial of **$inputNumber** is
**$result**.</p>";​
}​
?>​
</body>​
</html>​

Lab 2.2: MySQL Basics


(Before starting, ensure you have a database named patnisthadb and a table named students
with the columns id, name, age, and email.)
Database Setup (SQL commands):
CREATE DATABASE patnisthadb;​
USE patnisthadb;​
CREATE TABLE students (​
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,​
name VARCHAR(50) NOT NULL,​
age INT(3),​
email VARCHAR(50)​
);​

1. Task: Set up a MySQL database with a table to store student information (name,
age, email). Write PHP code to insert new records into the table from a form.

File: insert_student.php
<?php​
// ** 1. Database Configuration **​
$servername = "localhost";​
$username = "root"; // Default XAMPP/WAMP user​
$password = ""; // Default XAMPP/WAMP password​
$dbname = "patnisthadb";​

// ** 2. Handle Form Submission **​
$message = "";​
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['name'])) {​

$name = htmlspecialchars($_POST['name']);​
$age = htmlspecialchars($_POST['age']);​
$email = htmlspecialchars($_POST['email']);​

// Create connection​
$conn = new mysqli($servername, $username, $password, $dbname);​

// Check connection​
if ($conn->connect_error) {​
die("Connection failed: " . $conn->connect_error);​
}​

// SQL to insert data (using prepared statements for security)​
$stmt = $conn->prepare("INSERT INTO students (name, age, email)
VALUES (?, ?, ?)");​
$stmt->bind_param("sis", $name, $age, $email); // "s" = string,
"i" = integer​

if ($stmt->execute()) {​
$message = "<span style='color: green;'>New record created
successfully.</span>";​
} else {​
$message = "<span style='color: red;'>Error: " . $stmt->error
. "</span>";​
}​

$stmt->close();​
$conn->close();​
}​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>Insert Student Record</title>​
</head>​
<body>​
<h1>Add New Student</h1>​
<?php echo $message; ?>​
<form method="POST" action="">​
<label for="name">Name:</label>​
<input type="text" id="name" name="name" required><br><br>​

<label for="age">Age:</label>​
<input type="number" id="age" name="age" required
min="1"><br><br>​

<label for="email">Email:</label>​
<input type="email" id="email" name="email"><br><br>​

<input type="submit" value="Insert Record">​
</form>​
</body>​
</html>​

2. Task: Write PHP code to retrieve and display student records from the MySQL
database in a tabular format on a webpage.

File: view_students.php
<?php​
$servername = "localhost";​
$username = "root";​
$password = "";​
$dbname = "patnisthadb";​

// Create connection​
$conn = new mysqli($servername, $username, $password, $dbname);​

// Check connection​
if ($conn->connect_error) {​
die("Connection failed: " . $conn->connect_error);​
}​

// SQL to select data​
$sql = "SELECT id, name, age, email FROM students";​
$result = $conn->query($sql);​

?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>View Student Records</title>​
<style>​
table, th, td { border: 1px solid black; border-collapse:
collapse; padding: 8px; }​
th { background-color: #f2f2f2; }​
</style>​
</head>​
<body>​
<h1>Student Records</h1>​

<?php​
if ($result->num_rows > 0) {​
// Start the table​
echo "<table>";​
echo
"<thead><tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr></t
head>";​
echo "<tbody>";​

// Output data of each row​
while($row = $result->fetch_assoc()) {​
echo "<tr>";​
echo "<td>" . $row["id"] . "</td>";​
echo "<td>" . $row["name"] . "</td>";​
echo "<td>" . $row["age"] . "</td>";​
echo "<td>" . $row["email"] . "</td>";​
echo "</tr>";​
}​

echo "</tbody>";​
echo "</table>";​
} else {​
echo "<p>0 results found in the table.</p>";​
}​

$conn->close();​
?>​

</body>​
</html>​

3. Task: Implement a PHP script to update the email address of a student in the
MySQL database based on their ID.

File: update_email.php
<?php​
$servername = "localhost";​
$username = "root";​
$password = "";​
$dbname = "patnisthadb";​

$message = "";​

if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['studentId'])) {​

$studentId = htmlspecialchars($_POST['studentId']);​
$newEmail = htmlspecialchars($_POST['newEmail']);​

// Create connection​
$conn = new mysqli($servername, $username, $password, $dbname);​

if ($conn->connect_error) {​
die("Connection failed: " . $conn->connect_error);​
}​

// SQL to update data (using prepared statements)​
$stmt = $conn->prepare("UPDATE students SET email = ? WHERE id =
?");​
$stmt->bind_param("si", $newEmail, $studentId);​

if ($stmt->execute()) {​
if ($stmt->affected_rows > 0) {​
$message = "<span style='color: green;'>Record with ID
**$studentId** updated successfully.</span>";​
} else {​
$message = "<span style='color: orange;'>No record found
with ID **$studentId** or email is the same.</span>";​
}​
} else {​
$message = "<span style='color: red;'>Error updating record: "
. $stmt->error . "</span>";​
}​

$stmt->close();​
$conn->close();​
}​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>Update Student Email</title>​
</head>​
<body>​
<h1>Update Student Email</h1>​
<?php echo $message; ?>​
<form method="POST" action="">​
<label for="studentId">Student ID to Update:</label>​
<input type="number" id="studentId" name="studentId"
required><br><br>​

<label for="newEmail">New Email Address:</label>​
<input type="email" id="newEmail" name="newEmail"
required><br><br>​

<input type="submit" value="Update Email">​
</form>​
</body>​
</html>​
🍪 Lab 2.3: PHP Sessions and Cookies
🔐 Lab 2: Advanced Server Side Scripting
Lab 2.3: PHP Sessions and Cookies
1. Task: Create a login form using PHP. Implement session management to
authenticate users and redirect them to a welcome page upon successful login.

File 1: [Link] (Login Form & Authentication)


<?php​
session_start();​

// Hardcoded Credentials (Replace with database logic in a real app)​
$valid_username = "admin";​
$valid_password = "password123";​

$message = "";​

if ($_SERVER["REQUEST_METHOD"] == "POST") {​
$username = $_POST['username'] ?? '';​
$password = $_POST['password'] ?? '';​

// Simple validation and authentication​
if ($username === $valid_username && $password ===
$valid_password) {​
// Successful Login: Set session variables​
$_SESSION['loggedin'] = true;​
$_SESSION['username'] = $username;​
// Redirect to the welcome page​
header("Location: [Link]");​
exit;​
} else {​
$message = "<p style='color: red;'>Invalid username or
password.</p>";​
}​
}​
?>​
<!DOCTYPE html>​
<html>​
<head>​
<title>Login Page</title>​
</head>​
<body>​
<h1>User Login</h1>​
<?php echo $message; ?>​
<form method="POST" action="[Link]">​
<label for="username">Username:</label>​
<input type="text" id="username" name="username"
required><br><br>​
<label for="password">Password:</label>​
<input type="password" id="password" name="password"
required><br><br>​
<input type="submit" value="Login">​
</form>​
</body>​
</html>​

File 2: [Link] (Protected Page)


<?php​
session_start();​

// Check if the user is logged in​
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {​
// If not logged in, redirect to login page​
header("Location: [Link]");​
exit;​
}​

$username = $_SESSION['username'];​
?>​
<!DOCTYPE html>​
<html>​
<head>​
<title>Welcome</title>​
</head>​
<body>​
<h1>Welcome, <?php echo htmlspecialchars($username); ?>!</h1>​
<p>You have successfully logged in using PHP Sessions.</p>​
<p><a href="[Link]">Logout</a></p>​
</body>​
</html>​

File 3: [Link] (Logout Script)


<?php​
session_start();​
// Unset all session variables​
$_SESSION = array();​
// Destroy the session​
session_destroy();​
// Redirect to login page​
header("Location: [Link]");​
exit;​
?>​

2. Task: Write PHP code to set a cookie containing the user's preferred language
choice and display a greeting message in the chosen language on subsequent
visits.

File: language_selector.php
<?php​
$default_lang = 'en';​
$selected_lang = $default_lang;​
$message = "";​

$languages = [​
'en' => "Hello! Welcome to our site.",​
'fr' => "Bonjour! Bienvenue sur notre site.",​
'es' => "¡Hola! Bienvenido a nuestro sitio.",​
];​

// Handle form submission to set the cookie​
if (isset($_POST['language'])) {​
$selected_lang = $_POST['language'];​
// Set the cookie to expire in 30 days​
setcookie('user_language', $selected_lang, time() + (86400 * 30),
"/"); ​
$message = "Language preference saved successfully!";​
} ​
// Check for existing cookie​
elseif (isset($_COOKIE['user_language'])) {​
$selected_lang = $_COOKIE['user_language'];​
$message = "Your saved language preference is **" .
strtoupper($selected_lang) . "**.";​
}​

// Get the greeting message based on the determined language​
$greeting = $languages[$selected_lang] ?? $languages[$default_lang];​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>Language Preference Cookie</title>​
</head>​
<body>​
<h1>Language Preference</h1>​

<p style="font-weight: bold;"><?php echo $message; ?></p>​

<h2>Greeting:</h2>​
<p style="color: blue; font-size: 1.2em;">**<?php echo $greeting;
?>**</p>​

<form method="POST" action="">​
<label for="language">Select Language:</label>​
<select id="language" name="language">​
<option value="en" <?php echo ($selected_lang == 'en' ?
'selected' : ''); ?>>English</option>​
<option value="fr" <?php echo ($selected_lang == 'fr' ?
'selected' : ''); ?>>French</option>​
<option value="es" <?php echo ($selected_lang == 'es' ?
'selected' : ''); ?>>Spanish</option>​
</select>​
<input type="submit" value="Save Preference">​
</form>​
</body>​
</html>​

3. Task: Develop a PHP script to track and display the number of times a user has
visited a webpage using cookies.

File: visit_tracker.php
<?php​
$visits = 1; // Default visit count​

// Check if the 'visit_count' cookie exists​
if (isset($_COOKIE['visit_count'])) {​
// Retrieve the current count​
$visits = $_COOKIE['visit_count'];​
// Increment for the current visit​
$visits++; ​
}​

// Set or update the cookie. Expires in 1 year.​
$expiry_time = time() + (86400 * 365); // 86400 seconds = 1 day​
setcookie('visit_count', $visits, $expiry_time, "/"); ​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>Visit Counter Cookie</title>​
</head>​
<body>​
<h1>Visit Counter</h1>​

<p>According to your browser's cookies, this is your:</p>​

<?php​
echo "<h2 style='color: green;'>**" . number_format($visits) .
"** visit(s) to this page!</h2>";​
?>​

<p>Try refreshing the page to see the counter increase.</p>​
<p style="font-size: 0.9em; color: gray;">​
(Note: The cookie will last for 1 year unless cleared by your
browser.)​
</p>​
</body>​
</html>​

📐 Lab 3.1: Object-Oriented Programming in PHP


1. Task: Define a PHP class representing a product with properties like name,
price, and description. Create instances of the class and display product details
on the webpage.

File: product_oop.php
<?php​
class Product {​
// Properties (Attributes)​
public $name;​
public $price;​
public $description;​

// Constructor method​
public function __construct($name, $price, $description) {​
$this->name = $name;​
$this->price = $price;​
$this->description = $description;​
}​

// Method (Behavior)​
public function displayDetails() {​
echo "<div>";​
echo "<h3>{$this->name}</h3>";​
echo "<p><strong>Price:</strong> $" .
number_format($this->price, 2) . "</p>";​
echo "<p><strong>Description:</strong>
{$this->description}</p>";​
echo "</div>";​
}​
}​

// Create instances (Objects) of the Product class​
$laptop = new Product("UltraBook Pro", 1299.99, "A lightweight,
high-performance laptop for professionals.");​
$mouse = new Product("Ergo Wireless Mouse", 25.50, "Ergonomic design
with silent clicks.");​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>PHP OOP - Products</title>​
</head>​
<body>​
<h1>Our Products</h1>​
<?php​
// Call the displayDetails method on each object​
$laptop->displayDetails();​
$mouse->displayDetails();​
?>​
</body>​
</html>​

2. Task: Implement inheritance in PHP by creating a base class "Shape" and


derived classes like "Circle" and "Rectangle". Write PHP code to calculate the
area and perimeter of each shape.

File: shape_inheritance.php
<?php​
// Base Class​
abstract class Shape {​
abstract public function calculateArea(): float;​
abstract public function calculatePerimeter(): float;​

public function displayCalculations() {​
echo "<div>";​
echo "<h4>" . get_class($this) . "</h4>";​
echo "<p>Area: **" . number_format($this->calculateArea(), 2)
. "**</p>";​
echo "<p>Perimeter: **" .
number_format($this->calculatePerimeter(), 2) . "**</p>";​
echo "</div>";​
}​
}​

// Derived Class 1​
class Circle extends Shape {​
private $radius;​
const PI = 3.14159;​

public function __construct($radius) {​
$this->radius = $radius;​
}​

public function calculateArea(): float {​
return self::PI * $this->radius * $this->radius;​
}​

public function calculatePerimeter(): float {​
return 2 * self::PI * $this->radius; // Circumference​
}​
}​

// Derived Class 2​
class Rectangle extends Shape {​
private $width;​
private $height;​

public function __construct($width, $height) {​
$this->width = $width;​
$this->height = $height;​
}​

public function calculateArea(): float {​
return $this->width * $this->height;​
}​

public function calculatePerimeter(): float {​
return 2 * ($this->width + $this->height);​
}​
}​

// Create instances​
$myCircle = new Circle(5.0);​
$myRectangle = new Rectangle(10.0, 4.5);​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>PHP OOP - Inheritance & Shapes</title>​
</head>​
<body>​
<h1>Shape Calculations using Inheritance</h1>​
<?php​
$myCircle->displayCalculations();​
$myRectangle->displayCalculations();​
?>​
</body>​
</html>​

3. Task: Create a PHP program to handle exceptions for file operations such as
reading and writing files. Display appropriate error messages when exceptions
occur.

File: file_exception_handler.php
<?php​
$filename = "test_file.txt";​
$output = "";​

function readFileContent($file) {​
if (!file_exists($file)) {​
// Throw an exception if the file doesn't exist​
throw new Exception("File Not Found: The file **'$file'** does
not exist.", 1001);​
}​

if (!is_readable($file)) {​
// Throw an exception if the file is not readable​
throw new Exception("Permission Denied: Cannot read file
**'$file'**.", 1002);​
}​

$content = file_get_contents($file);​
return "File **'$file'** read successfully. Content length: " .
strlen($content) . " bytes.";​
}​

// ----------------------------------------------------​
// Example 1: Trying to read a file that exists (should succeed)​
// Create the file first for the test to pass​
file_put_contents($filename, "This is test content.");​

try {​
$output .= "<h3>Attempt 1 (Success):</h3>";​
$output .= "<p style='color: green;'>" .
readFileContent($filename) . "</p>";​
} catch (Exception $e) {​
$output .= "<h3>Attempt 1 (Failure):</h3>";​
$output .= "<p style='color: red;'>Caught Exception: **Code
{$e->getCode()}** - {$e->getMessage()}</p>";​
}​

// Example 2: Trying to read a file that does NOT exist (should fail)​
try {​
$output .= "<h3>Attempt 2 (Failure):</h3>";​
$output .= "<p>" . readFileContent("non_existent_file.log") .
"</p>";​
} catch (Exception $e) {​
$output .= "<h3>Attempt 2 (Failure):</h3>";​
$output .= "<p style='color: red;'>Caught Exception: **Code
{$e->getCode()}** - {$e->getMessage()}</p>";​
}​
?>​

<!DOCTYPE html>​
<html>​
<head>​
<title>PHP Exception Handling</title>​
</head>​
<body>​
<h1>File Operation Exception Handling</h1>​
<?php echo $output; ?>​
</body>​
</html>​

🌐 Lab 3.2: AJAX Implementation with PHP


1. Task: Develop an AJAX-based PHP application to fetch and display real-time
weather data from an API on a webpage without refreshing the page.

(Note: This requires a publicly available Weather API key, e.g., from OpenWeatherMap. For the
lab, we'll demonstrate the AJAX structure and a dummy data fetch.)
File 1: [Link] (Front-end with AJAX)
<!DOCTYPE html>​
<html>​
<head>​
<title>AJAX Weather App</title>​
</head>​
<body>​
<h1>Real-Time Weather Fetch</h1>​
<label for="city">Enter City:</label>​
<input type="text" id="city" value="London">​
<button Weather</button>​

<div id="weather-display" style="border: 1px solid #ccc;
margin-top: 20px; padding: 10px;">​
Click 'Get Weather' to load data...​
</div>​

<script>​
function fetchWeather() {​
const city = [Link]('city').value;​
const display =
[Link]('weather-display');​
[Link] = 'Loading weather data for **' + city +
'...**';​

// 1. Create a new XMLHttpRequest object​
const xhr = new XMLHttpRequest();​

// 2. Configure the request: GET request to the PHP
backend​
[Link]('GET', 'get_weather.php?city=' +
encodeURIComponent(city), true);​

// 3. Define the function to run when the request
completes​
[Link] = function() {​
// Check if request is done (4) and successful (200)​
if ([Link] === 4 && [Link] === 200) {​
// Update the DOM with the response data​
[Link] = [Link];​
} else if ([Link] === 4) {​
// Handle errors​
[Link] = 'Error fetching data. Status:
' + [Link];​
}​
};​

// 4. Send the request​
[Link]();​
}​
</script>​
</body>​
</html>​

File 2: get_weather.php (PHP Backend Script)


<?php​
// Set content type to HTML (or JSON if needed)​
header('Content-Type: text/html');​

// API Key and City (use a real key in production)​
$api_key = "YOUR_OPENWEATHERMAP_API_KEY"; // Replace with your actual
key​
$city = $_GET['city'] ?? 'Default City'; // Get city from AJAX request​

// ** DUMMY DATA FOR LAB DEMONSTRATION **​
if ($city == "London") {​
$temp = 15;​
$desc = "Cloudy with chance of rain.";​
} elseif ($city == "Paris") {​
$temp = 22;​
$desc = "Sunny and clear skies.";​
} else {​
$temp = rand(10, 30);​
$desc = "Variable conditions.";​
}​

// ** Real API Call Structure (Commented out) **​
/*​
$url =
"[Link]
key}&units=metric";​
$data = @file_get_contents($url);​

if ($data === false) {​
echo "Could not connect to weather service.";​
} else {​
$weather = json_decode($data, true);​
if ($weather && $weather['cod'] == 200) {​
$temp = $weather['main']['temp'];​
$desc = $weather['weather'][0]['description'];​
} else {​
echo "City not found or API error.";​
exit;​
}​
}​
*/​
// Output the result to be displayed by AJAX​
echo "<h2>Weather in **" . htmlspecialchars($city) . "**</h2>";​
echo "<p>Temperature: **{$temp}°C**</p>";​
echo "<p>Description: **{$desc}**</p>";​
echo "<p style='font-size:0.8em; color:gray;'>Data fetched at: " .
date("H:i:s") . "</p>";​

?>​
2. Task: Write PHP code to dynamically load content from a MySQL database
using AJAX when a user clicks on a button or link.

(Pre-requisite: Assume you have a products table with columns id and name.)
File 1: ajax_db_loader.html (Front-end with Button)
<!DOCTYPE html>​
<html>​
<head>​
<title>AJAX Database Loader</title>​
</head>​
<body>​
<h1>AJAX Database Loader</h1>​
<button Products</button>​

<div id="product-list" style="margin-top: 20px;">​
Click the button to load product data from the database...​
</div>​

<script>​
function loadProducts() {​
const display = [Link]('product-list');​
[Link] = 'Connecting to database and fetching
data...';​

const xhr = new XMLHttpRequest();​
[Link]('GET', 'fetch_products.php', true);​

[Link] = function() {​
if ([Link] === 4 && [Link] === 200) {​
[Link] = [Link];​
} else if ([Link] === 4) {​
[Link] = 'Error loading data: ' +
[Link];​
}​
};​
[Link]();​
}​
</script>​
</body>​
</html>​

File 2: fetch_products.php (PHP Backend for DB Interaction)


<?php​
// Database Configuration​
$servername = "localhost";​
$username = "root";​
$password = "";​
$dbname = "patnisthadb"; // Use the same DB name from Lab 2.2​

// Create connection​
$conn = new mysqli($servername, $username, $password, $dbname);​

if ($conn->connect_error) {​
// If connection fails, output the error message directly to the
AJAX response​
die("<p style='color:red;'>Connection Failed: " .
$conn->connect_error . "</p>");​
}​

$sql = "SELECT id, name FROM students LIMIT 5"; // Using 'students'
table from Lab 2.2​
$result = $conn->query($sql);​

$output = "<h2>Recently Loaded Products (Students):</h2>";​
if ($result->num_rows > 0) {​
$output .= "<ul>";​
// Output data of each row​
while($row = $result->fetch_assoc()) {​
$output .= "<li>ID: {$row['id']} - Name: **" .
htmlspecialchars($row['name']) . "**</li>";​
}​
$output .= "</ul>";​
} else {​
$output .= "<p>0 results found.</p>";​
}​

$conn->close();​
echo $output; // Send the final HTML output back to the AJAX request​
?>​

3. Task: Implement form validation using AJAX and PHP to check if a username is
already taken in a database when a user tries to register.

File 1: [Link] (Front-end with AJAX on Blur)


<!DOCTYPE html>​
<html>​
<head>​
<title>AJAX Username Check</title>​
</head>​
<body>​
<h1>User Registration</h1>​
<form id="registrationForm">​
<label for="username">Username:</label>​
<input type="text" id="username" name="username"
> <span id="username-status" style="margin-left: 10px;"></span>​
<br><br>​

<label for="email">Email:</label>​
<input type="email" id="email" name="email" required>​
<br><br>​

<input type="submit" value="Register" id="register-btn"
disabled>​
</form>​

<script>​
function checkUsername() {​
const username =
[Link]('username').value;​
const status = [Link]('username-status');​
const button = [Link]('register-btn');​

if ([Link] < 3) {​
[Link] = '<span style="color:red;">Username
too short.</span>';​
[Link] = true;​
return;​
}​

[Link] = '<span style="color:orange;">Checking
availability...</span>';​

const xhr = new XMLHttpRequest();​
[Link]('GET', 'check_username.php?username=' +
encodeURIComponent(username), true);​

[Link] = function() {​
if ([Link] === 4 && [Link] === 200) {​
const response = [Link]();​
if (response === 'taken') {​
[Link] = '<span
style="color:red;">Username **is taken**.</span>';​
[Link] = true; // Disable submission​
} else {​
[Link] = '<span
style="color:green;">Username **is available**!</span>';​
[Link] = false; // Enable submission​
}​
} else if ([Link] === 4) {​
[Link] = '<span
style="color:gray;">Error connecting to server.</span>';​
[Link] = true;​
}​
};​
[Link]();​
}​
</script>​
</body>​
</html>​

File 2: check_username.php (PHP Backend for AJAX Check)


<?php​
// Database Configuration​
$servername = "localhost";​
$username = "root";​
$password = "";​
$dbname = "patnisthadb";​

// Get the username from the AJAX GET request​
$check_username = $_GET['username'] ?? '';​

// Create connection​
$conn = new mysqli($servername, $username, $password, $dbname);​

if ($conn->connect_error) {​
die("error"); // Simple error response​
}​

// Prepare statement to check if username (name) exists in the
students table​
$stmt = $conn->prepare("SELECT COUNT(*) FROM students WHERE name =
?");​
$stmt->bind_param("s", $check_username);​
$stmt->execute();​
$stmt->bind_result($count);​
$stmt->fetch();​
$stmt->close();​
$conn->close();​

// Output 'taken' or 'available'​
if ($count > 0) {​
echo "taken";​
} else {​
echo "available";​
}​
?>​
Lab 3.3: JQuery Usage and Manipulation
1. Task: Use jQuery to create a slideshow on a webpage with images and
navigation buttons for previous and next slides.

(This requires including the jQuery library in the HTML.) File: jquery_slideshow.html
<!DOCTYPE html>​
<html>​
<head>​
<title>jQuery Slideshow</title>​
<style>​
.slideshow-container { position: relative; max-width: 600px;
margin: auto; }​
.mySlides { display: none; } /* Hide all slides by default */​
.slide-img { width: 100%; height: auto; }​
.prev, .next { cursor: pointer; position: absolute; top: 50%;
width: auto; padding: 16px; margin-top: -22px; color: white;
font-weight: bold; font-size: 18px; transition: 0.6s ease;
border-radius: 0 3px 3px 0; user-select: none; background-color:
rgba(0,0,0,0.8); }​
.next { right: 0; border-radius: 3px 0 0 3px; }​
</style>​
<script
src="[Link]
></script>​
</head>​
<body>​
<h1>jQuery Image Slideshow</h1>​

<div class="slideshow-container">​
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 1"></div>​
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 2"></div>​
<div class="mySlides fade"><img src="[Link]"
class="slide-img" alt="Image 3"></div>​

<a class="prev" > <a class="next" > </div>​

<script>​
let slideIndex = 1;​

// Function to show a specific slide​
function showSlides(n) {​
const $slides = $('.mySlides'); // Select all slides using
jQuery​

if (n > $[Link]) { slideIndex = 1 } // Wrap around
to the first slide​
if (n < 1) { slideIndex = $[Link] } // Wrap around
to the last slide​

$[Link](); // Hide all slides​
$($slides[slideIndex - 1]).show(); // Show the current
slide​
}​

// Function to change the slide index​
function plusSlides(n) {​
showSlides(slideIndex += n);​
}​

// Initialize the slideshow when the document is ready​
$(document).ready(function() {​
showSlides(slideIndex);​
});​
</script>​
</body>​
</html>​

2. Task: Use jQuery UI widget for a date picker to select a date from a calendar
and display it in a text input field.

(This requires including jQuery, jQuery UI CSS, and jQuery UI JS.)


File: jquery_datepicker.html
<!DOCTYPE html>​
<html>​
<head>​
<title>jQuery UI Date Picker</title>​
<link rel="stylesheet"
href="[Link]
<style>​
/* Optional custom styling */​
input[type="text"] { padding: 8px; border: 1px solid #ccc;
font-size: 16px; }​
</style>​
<script
src="[Link]
<script
src="[Link]
</head>​
<body>​
<h1>jQuery UI Date Picker</h1>​

<label for="datepicker">Select a Date:</label>​
<input type="text" id="datepicker" readonly>​

<script>​
$(function() {​
// Initialize the Datepicker widget on the input field​
$("#datepicker").datepicker({​
dateFormat: "dd/mm/yy", // Custom date format​
changeMonth: true, // Allow month change​
changeYear: true // Allow year change​
});​
});​
</script>​
</body>​
</html>​

3. Task: Write jQuery code to hide/show HTML elements based on user


interactions, such as clicking on a button or checkbox.

File: jquery_hide_show.html
<!DOCTYPE html>​
<html>​
<head>​
<title>jQuery Hide/Show</title>​
<script
src="[Link]
></script>​
<style>​
#secret-message { ​
background-color: yellow; ​
padding: 10px; ​
border: 1px solid orange; ​
margin-top: 15px; ​
}​
</style>​
</head>​
<body>​
<h1>jQuery Hide/Show Toggle</h1>​

<button id="toggle-btn">Toggle Message Visibility</button>​

<p>​
<input type="checkbox" id="checkbox-toggle"> ​
<label for="checkbox-toggle">Check to Show Message</label>​
</p>​

<div id="secret-message">​
<p>This message is controlled by both the button and the
checkbox!</p>​
</div>​

<script>​
$(document).ready(function() {​
// 1. Button Interaction (Using .toggle() for simple
hide/show)​
$("#toggle-btn").click(function() {​
$("#secret-message").toggle(500); // 500ms slide
animation​
});​

// 2. Checkbox Interaction (Using .show() and .hide())​
$("#checkbox-toggle").change(function() {​
if ($(this).is(":checked")) {​
$("#secret-message").show(300); // Show quickly​
} else {​
$("#secret-message").hide(300); // Hide quickly​
}​
});​

// Initial state: hide the message if the checkbox is
unchecked​
if (!$("#checkbox-toggle").is(":checked")) {​
$("#secret-message").hide();​
}​
});​
</script>​
</body>​
</html>​

Lab 4: Content Management Systems (Joomla and


WordPress)
These tasks are configuration-based and cannot be solved with code alone. I will provide the
steps required to complete the lab tasks for both CMS platforms.

Lab 4.1: Joomla Installation and Customization


1. Task: Install Joomla CMS on a local server and customize the default template
by changing colors, fonts, and layout styles.

1.​ Installation:
○​ Prerequisites: Ensure XAMPP/WAMP/MAMP is running (Apache, MySQL, PHP).
○​ Download: Download the latest Joomla package from the official site.
○​ Extract: Extract the files into your local server's web root (e.g., htdocs/joomla).
○​ Database: Create a new MySQL database (e.g., joomladb).
○​ Web Installer: Navigate to [Link] and follow the on-screen steps,
providing site name, superuser credentials, and the database details.
2.​ Template Customization (Via Administrator Panel):
○​ Log into the Joomla Administrator Panel ([Link]
○​ Navigate to System -> Templates -> Site Templates.
○​ Find the active template (e.g., Cassiopeia) and click on its name to open the editor.
○​ Use the editor to change Colors, Fonts, and Layout settings provided by the
template's developer.
○​ For advanced layout/style changes: Navigate to System -> Site Template Styles,
find your style, and use the Custom CSS section to add your own CSS rules to
override default styles.

2. Task: Install a new Joomla module that displays a list of recent articles on the
homepage with thumbnails and summaries.

1.​ Find and Download Module: Search the Joomla Extensions Directory for a "Recent
Articles Module" or similar. Download the .zip file.
2.​ Installation:
○​ In the Joomla Administrator Panel, navigate to System -> Install -> Extensions.
○​ Drag and drop the downloaded .zip file or use the "Browse for file" button to upload
and install the module.
3.​ Module Configuration:
○​ Navigate to Content -> Site Modules.
○​ Locate the newly installed module (or the built-in Latest Articles module).
○​ Position: Set the module's position to one that is visible on the homepage (e.g.,
sidebar-right, position-7).
○​ Menu Assignment: Ensure the module is set to display on the Home menu item.
○​ Options: Configure the options to include a thumbnail and a short summary (intro
text) for each article.
○​ Save & Close. The recent articles list should now appear on the frontend.

Lab 4.2: WordPress Administration and Theme Integration


1. Task: Set up a WordPress site on a web server and install a custom theme.
Customize the theme by adding a logo, changing colors, and modifying header
and footer styles.

1.​ Installation: (Similar to Joomla, but easier using the Famous 5-Minute Install)
○​ Download: Download WordPress from the official site.
○​ Extract: Extract into your web root (e.g., htdocs/wordpress).
○​ Database: Create a MySQL database (e.g., wp_db).
○​ Run Installer: Navigate to [Link] and complete the installation.
2.​ Install a Custom Theme:
○​ Log into the WordPress Dashboard (/wp-admin).
○​ Navigate to Appearance -> Themes -> Add New.
○​ Search for a custom theme (e.g., Astra, OceanWP, or upload a custom theme
ZIP).
○​ Click Install and then Activate.
3.​ Theme Customization:
○​ Navigate to Appearance -> Customize. This opens the WordPress Customizer.
○​ Logo: Find the Site Identity section to upload your logo image.
○​ Colors: Find the Colors or Global/General section to change the primary and
accent colors.
○​ Header/Footer: Use the corresponding sections in the Customizer to change
layouts, add widgets, or modify copyright text.

2. Task: Create a new WordPress Page with custom content and configure it to be
the homepage of the website.

1.​ Create the Page:


○​ In the WordPress Dashboard, navigate to Pages -> Add New.
○​ Give it a title (e.g., "Welcome Home").
○​ Add your custom content (text, images, blocks) to the page editor.
○​ Click Publish.
2.​ Set as Homepage:
○​ Navigate to Settings -> Reading.
○​ Under the section "Your homepage displays," select the option "A static page."
○​ In the "Homepage" dropdown menu, select the newly created page "Welcome
Home."
○​ Click Save Changes.

3. Task: Install and activate WordPress plugins for additional functionality, such
as SEO optimization, social media sharing, or site backup. Configure the plugins
according to the site's requirements.

1.​ Navigate to Plugins:


○​ In the WordPress Dashboard, navigate to Plugins -> Add New.
2.​ Install & Activate Plugins:
○​ SEO: Search for "Yoast SEO" or "Rank Math." Click Install Now and then
Activate.
○​ Social Sharing: Search for "Social Sharing Buttons" or similar. Click Install Now
and then Activate.
○​ Backup: Search for "UpdraftPlus" or "Duplicator." Click Install Now and then
Activate.
3.​ Configure Plugins:
○​ After activation, configuration is key. Usually, a new menu item is created for the
plugin (e.g., "Yoast SEO" or "UpdraftPlus").
○​ SEO: Follow the setup wizard for your chosen SEO plugin (e.g., enter site name,
choose primary category).
○​ Backup: Configure your backup plugin to set a backup schedule (e.g.,
daily/weekly) and select a remote storage location (e.g., Google Drive, Dropbox).

You might also like