WEB PROGRAMMING LAB PROGRAMS
1. Create a form with the elements of Textboxes, Radio buttons, Checkboxes, and so on. Write
JavaScript code to validate the format in email, and mobile number in 10 characters, If a textbox
has been left empty, popup an alert indicating when email, mobile number and textbox has been
left empty.
Program:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h2>Registration Form</h2>
<!-- Form with textboxes, radio buttons, and checkboxes -->
<form onsubmit="return validateForm()">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
Mobile: <input type="text" id="mobile"><br><br>
Gender:
<input type="radio" name="gender"> Male
<input type="radio" name="gender"> Female <br><br>
Hobbies:
<input type="checkbox"> Reading
<input type="checkbox"> Sports <br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
// Get values from textboxes
let name = [Link]("name").value;
let email = [Link]("email").value;
let mobile = [Link]("mobile").value;
// Check if any field is empty
if (name === "" || email === "" || mobile === "") {
alert("All fields are required!");
return false;
}
// Check email format using regular expression
let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{ 2,3}$/;
if () {
alert("Invalid email format!");
return false;
}
// Check if mobile number has exactly 10 digits
if ([Link] !== 10 || isNaN(mobile)) {
alert("Mobile number must be 10 digits!");
return false;
}
// If everything is correct
alert("Form submitted successfully!");
return true;
}
</script>
</body>
</html>
^ → Start of the string
[^ ]+ → One or more characters that are not a space (this is before the @).
@ → Must contain @.
[^ ]+ → Again, one or more characters after @ (domain name, like gmail).
\. → A literal dot (.).
[a-z]{2,3} → 2 or 3 small letters (like com, in, org).
$ → End of the string.
Output:
2. Develop an HTML Form, which accepts any Mathematical expression. Write JavaScript code
to Evaluate the expression and Display the result.
Program:
<!DOCTYPE html>
<html>
<head>
<title>Math Expression Evaluator</title>
</head>
<body>
<h2>Evaluate Math Expression</h2>
<!-- Simple form for entering expression -->
<form onsubmit="return false;">
Enter Expression:
<input type="text" id="expr" placeholder="e.g. 5+6*2"><br><br>
<button onclick="evaluateExpr()">Calculate</button>
</form>
<!-- Result will be shown here -->
<p id="result"></p>
<script>
function evaluateExpr() {
// Get value from textbox
let exp = [Link]("expr").value;
// If expression is empty
if (exp === "") {
alert("Please enter an expression!");
return;
}
try {
// eval() is used to calculate mathematical expressions
let res = eval(exp);
[Link]("result").innerHTML = "Result: " + res;
} catch {
// If express ion is invalid
alert("Invalid Expression!");
}
}
</script>
</body>
</html>
Output:
3. Create a page with dynamic effects. Write the code to include layers and basic animation.
Program:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Effects</title>
<style>
/* Create a red box (layer) */
#box {
width: 100px;
height: 100px;
background-color: red;
position: relative; /* Needed for movement */
}
</style>
</head>
<body>
<h2>Basic Animation</h2>
<button onclick="moveBox()">Start Animation</button>
<div id="box"></div>
<script>
function moveBox() {
let box = [Link]("box");
let pos = 0; // Starting position
let id = setInterval(frame, 10); // Call frame every 10ms
function frame() {
if (pos == 300) { // Stop at 300px
clearInterval(id);
} else {
pos++;
[Link] = pos + "px"; // Move box to the right
}
}
}
</script>
</body>
</html>
Output:
4. Write a JavaScript code to find the sum of N natural Numbers. (Use userdefined function)
<!DOCTYPE html>
<html>
<head>
<title>Sum of N Natural Numbers</title>
</head>
<body>
<h2>Sum of N Natural Numbers</h2>
<!-- Input for N -->
Enter a number (N):
<input type="text" id="num">
<button onclick="findSum()">Calculate</button>
<p id="result"></p>
<script>
// User-defined function to calculate sum
function sumNatural(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i; // add each number to sum
}
return sum;
}
function findSum() {
let n = [Link]("num").value;
if (n === "" || isNaN(n)) {
alert("Please enter a valid number!");
return;
}
n = parseInt(n); // convert string to integer
let result = sumNatural(n); // call user-defined function
[Link]("result").innerHTML =
"Sum of first " + n + " natural numbers is: " + result;
}
</script>
</body>
</html>
Output:
5. Write a JavaScript code block using arrays and generate the current date in words, this should
include the day, month and year.
<!DOCTYPE html>
<html>
<head>
<title>Date in Words</title>
</head>
<body>
<h2>Current Date in Words</h2>
<p id="date"></p>
<script>
// Arrays for days and months
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
let months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
// Get current date
let today = new Date();
let dayName = days[[Link]()]; // Get day in words
let monthName = months[[Link]()]; // Get month in words
let date = [Link](); // Day of month
let year = [Link](); // Year
[Link]("date").innerHTML =
"Today is " + dayName + ", " + date + " " + monthName + " " + year;
</script>
</body>
</html>
Output:
6. Create a form for Student information. Write JavaScript code to find Total, Average, Result
and Grade.
<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h2>Student Result Calculator</h2>
<form onsubmit="return false;">
Name: <input type="text" id="name"><br><br>
Subject 1: <input type="text" id="s1"><br><br>
Subject 2: <input type="text" id="s2"><br><br>
Subject 3: <input type="text" id="s3"><br><br>
<button onclick="calculateResult()">Submit</button>
</form>
<p id="output"></p>
<script>
function calculateResult() {
let s1 = parseInt([Link]("s1").value);
let s2 = parseInt([Link]("s2").value);
let s3 = parseInt([Link]("s3").value);
let total = s1 + s2 + s3;
let avg = total / 3;
let result = (s1 >= 35 && s2 >= 35 && s3 >= 35) ? "Pass" : "Fail";
let grade;
if (avg >= 75) grade = "Distinction";
else if (avg >= 60) grade = "First Class";
else if (avg >= 50) grade = "Second Class";
else if (avg >= 35) grade = "Pass Class";
else grade = "Fail";
[Link]("output").innerHTML =
"Total: " + total + "<br>" +
"Average: " + [Link](2) + "<br>" +
"Result: " + result + "<br>" +
"Grade: " + grade;
}
</script>
</body>
</html>
Output:
7. Create a form for Employee information. Write JavaScript code to find DA, HRA, PF, TAX,
Gross pay, Deduction and Net pay.
<!DOCTYPE html>
<html>
<head>
<title>Employee Salary Calculator</title>
</head>
<body>
<h2>Employee Salary Calculator</h2>
<form onsubmit="return false;">
Name: <input type="text" id="ename"><br><br>
Basic Pay: <input type="text" id="basic"><br><br>
<button onclick="calculateSalary()">Calculate</button>
</form>
<p id="salary"></p>
<script>
function calculateSalary() {
let basic = parseFloat([Link]("basic").value);
// Allowances and deductions (example % values)
let DA = basic * 0.1; // 10% of basic
let HRA = basic * 0.15; // 15% of basic
let PF = basic * 0.05; // 5% of basic
let TAX = basic * 0.1; // 10% of basic
let gross = basic + DA + HRA;
let deduction = PF + TAX;
let net = gross - deduction;
[Link]("salary").innerHTML =
"Basic Pay: " + basic + "<br>" +
"DA (10%): " + DA + "<br>" +
"HRA (15%): " + HRA + "<br>" +
"PF (5%): " + PF + "<br>" +
"TAX (10%): " + TAX + "<br>" +
"Gross Pay: " + gross + "<br>" +
"Deduction: " + deduction + "<br>" +
"Net Pay: " + net;
}
</script>
</body>
</html>
8. Write a program in PHP to change background color based on day of the week using if else if
statements and using arrays .
<?php
// Get the current day name (e.g., Monday, Tuesday, etc.)
$day = date("l");
// Define hex color codes in an array
$colors = array(
"Monday" => "#ADD8E6", // Light Blue
"Tuesday" => "#90EE90", // Light Green
"Wednesday" => "#FFFFE0", // Light Yellow
"Thursday" => "#FFB6C1", // Light Pink
"Friday" => "#F08080", // Light Coral
"Saturday" => "#D3D3D3", // Light Gray
"Sunday" => "#FFFFFF" // White
);
// Initialize background color
$backgroundColor = "#FFFFFF"; // Default
// Set color using if-else-if and the array
if ($day == "Monday") {
$backgroundColor = $colors["Monday"];
} else if ($day == "Tuesday") {
$backgroundColor = $colors["Tuesday"];
} else if ($day == "Wednesday") {
$backgroundColor = $colors["Wednesday"];
} else if ($day == "Thursday") {
$backgroundColor = $colors["Thursday"];
} else if ($day == "Friday") {
$backgroundColor = $colors["Friday"];
} else if ($day == "Saturday") {
$backgroundColor = $colors["Saturday"];
} else if ($day == "Sunday") {
$backgroundColor = $colors["Sunday"];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Background Color Based on Day</title>
</head>
<body style="background-color: <?php echo $backgroundColor; ?>;">
<h1>Today is <?php echo $day; ?></h1>
</body>
</html>
9. Write a simple program in PHP for i) generating Prime number ii) generate Fibonacci series.
<?php
// Program to generate prime numbers up to a given limit
$limit = 20; // Change this limit as needed
echo "Prime numbers up to $limit: ";
for ($num = 2; $num <= $limit; $num++) {
$isPrime = true;
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0 ) {
$isPrime = false;
break;
}
}
if ($isPrime) {
echo $num . " ";
}
}
?>
ii)fibonacci
<?php
// Program to generate Fibonacci series for given number of terms
$terms = 10; // Change this to generate more/less terms
$a = 0;
$b = 1;
echo "Fibonacci series for $terms terms: ";
for ($i = 0; $i < $terms; $i++) {
echo $a . " ";
$next = $a + $b;
$a = $b;
$b = $next;
}
?>
10. Write a PHP program to remove duplicates from a sorted list
<?php
// Program to remove duplicates from a sorted list
// Step 1: Define a sorted list (array with duplicate elements)
$numbers = array(1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7);
// Step 2: Use array_unique() to remove duplicates
$uniqueNumbers = array_unique($numbers);
// Step 3: Re-index the array (since array_unique keeps old keys)
$uniqueNumbers = array_values($uniqueNumbers);
// Step 4: Print the final list without duplicates
echo "Original List: ";
print_r($numbers);
echo "<br>List after removing duplicates: ";
print_r($uniqueNumbers);
?>
11. Write a PHP Script to print the following pattern on the Screen:
*****
****
***
**
*
<?php
// Program to print a pattern in reverse pyramid shape
// Step 1: Set the number of rows
$rows = 5;
// Step 2: Outer loop for rows
for ($i = $rows; $i >= 1; $i--) {
// Step 3: Inner loop to print stars
for ($j = 1; $j <= $i; $j++) {
echo "*";
}
// Step 4: Move to the next line
echo "<br>";
}
?>
12. Write a simple program in PHP for Searching of data by different criteria.
<?php
// Sample dataset: array of students with ID, Name, and City
$students = [
["id" => 1, "name" => "Ravi", "city" => "Bangalore"],
["id" => 2, "name" => "Anita", "city" => "Mysore"],
["id" => 3, "name" => "Kiran", "city" => "Bangalore"],
["id" => 4, "name" => "Meena", "city" => "Dharwad"]
];
// Search criteria (we can change these values to test)
$searchBy = "city"; // Options: id, name, city
$searchValue = "Bangalore";
// Flag to check if found
$found = false;
echo "<h3>Search Results</h3>";
// Loop through the dataset
foreach ($students as $student) {
if (strtolower($student[$searchBy]) == strtolower($searchValue)) {
echo "ID: " . $student["id"] .
" | Name: " . $student["name"] .
" | City: " . $student["city"] . "<br>";
$found = true;
}
}
if (!$found) {
echo "No records found for $searchBy = $searchValue";
}
?>
13. Write a function in PHP to generate captcha code
<?php
// Function to generate a random captcha code
function generateCaptcha($length = 6) {
// Characters allowed in captcha
$characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$captcha = '';
// Generate random characters
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, strlen($characters) - 1)];
}
return $captcha;
}
// Example usage
$captchaCode = generateCaptcha(6); // 6-character captcha
echo "Your Captcha Code is: <b>$captchaCode</b>";
?>
14. Write a Program to store and read image from Database.
#connectivity
<?php
$servername = "[Link]"; // localhost IP to avoid socket issues
$username = "root"; // your MySQL username
$password = "nmkrv25"; // your MySQL password
$dbname = "image"; // your database name
$port = 3306; // default MySQL port
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
#prgm
<?php
$conn = mysqli_connect("localhost", "root", "nmkrv25", "image");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Handle image upload
if (isset($_POST['upload'])) {
$imgData = addslashes(file_get_contents($_FILES["uploadfile"]["tmp_name"]));
$sql = "INSERT INTO newpictures (img) VALUES ('$imgData')";
mysqli_query($conn, $sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload & View Images</title>
</head>
<body>
<h3>Upload Image</h3>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="uploadfile" required>
<button type="submit" name="upload">Upload</button>
</form>
<hr>
<h3>Uploaded Images</h3>
<?php
$result = mysqli_query($conn, "SELECT * FROM newpictures");
while ($row = mysqli_fetch_assoc($result)) {
$imgData = base64_encode($row['img']);
echo "<img src='data:image/jpeg;base64,{$imgData}' width='150' height='150'
style='margin:5px; border:1px solid #ccc;'>";
}
mysqli_close($conn);
?>
</body>
</html>
#dbms
use image;
CREATE TABLE newpictures (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
img LONGBLOB
);
describe newpictures;
15. Write a program in PHP to read and write file using form control.
<!DOCTYPE html>
<html>
<body>
<h3>Write and Read File</h3>
<form method="post">
Enter some text: <input type="text" name="content" required>
<input type="submit" name="write" value="Write to File">
<input type="submit" name="read" value="Read from File">
</form>
<?php$filename = "[Link]";
// Write to fileif (isset($_POST['write'])) {
$data = $_POST['content'];
file_put_contents($filename, $data);
echo "<p>Data written to file successfully!</p>";
}
// Read from fileif (isset($_POST['read'])) {
if (file_exists($filename)) {
$data = file_get_contents($filename);
echo "<p><b>File Content:</b> $data</p>";
} else {
echo "<p>File not found!</p>";
}
}?>
</body>
</html>
16. Write a program in PHP to Validate Input
<!DOCTYPE html>
<html>
<body>
<h3>Input Validation Example</h3>
<form method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit" value="Validate">
</form>
<?phpif (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$age = trim($_POST['age']);
if (empty($name) || empty($email) || empty($age)) {
echo "<p>Please fill all fields!</p>";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p>Invalid email format!</p>";
} elseif (!is_numeric($age)) {
echo "<p>Age must be a number!</p>";
} else {
echo "<p>All inputs are valid </p>";
}
}?>
</body>
</html>
17. Write a program in PHP for exception handling for i) divide by zero ii) checking date format.
<!DOCTYPE html>
<html>
<body>
<h3>Exception Handling Example</h3><?php// i) Divide by zerotry {
$a = 10;
$b = 0;
if ($b == 0) {
throw new Exception("Cannot divide by zero!");
}
echo "Result: " . ($a / $b);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "<br>";
}
// ii) Checking date formattry {
$date = "2025-13-05"; // invalid month
$d = DateTime::createFromFormat('Y-m-d', $date);
if (!$d || $d->format('Y-m-d') !== $date) {
throw new Exception("Invalid date format!");
}
echo "Valid date!";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}?>
</body>
</html>
18. PHP Program to Add, Update, and Delete using Student Database
Step 1: Create a table in your database (studentdb):
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Step 2: Simple PHP code:
<?php$conn = mysqli_connect("localhost", "root", "", "studentdb");if (!$conn) die("Connection
failed: " . mysqli_connect_error());
// Add recordif (isset($_POST['add'])) {
$name = $_POST['name'];
$age = $_POST['age'];
mysqli_query($conn, "INSERT INTO students (name, age) VALUES ('$name', '$age')");
}
// Update recordif (isset($_POST['update'])) {
$id = $_POST['id'];
$age = $_POST['age'];
mysqli_query($conn, "UPDATE students SET age='$age' WHERE id=$id");
}
// Delete recordif (isset($_POST['delete'])) {
$id = $_POST['id'];
mysqli_query($conn, "DELETE FROM students WHERE id=$id");
}?>
<!DOCTYPE html>
<html>
<body>
<h3>Student Database</h3>
<form method="post">
ID: <input type="number" name="id"><br>
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br><br>
<button name="add">Add</button>
<button name="update">Update</button>
<button name="delete">Delete</button>
</form>
<hr>
<h4>Records:</h4><?php$result = mysqli_query($conn, "SELECT * FROM students");while
($row = mysqli_fetch_assoc($result)) {
echo "ID: {$row['id']} - Name: {$row['name']} - Age: {$row['age']}<br>";
}mysqli_close($conn);?>
</body>
</html>