0% found this document useful (0 votes)
43 views

WP Lab Manual

Uploaded by

sujithsaju564
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

WP Lab Manual

Uploaded by

sujithsaju564
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

ACHARYA INSTITUTE OF GRADUATE STUDIES

(NAAC Re -Accredited ‘A’ and Affiliated to Bengaluru City University)


Soladevanahalli, Bengaluru-560107

DEPARTMENT COMPUTER APPLICATION

WEB PROGRAMMING
LAB MANUAL – NEP SYLLABUS

SEMESTER : V
COURSE CODE :CA-C25L
SYLLABUS
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.
2. Develop an HTML Form, which accepts any Mathematical expression. Write JavaScript
code to Evaluate the expression and Display the result.

3. Create a page with dynamic effects. Write the code to include layers and basic animation.
4. Write a JavaScript code to find the sum of N natural Numbers. (Use userdefined function)
5. Write a JavaScript code block using arrays and generate the current date in words, this
should include the day, month and year.

6. Create a form for Student information. Write JavaScript code to find Total, Average,
Result and Grade.
7. Create a form for Employee information. Write JavaScript code to find DA, HRA, PF,
TAX, Gross pay, Deduction and Net pay.
8. Write a program in PHP to change background color based on day of the week using if else
if statements and using arrays .

9. Write a simple program in PHP for i) generating Prime number ii) generate Fibonacci
series.
10. Write a PHP program to remove duplicates from a sorted list
11. Write a PHP Script to print the following pattern on the Screen:

*****
****
***
**
*
12. Write a simple program in PHP for Searching of data by different criteria

13. Write a function in PHP to generate captcha code


14. Write a program in PHP to add, update and delete using student database.
15. Write a program in PHP to Validate Input

16. Write a program in PHP for setting and retrieving a cookie


17. Write a PHP program to Create a simple webpage of a college.
18. Write a program in PHP for exception handling for i) divide by zero ii) checking date
format.
INDEX

S.NO EXPERIMENT PAGE NUMBER

1 FORM VALIDATION 1
2 EVALUATE MATHEMATICAL EXPRESSION 3
3 DYNAMIC EFFECTS 5
4 SUM OF N NATURAL NUMBERS 7
5 CURRENT DATE IN WORDS 9
6 STUDENT INFORMATION 11
7 EMPLOYEE INFORMATION 13
8 CHANGE BACKGROUNG COLOR 15
9 PRIME NUMBER AND FIBONACCI SERIES 17
10 REMOVE DUPLICATES FROM SORTED LIST 19
11 PATTERN PRINTING 21
12 SEARCHING OF DATA 23
13 GENERATE CAPTCHA CODE 25
14 STUDENT DATABASE 27
15 VALIDATE INPUT 30
16 COOKIE 33
17 WEB PAGE OF COLLEGE 35
18 EXCEPTION HANDLING 37
Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -1
OBJECTIVE:
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.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h2>Contact Form</h2>
<form>
Name:<input type="text" id="name" name="name"><br>
Email:<input type="text" id="email" name="email"><br>
Mobile Number:<input type="text" id="mobile" name="mobile"><br>
Gender:<input type="radio" id="male" name="gender"value="male">Male
<input type="radio" id="female" name="gender" value="female">Female<br>
Hobbies: Reading<input type="checkbox" id="reading" name="hobbies"
value="reading">
Gaming<input type="checkbox" id="gaming" name="hobbies" value="gaming">
<br>
<input type="submit" value="Submit" onclick="val()">
</form>
<script>
function val()
{
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var mobile = document.getElementById('mobile').value;
if (name.trim()==''||email.trim()==''||mobile.trim()=='') {
alert('Please fill out all fields.');
return;
}

Web Programming Lab 1


Acharya Institute of Graduate Studies Department of Computer Application

var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;


if (!emailRegex.test(email)) {
alert('Please enter a valid email address.');
return;
}
if (mobile.length !== 10 || isNaN(mobile)) {
alert('Please enter a valid 10-digit mobile number.');
return;
}
console.log('Form submitted successfully!');
}
</script>
</body>
</html>

OUTPUT:

Web Programming Lab 2


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -2
OBJECTIVE:
Develop an HTML Form, which accepts any Mathematical expression. Write JavaScript code to
Evaluate the expression and Display the result.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Math Expression Evaluator</title>
</head>
<body>
<h2>Math Expression Evaluator</h2>
<form>
Enter a Mathematical Expression:<input type="text" id="expression" name="expression"><br>
<input type="submit" value="Evaluate" onClick="evaluateExpression()">
</form>
<script>
function evaluateExpression() {
var expressionInput=document.getElementById('expression').value;
var res=eval(expressionInput);
document.write("Result="+res);
}
</script>
</body>
</html>

