WP Lab Program
WP Lab Program
<html>
<head>
<script>
function validate() {
var form = document.forms["myForm"];
var name = form.elements["name"].value.trim();
var email = form.elements["email"].value.trim();
var mobile = form.elements["mobile"].value.trim();
var gender = form.elements["gender"].value;
var hobby1 = form.elements["hobby1"].checked;
var hobby2 = form.elements["hobby2"].checked;
if (!/^[a-zA-Z ]+$/.test(name)) {
alert("Please enter a valid name (only letters and spaces allowed).");
return false;
}
if (!/^\S+@\S+\.\S+$/.test(email)) {
alert("Please enter a valid email address.");
return false;
}
if (!/^\d{10}$/.test(mobile)) {
alert("Please enter a valid 10-digit mobile number.");
return false;
}
if (!gender) {
alert("Please select a gender.");
return false;
}
if (!hobby1 && !hobby2) {
alert("Please select at least one hobby.");
return false;
}
alert("Successfully submitted");
return true;
}
</script>
</head>
<body>
<h1 > Form Validation </h1>
<form name="myForm" onsubmit="return validate()">
Name:
<input type="text" name="name"/><br><br>
Email:
<input type="text" name="email"/><br><br>
Mobile:
<input type="text" name="mobile"/><br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br><br>
Hobbies:
<input type="checkbox" name="hobby1" value="reading"> Reading
<input type="checkbox" name="hobby2" value="traveling">
Traveling<br><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Program02
Develop a HTML Form, which accepts any Mathematical expression.
Werite JavaScript code to Evaluates the expression and displays the result.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Expression Evaluation</title>
<script type="text/javascript">
function Evaluate()
{
var enteredExpr = document.getElementById("expr").value;
document.getElementById("result").value = eval(enteredExpr);
}
</script>
</head>
<body>
<form name="myForm">
Enter any valid expression: <input type="text" id="expr" /> <br /> <br />
<input type="button" value="Evaluate" onClick="Evaluate()" /> <br /> <br />
Result of expression: <input type="text" id="result" /> <br /> <br />
</form>
</body>
</html>
Program03
Create a page with dynamic effects. Write the code to include layers
and basic animation.
Program04
Write a JavaScript code to find the sum of N natural Numbers. (Use
userdefined function)
<!DOCTYPE html>
<html>
<head>
<title>Natural Numbers</title>
<script type="text/javascript">
function sum() {
var num = window.prompt("Enter the value of N");
var n = parseInt(num);
var sum = (n * (n + 1)) / 2;
window.alert("Sum of First " + n + " Natural numbers are: " + sum);
}
</script>
</head>
<body bgcolor="pink">
<h1 align="center">Finding Sum of N Natural Numbers</h1>
<hr>
<form align="center">
<input type="button" value="Click Here" onclick="sum()" />
</form>
</body>
</html>
Program05
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 Display</title>
<script type="text/javascript">
var days = ["1",
"2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","1
9","20","21","22","23","24","25","26","27","28","29","30","31"];
var months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October",
"November", "December"];
var year = "2024";
var dateObj = new Date();
var currMonth = dateObj.getMonth();
var currDate = dateObj.getDate();
var currYear = dateObj.getFullYear();
if (currYear == 2024)
alert("Today's Date is : " + days[currDate - 1] + " " +
months[currMonth] + " " + year);
else
alert("Today's Date is : " + days[currDate - 1] + " " +
months[currMonth] + " " + currYear);
</script>
</head>
<body>
</body>
</html>
Program06
Create a form for Student information. Write JavaScript code to find
Total, Average, Result and Grade.
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript">
function calc() {
var m1, m2, m3, avg = 0, total = 0, result = "", grade = "";
m1 = parseInt(document.form1.wp.value);
m2 = parseInt(document.form1.sp.value);
m3 = parseInt(document.form1.cg.value);
total = m1 + m2 + m3;
avg = total / 3;
if (m1 < 35 || m2 < 35 || m3 < 35) {
result = "fail";
grade = "D";
} else if (avg >= 75) {
result = "Distinction";
grade = "A+";
} else if (avg >= 60) {
result = "First class";
grade = "A";
} else if (avg >= 50) {
result = "Second class";
grade = "B";
} else{
result = "Pass class";
grade = "C";
}
document.form1.result.value = result;
document.form1.grade.value = grade;
document.form1.total.value = total;
document.form1.average.value = avg;
}
</script>
</head>
<body bgcolor="pink">
<h1 align="center">STUDENT FORM</h1>
<form name="form1">
<table border="5" align="center">
<tr>
<td>Student Name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>Semester</td>
<td><input type="text" /></td>
</tr>
<tr>
<td colspan="2" align="center">SUBJECT MARKS</td>
</tr>
<tr>
<td>Web Programming</td>
<td><input type="text" name="wp" /></td>
</tr>
<tr>
<td>Computer Graphics</td>
<td><input type="text" name="cg" /></td>
</tr>
<tr>
<td>System Programming</td>
<td><input type="text" name="sp" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" onclick="calc()" value="CALCULATE" /></td>
</tr>
<tr>
<td>Total</td>
<td><input type="text" name="total" /></td>
</tr>
<tr>
<td>Average</td>
<td><input type="text" name="average" /></td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" name="result" /></td>
</tr>
<tr>
<td>Grade</td>
<td><input type="text" name="grade" /></td>
</tr>
</table>
</form>
</body>
</html>
Program07
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 Report</title>
<script type="text/javascript">
function showSalary() {
var name = document.getElementById("empname").value;
var empno = document.getElementById("empno").value;
var basic = parseInt(document.getElementById("basic").value);
var hra = basic * 0.4;
var da = basic * 0.6;
var gross = basic + hra + da;
var pf = gross * 0.13;
var tax = 0.2 * gross;
var deductions = pf + tax;
var netsalary = gross - deductions;
document.write("<body bgcolor=skyblue>");
document.writeln("<table border='5' align=center>");
document.writeln("<tr><th colspan=2>Employee Salary Report</th></tr>");
document.writeln("<tr><td>Employee Name:</td><td>" + name +
"</td></tr>");
document.writeln("<tr><td>Emp No:</td><td>" + empno + "</td></tr>");
document.writeln("<tr><td>Basic Salary:</td><td>" + basic + "</td></tr>");
document.writeln("<tr><td>HRA (40% of basic)</td><td>" + hra +
"</td></tr>");
document.writeln("<tr><td>DA (60% of basic)</td><td>" + da + "</td></tr>");
document.writeln("<tr><td>Gross Salary:</td><td>" + gross + "</td></tr>");
document.writeln("<tr><td>PF (13% of basic)</td><td>" + pf + "</td></tr>");
document.writeln("<tr><td>Tax (20% of gross)</td><td>" + tax +
"</td></tr>");
document.writeln("<tr><td>Deductions (PF + Tax)</td><td>" + deductions +
"</td></tr>");
document.writeln("<tr><td>Net Salary (Gross - Deductions)</td><td>" +
netsalary + "</td></tr>");
document.writeln("</table>");
document.write("</body>");
}
</script>
</head>
<body bgcolor="pink" align="center">
<form>
<table border="5" align=center>
<tr>
<th colspan=2>Employee Salary Form</th>
</tr>
<tr>
<td>Employee Name:</td>
<td><input type="text" id="empname" /></td>
</tr>
<tr>
<td>Employee Number:</td>
<td><input type="text" id="empno" /></td>
</tr>
<tr>
<td>Basic Pay:</td>
<td><input type="text" id="basic" /></td>
</tr>
</table>
<br>
<input type="button" value="Show Salary" onclick="showSalary()">
</form>
</body>
</html>
Program08
Write a program in PHP to change background color based on day of
the week using if else if statements and using arrays
<?php
$dayColors = [
'Sunday' => '#ffcccb',
'Monday' => '#ffebcd',
'Tuesday' => '#add8e6',
'Wednesday' => '#98fh98',
'Thursday' => '#f0e68c',
'Friday' => '#dda0dd',
'Saturday' => '#c0c0c0'
];
$currentDay = date('l');
$backgroundColor = '#ffffff'; // Default white color
if (array_key_exists($currentDay, $dayColors)) {
$backgroundColor = $dayColors[$currentDay];
}
?>
<IDOCTYPE html>
<htmlI>
<head>
<title>Background Color Based on Day of the Week</title>
<style>
body {
background-color: <?php echo $backgroundColor; ?>;
} </style>
</head>
<body>
<h1>Welcome! Today is <?php echo $currentDay; ?></h1>
</body>
</html>
Program09
Write a simple program in PHP for i) generating Prime number ii)
generate Fibonacci series.
<?php
function isPrime($num){
if($num <= 1){
return false;
} for($i = 2; $i <= sqrt($num); $i++){
if($num % $i == 0){
return false;
}}
return true;
}
function generatePrimes($n){
$primeNumbers = [];
$count = 0;
$i=2;
while($count < $n){ if(isPrime($i)){
$primeNumbers[] = $i;
$count++;
} $i++;
}
return $primeNumbers;
}
function generateFibonacci($n){
$fibonacciSeries = [];
$first = 0;
$second = 1;
$fibonacciSeries[] = $first;
$fibonacciSeries[] = $second;
for($i = 2; $i < $n; $i++){
$next = $first + $second;
$fibonacciSeries[] = $next;
$first = $second;
$second = $next; }
return $fibonacciSeries;
}
$numberOfPrimes = 10;
$numberOfTerms = 10;
$primes = generatePrimes($numberOfPrimes);
$fibonacci = generateFibonacci($numberOfTerms);
echo "Prime numbers:";
echo "<pre>" . print_r($primes, true) . "</pre>";
echo "Fibonacci series:";
echo "<pre>" . print_r($fibonacci, true) . "</pre>";
?>
Program10
Write a PHP program to remove duplicates from a sorted list
<IDOCTYPE html>
<html>
<head>
<title>Remove Duplicates from Sorted List</title>
</head>
<body>
<h2>Enter a sorted list of numbers separated by spaces:</h2>
<form method="post">
<input type="text" name="numbers" placeholder="Enter
numbers">
<input type="submit" name="submit" value="Remove
Duplicates">
</form>
<?php
function removeDuplicates($arr) {
$n = count($arr);
if($n==0|$n==1){
return $arr;
}
$unique = [];
$unique[] =$arr[0];
for ($i = 1; $i < $n; $i++) {
if ($arr[$i] != $arr[$i - 1]) {
$unique[] = $arr[$i];
}}
return $unique;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST["numbers"];
$inputArray = explode(' ', $input);
$sortedList = array_map('intval', $inputArray);
sort($sortedList);
echo "<h2>Entered List:</h2>";
echo "<pre>" . print_r($sortedList, true) . "</pre>";
$result = removeDuplicates($sortedList);
echo "<h2>List after removing duplicates:</h2>";
echo "<pre>" . print_r($result, true) . "</pre>";
}
?>
</body>
</html>
Program11
Write a PHP Script to print the following pattern on the Screen
<?php
$rows = 5;
for ($i = $rows; $i >= 1; $i--) {
for ($j = $rows; $j > $i; $j--) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
echo "*";
}
echo "<br>";
}
?>
Program12
Write a simple program in PHP for Searching of data by different
criteria.
<?php
$users=[
['id' => 1, 'name' => 'Anjali', 'age' => 20, 'email' => 'anjali@example.com'],
['id'=> 2, 'name' =>'Nena', 'age' => 19, 'email' => 'nena@example.com'],
['id' => 3, 'name' => 'Madhusudhan', 'age' => 22, 'email' =>
'madhu@example.com'],
['id' => 4, 'name' => 'Vinay', 'age' => 21, 'email' => 'vinay@example.com'],
];
function searchData($data, $criteria, $value) {
$results = [];
foreach ($data as $item) {
if ($item[$criteria] == $value) {
$results[] = $item;
}}
return $results;
}
$searchCriteria = 'age';
$searchValue = 20;
$searchResults = searchData($users, $searchCriteria, $searchValue);
echo "Search Results for $searchCriteria = $searchValue:<br>";
if (count($searchResults) > 0) {
foreach ($searchResults as $result) {
echo "ID:". $result['id'].", Name: " . $result['name']. ", Age: " . $result['age'] ."
,Email: " . $result['email'] . "<br>";
}
} else {
echo "No results found.";
}
?>
Program13
Write a function in PHP to generate captcha code
<?php
function generateCaptcha($length = 6) {
$characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkimnopgrstuvwxyz01234
56789';
$captcha ="";
$charLength = strlen($characters);
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0,$charLength-1)];
}
$_SESSION['captcha'] = $captcha;
return $captcha;
}
session_start();
$captchaCode = generateCaptcha(6);
echo "Generated Captcha: $captchaCode";
?>
Program14
Write a Program to store and read image from Database.
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "studentdb";
$conn =new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["submit"])) {
$image = $_FILES['image']['tmp_name'];
$imgContent =addslashes(file_get_contents($image));
$sql = "INSERT INTO images (name, image_data) VALUES
(".$_FILES['image']['name']."','$imgContent')";
if ($conn->query($sql) === TRUE) {
echo "Image uploaded successfully.";
}else {
echo "Error uploading image: " . $conn->error;
}
}
$sql = "SELECT image_data FROM images WHERE id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
header("Content-type: image/*");
echo $row['image_data'];
}else {
echo "Image not found.";
}
$conn->close();
?>
<!-- HTML Form for Image Upload -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" value="Upload" name="submit" />
</form>
Program15
Write a program in PHP to read and write file using form control.
<IDOCTYPE html>
<html>
<head>
<title>Read and Write File</title>
</head>
<body>
<h2>Write to File</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<textarea name="content" rows="5" cols="40" placeholder="Enter text to
write"></textarea><br><br>
<input type="submit" name="write" value="Write to File">
</form>
<hr>
<h2>Read from File</h2>
<?php
$file = "data.txt";
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST["write"])) {
$content = $_POST["content"];
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
echo "Content written to file successfully!";
}
if (file_exists($file)) {
$content = file_get_contents($file);
echo "<pre>$content</pre>";
}else {
echo "File not found!";
}
?>
</body>
</html>
Program16
Write a program in PHP to add, update and delete using student
database.
<!DOCTYPE html>
<html>
<head>
<title>Student Database Operations</title>
</head>
<body>
<?php
$servername = "localhost"; $username = "root"; $password ="";
$dbname = "studentdb";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$add_sql = "INSERT INTO students (name, age, grade) VALUES
('Shiva', 32, 'A+')";
if ($conn->query($add_sql) === TRUE) {
echo "New record added successfully.<br><br><br>";
}else {
echo "Error adding record: " . $conn->error . "<br>";
}
$update_sql="UPDATE students SET age = 33 WHERE name =
'Swamy'";
if ($conn->query(Supdate_sql) === TRUE) {
echo "Record updated successfully. <br><br><br>";
} else {
echo "Error updating record: " . $conn->error . "<br>";
}
$delete_sql = "DELETE FROM students WHERE name =
'Swamy'";
if ($conn->query(Sdelete_sql) === TRUE) {
echo "Record deleted successfully.<br><br><br>";
} else {
echo "Error deleting record: " . $conn->error . "<br>";
}
$conn->close();
?>
</body>
</html>
Program17
Write a program in PHP to Validate Input.
<!DOCTYPE html>
<html>
<head>
<title>Input Validation</title>
</head>
<body>
<?php
$username = $usernameErr ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameErr = "Only letters and white space allowed";
} } }
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
<h2>Validate Input: Username</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']);?>">
Username: <input type="text" name="username">
<span class="error">* <?php echo $usernameErr; ?></span>
<br><br> <input type="submit" name="submit" value="Submit">
</form>
<?php
if (!empty($username)) {
echo "<h3>Entered Username:</h3>";
echo $username;
} ?>
</body>
</html>
Program18
Write a program in PHP for setting and retrieving a cookie
<?php
$cookie_name = "shivu";
$cookie_value ="857fdr";
$expiration_time = time() + (24 * 3600);
setcookie($cookie_name, $cookie_value, $expiration_time, "/");
echo "Cookie '$cookie_name' is set.<br><br><br>";
if(isset($_COOKIE[$cookie_name]))
{
echo "Value of cookie '$cookie_name'is : ". $_COOKIE[$cookie_name];
}
else
{
echo "Cookie named '$cookie_name' is not set.";
}
?>
Program19
Write a PHP program to Create a simple webpage of a college.
<IDOCTYPE html>
<html>
<head>
<title>College Website</title>
<!-- CSS styles can be added here -->
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
hl {
color: #333;
}
p{
color: #666;
}
</style>
</head>
<body>
<header>
<h1>Welcome to Our College</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Courses</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<section>
<h2>About Our College</h2>
<p>This is a brief description of our college.</p>
</section>
<section>
<h2>Available Courses</h2>
<?php
$courses = ['Computer Science', 'Engineering', 'Business',
'Arts', 'Science'];
echo "<ul>";
foreach($courses as $course)
{
echo "<li>$course</li>";
}
echo "</ul>";
?>
</section>
<section> <h2>Contact Information</h2>
<p>Address: 123 College Avenue, City, Country</p>
<p>Email: info@college.com</p>
<p>Phone: 080 - 25634869</p>
</section>
</main>
<footer>
<p>©
<?php
echo date("Y");
?>
Our College. All rights reserved.</p>
</footer>
</body>
</html>
Program20
Write a program in PHP for exception handling for
i) divide by zero ii) checking date format.
<?php
try {
$numerator = 10;
$denominator = 2;
if ($denominator === 0) {
throw new Exception("Division by zero error");
}
$result = $numerator / $denominator;
echo "Result of division: " . $result . "<br>";
$dateString = '2024-01-08';
$dateFormat ='Y-m-d';
$date = DateTime::createFromFormat($dateFormat, $dateString);
if (!$date || $date->format($dateFormat) !== $dateString) {
throw new Exception("Invalid date format");
}
echo "Date is valid: " . $dateString;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>