Web Programming Lab 3


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 4


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -3
OBJECTIVE:
Create a page with dynamic effects. Write the code to include layers and basic animation.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<head>
<title>Dynamic Effects Page</title>
<style>
body {
margin: 0;
overflow: hidden;
}
.layer {
position: absolute;
width: 100%;
height: 100%;
transition: transform 1s ease-in-out;
}
#layer1 {
transform: translateY(-100%);
background-color:red;
}
#layer2 {
transform: translateY(100%);
background-color:green;
}

</style>
</head>
<body>
<div class="layer" id="layer1"></div>
<div class="layer" id="layer2"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Animate layers on page load
animateLayer('layer1', 0);
animateLayer('layer2', 0);

Web Programming Lab 5


Acharya Institute of Graduate Studies Department of Computer Application

});
function animateLayer(layerId, delay) {
var layer = document.getElementById(layerId);
// Use setTimeout to create a delay before applying the animation
setTimeout(function() {
// Apply animation by setting transform to translateY(0)
layer.style.transform = 'translateY(0)';
}, delay);
}
</script>
</body>
</html>
OUTPUT:

Web Programming Lab 6


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -4
OBJECTIVE:
Write a JavaScript code to find the sum of N natural Numbers. (Use userdefined function).

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Sum of N Natural Numbers</title>
</head>
<body>
<h2>Sum of N Natural Numbers</h2>
<p>Enter a positive integer N:</p>
<input type="number" id="inputNumber">
<button onclick="calculateSum()">Calculate Sum</button>
<p id="result"></p>
<script>
function calculateSum() {
var n = document.getElementById('inputNumber').value;
if (n <= 0) {
alert('Please enter a positive integer.');
return;
}
n = Number(n);
// Calculate the sum using the formula for the sum of first N natural numbers
var sum = (n * (n + 1)) / 2;
document.getElementById('result').innerHTML = 'Sum of first ' + n + ' natural numbers
is: ' + sum;
}
</script>
</body>
</html>

Web Programming Lab 7


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 8


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -5
OBJECTIVE:
Write a JavaScript code block using arrays and generate the current date in words, this should
include the day, month and year.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Current Date in Words</title>
</head>
<body>
<h2>Current Date in Words</h2>
<p id="currentDate"></p>
<script>
// Array of month names
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'];
// Get the current date
var currentDate = new Date();
// Get day, month, and year components
var day = currentDate.getDate();
var monthIndex = currentDate.getMonth();
var year = currentDate.getFullYear();
// Get the month name from the array
var monthName = monthNames[monthIndex];
// Display the current date in words
var currentDateInWords = 'Today is ' + monthName + ' ' + day + ', ' + year;
document.getElementById('currentDate').innerText = currentDateInWords;
</script>
</body>
</html>

Web Programming Lab 9


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 10


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -6
OBJECTIVE:
Create a form for Student information. Write JavaScript code to find Total, Average, Result and
Grade.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Student Information Form</title>
</head>
<body>
<h2>Student Information</h2>
<form>
Name:<input type="text" id="name" name="name">
Math Score:<input type="number" id="math" name="math">
Science Score:<input type="number" id="science" name="science">
English Score:<input type="number" id="english" name="english" required>
<input type="button" value="Calculate" onclick="calculateResults()">
</form>
<h3>Results:</h3>
<p>Total Score: <span id="total"></span></p>
<p>Average Score: <span id="average"></span></p>
<p>Result: <span id="result"></span></p>
<p>Grade: <span id="grade"></span></p>
<script>
function calculateResults() {
var math = parseFloat(document.getElementById('math').value);
var science = parseFloat(document.getElementById('science').value);
var english = parseFloat(document.getElementById('english').value);
// Validate if the scores are valid numbers
if(isNaN(math) || isNaN(science) || isNaN(english)){
alert('Please enter valid numeric scores.');
return;
}
// Calculate total, average, result, and grade
var total = math + science + english;
var average = total / 3;
var result = (average >= 40) ? 'Pass' : 'Fail';

Web Programming Lab 11


Acharya Institute of Graduate Studies Department of Computer Application

var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'F';
}
document.getElementById('total').innerText = total;
document.getElementById('average').innerText = average.toFixed(2);
document.getElementById('result').innerText = result;
document.getElementById('grade').innerText = grade;
}
</script>
</body>
</html>

OUTPUT:

Web Programming Lab 12


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -7
OBJECTIVE:
Create a form for Employee information. Write JavaScript code to find DA, HRA, PF, TAX,
Gross pay, Deduction and Net pay.

PROCEDURE:

1. Open Notepad
2. Write JavaScript code
3. save file, and give it a name that ends with “.html” extension

SOURCE CODE:
<html>
<head>
<title>Employee Information Form</title>
</head>
<body>
<h2>Employee Information</h2>
<form>
Employee Name:<input type="text" id="employeeName"
name="employeeName"><br>
Basic Salary:<input type="number" id="basicSalary" name="basicSalary"><br>
HRA Percentage:<input type="number" id="hraPercentage"
name="hraPercentage"><br>
DA Percentage:<input type="number" id="daPercentage" name="daPercentage"><br>
Tax Percentage:<input type="number" id="taxPercentage" name="taxPercentage"
required><br>
<input type="button" value="Calculate" onclick="calculateSalary()">
</form>
<h3>Salary Details:</h3>
<p>DA: <span id="da"></span></p>
<p>HRA: <span id="hra"></span></p>
<p>PF: <span id="pf"></span></p>
<p>TAX: <span id="tax"></span></p>
<p>Gross Pay: <span id="grossPay"></span></p>
<p>Deduction: <span id="deduction"></span></p>
<p>Net Pay: <span id="netPay"></span></p>
<script>
function calculateSalary() {
var basicSalary = parseFloat(document.getElementById('basicSalary').value);
var hraPercentage = parseFloat(document.getElementById('hraPercentage').value);
var daPercentage = parseFloat(document.getElementById('daPercentage').value);
var taxPercentage = parseFloat(document.getElementById('taxPercentage').value);

Web Programming Lab 13


Acharya Institute of Graduate Studies Department of Computer Application

if (isNaN(basicSalary) || isNaN(hraPercentage) || isNaN(daPercentage) ||


isNaN(taxPercentage)) {
alert('Please enter valid numeric values.');
return;
}
var da = (daPercentage / 100) * basicSalary;
var hra = (hraPercentage / 100) * basicSalary;
var pf = 0.12 * basicSalary; // Assuming PF is 12% of basic salary
var tax = (taxPercentage / 100) * basicSalary;
var grossPay = basicSalary + da + hra;
var deduction = pf + tax;
var netPay = grossPay - deduction;
// Display the results on the page
document.getElementById('da').innerText = da.toFixed(2);
document.getElementById('hra').innerText = hra.toFixed(2);
document.getElementById('pf').innerText = pf.toFixed(2);
document.getElementById('tax').innerText = tax.toFixed(2);
document.getElementById('grossPay').innerText = grossPay.toFixed(2);
document.getElementById('deduction').innerText = deduction.toFixed(2);
document.getElementById('netPay').innerText = netPay.toFixed(2);
}
</script>
</body>
</html>

OUTPUT:

Web Programming Lab 14


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -8
OBJECTIVE:
Write a program in PHP to change background color based on day of the week using if else if
statements and using arrays .

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
$days=array(0=>"blue",1=>"green", 2=>"red", 3=>"purple", 4=>"yellow", 5=>"cyan",
6=>"orange");
$today = date('w');
$defaultColor = '#FFFFFF';
if (array_key_exists($today, $days)) {
echo '<body style="background-color:' . $days[$today] . '">';
} else {
return $defaultColor;
}
?>

Web Programming Lab 15


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 16


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -9
OBJECTIVE:
Write a simple program in PHP for i) generating Prime number ii) generate Fibonacci series.

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
echo "Prime Number";
$count=0;
$num=2;
while($count<15)
{
$div_count=0;
for($i=1;$i<=$num;$i++)
{
if(($num%$i)==0)
{
$div_count++;
}
}
if($div_count<3)
{
echo $num." , ";
$count=$count+1;
}
$num=$num+1;
}
echo "<br>Fibonacci Series";
$num1=0;
$num2=1;
echo $num1 . ' ' . $num2 . ' ';
for ($i=2;$i<10;$i++) {
$num3=$num1 + $num2;
echo $num3 . ' ';
$num1=$num2;
$num2=$num3;
}

Web Programming Lab 17


Acharya Institute of Graduate Studies Department of Computer Application

?>

OUTPUT:

Web Programming Lab 18


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -10
OBJECTIVE:
Write a PHP program to remove duplicates from a sorted list.

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
function removeDuplicates($sortedList) {
$length = count($sortedList);
if ($length <= 1) {
return $sortedList;
}
$uniqueList = [$sortedList[0]];
for ($i = 1; $i < $length; $i++) {
// Compare with the previous element
if ($sortedList[$i] != $sortedList[$i - 1]) {
$uniqueList[] = $sortedList[$i];
}
}
return $uniqueList;
}
$sortedList = [1, 2, 2, 3, 4, 4, 4, 5, 6, 6, 7];
$uniqueList = removeDuplicates($sortedList);
echo '<p>Original List: ' . implode(', ', $sortedList) . '</p>';
echo '<p>Unique List: ' . implode(', ', $uniqueList) . '</p>';
?>

Web Programming Lab 19


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 20


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -11
OBJECTIVE:
Write a PHP Script to print the following pattern on the Screen:

*****
****
***
**
*

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j < $i; $j++) {
echo "&nbsp;";
}
for ($k = $i; $k <= $rows; $k++) {
echo "*";
}
echo "<br>";
}
?>

Web Programming Lab 21


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 22


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -12
OBJECTIVE:
Write a simple program in PHP for Searching of data by different criteria

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
search.html
<html>
<head>
<title>Search Array Value</title>
</head>
<body>
<form method="post" action="search.php">
Enter a value: <input type="text" name="search_value">
<input type="submit" value="Search">
</form>
</body>
</html>

search.php
<?php
$array=array("apple", "banana", "cherry", "date", "elderberry", "fig", "grape");
$search_value=$_POST["search_value"];
if(in_array($search_value, $array)) {
echo "Value '$search_value' was found in the array.";
} else {
echo "Value '$search_value' was not found in the array.";
}
?>

Web Programming Lab 23


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 24


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -13
OBJECTIVE:
Write a function in PHP to generate captcha code

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
function generateCaptcha($length) {
// Generate a random alphanumeric string of the specified length

$characters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567
89';
$captcha='';
for($i=0;$i<$length;$i++) {
$captcha .=$characters[rand(0,strlen($characters)-1)];
}
echo "Captcha: $captcha";
}
$captchaCode=generateCaptcha(6);
?>

Web Programming Lab 25


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 26


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -14
OBJECTIVE:
Write a program in PHP to add, update and delete using student database.

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
stud.html
<html>
<head>
<title>Student Registration</title>
</head>
<body>
<form method="GET" action="stud.php">
Name:<input type="text" name="txt_name"><br>
Course:<input type="text" name="txt_course"><br>
<input type="submit" value="Registration">
</form>
</body>
</html>

stud.php
<?php
$n=$_GET['txt_name'];
$c=$_GET['txt_course'];
//create database connection
$con=mysqli_connect('localhost','root','');
if(!$con)
{
die("Not connected".mysqli_error($con));
}
echo "Connected successfully<br>";
//create database
$sql1="create database db_new";
$rt1=mysqli_query($con,$sql1);
if(!$rt1)

Web Programming Lab 27


Acharya Institute of Graduate Studies Department of Computer Application

{
die("Cannot create database".mysqli_error($con));
}
echo "Database Created<br>";
mysqli_select_db($con,'db_new');
//Create table
$sql2="create table student(name varchar(20) not null,course varchar(10))";
$rt2=mysqli_query($con,$sql2);
if(!$rt2)
{
die("Cannot create table".mysqli_error($con));
}
echo "Table Created<br>";
//insert value into table
$sql3="insert into student(name,course)values('$n','$c')";
$rt3=mysqli_query($con,$sql3);
if(!$rt3)
{
die("Cannot insert value into table".mysqli_error($con));
}
echo "Value inserted<br>";
//update value
$sql4="update student set course='BCA'";
$rt4=mysqli_query($con,$sql4);
if(!$rt4)
{
die("Cannot update".mysqli_error($con));
}
echo "Value Updated<br>";
//delete data
$sql5="Delete from student";
$rt5=mysqli_query($con,$sql5);
if(!$rt5)
{
die("Cannot delete".mysqli_error($con));
}
echo "Value deleted<br>";
?>

Web Programming Lab 28


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 29


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -15
OBJECTIVE:
Write a program in PHP to Validate Input

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<html>
<head>
<title>Input Validation</title>
</head>
<body>
<?php
$nameErr = $emailErr = $ageErr = "";
$name = $email = $age = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";

Web Programming Lab 30


Acharya Institute of Graduate Studies Department of Computer Application

}
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
if (!is_numeric($age)) {
$ageErr = "Age must be a number";
}
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Name:</label>
<input type="text" name="name">
<span class="error"><?php echo $nameErr; ?></span>
<br><br>

<label for="email">Email:</label>
<input type="text" name="email">
<span class="error"><?php echo $emailErr; ?></span>
<br><br>

<label for="age">Age:</label>
<input type="text" name="age">
<span class="error"><?php echo $ageErr; ?></span>
<br><br>

<input type="submit" name="submit" value="Submit">


</form>

<?php
// Display the submitted data
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($nameErr) &&
empty($emailErr) && empty($ageErr)) {
echo "<h2>Submitted Data:</h2>";
echo "Name: $name <br>";
echo "Email: $email <br>";
echo "Age: $age <br>";
}
?>
</body>
</html>

Web Programming Lab 31


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 32


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -16
OBJECTIVE:
Write a program in PHP for setting and retrieving a cookie

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<?php
// Set a cookie
$cookie_name = "user";
$cookie_value = "John";
$cookie_expire = time() + 86400; // 86400 seconds = 1 day
setcookie($cookie_name, $cookie_value, $cookie_expire); // Parameters: name, value, expiration
time, path
// Check if the cookie is set and retrieve its value
if (isset($_COOKIE[$cookie_name])) {
$user = $_COOKIE[$cookie_name];
echo "Welcome, $user!";
} else {
echo "Cookie named '$cookie_name' is not set.";
}
?>

Web Programming Lab 33


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 34


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -17
OBJECTIVE:
Write a PHP program to Create a simple webpage of a college.

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
<html>
<head>
<title>
College
</title>
</head>
<body bgcolor="lightgray">
<?php
<hr>
<h2 align="center" style="color: black;">Acharya Institute of Graduate Studies</h2>
<hr>
<center><img src="cllg.jpg" width="500" height="300"></center>
<h2 align="center" style="color: black;">About College </h2>
<p style="font-family:courier";>Acharya Institute of Graduate Studies, or AIGS, is a private co-
educational engineering and management college in Bengaluru, India, affiliated with the
Bangalore University (BU) and accredited by the National Assessment and Accreditation
Council
(NAAC). Established in 2005, it offers seven undergraduate courses and nine postgraduate
courses.
Acharya organises the Acharya Habba, an annual two-day intercollegiate cultural festival that is
one of the largest in Bengaluru and Karnataka.
The Deccan Herald lists AIGS as one of the "notable" colleges to apply the Karnataka
Management Aptitude Test (KMAT) for admission to postgraduate management courses.
</p>
<a href="dept.html">Departments</a><br>
<a href="course.html">Courses Offered</a><br>
<a href="contact.html">Contact us</a>
?>
</body>

Web Programming Lab 35


Acharya Institute of Graduate Studies Department of Computer Application

</html>

OUTPUT:

Web Programming Lab 36


Acharya Institute of Graduate Studies Department of Computer Application

PROGRAM NO -18
OBJECTIVE:
Write a program in PHP for exception handling for i) divide by zero ii)
checking date format.

PROCEDURE:

1. Open Notepad
2. Write php code
3. save file in C:\wamp64\www, and give it a name that ends with “.php” extension
4. Open WAMP
5. Type localhost/filename.php

SOURCE CODE:
Exe.html
<html>
<head>
<title>
Exception Handling
</title>
</head>
<body>
<form method="GET" action="exe.php">
Enter divident:<input type="text" name="divident"><br>
Enter divisor:<input type="text" name="divisor"><br>
<input type="submit" value="Division">
</form>
</body>
</html>

Exe.php
<?php
//division by zero
$A=$_GET['divident'];
$B=$_GET['divisor'];
try
{
if ($B == 0)
{
throw new Exception("Divide by Zero exception occurred");
}
$C = $A / $B;

Web Programming Lab 37


Acharya Institute of Graduate Studies Department of Computer Application

printf("Result of $A/$B: %d<br>", $C);


}
catch(Exception $e)
{
printf("Exception: %s", $e->getMessage());
}

//invalid date format


function validateDateFormat($date) {
$format ='Y-m-d'; // Define the expected date format
$dateTime = DateTime::createFromFormat($format, $date);

if ($dateTime && $dateTime->format($format) === $date) {


return true;
} else {
return false;
}
}
try {
$inputDate = "2023-10-12";

if (validateDateFormat($inputDate)) {
echo "Date is in the correct format: $inputDate";
} else {
throw new Exception("Invalid date format: $inputDate");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>

Web Programming Lab 38


Acharya Institute of Graduate Studies Department of Computer Application

OUTPUT:

Web Programming Lab 39

You might also like