WEB PROGRAMMING LAB (html&php)

 WEB PROGRAMMING LAB(NEP)

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

code:

<html>

<head>
<title>Black Eye Form</title>
<script>
function Form() {
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var phone = document.forms["myForm"]["phone"].value;
if (name == "") {
alert(" name must be filled out");
return false;
}
if (email == "") {
aler("Please Enter Email Address");
return false;
}
if (password == "") {
alert("Password must be filled out");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long");
return false;
}
if (phone == "") {
alert("Number must be filled out");
return false;
}
if (phone.length < 10) {
alert("Phone number must be at least 10 digits");
return false;
}
alert("Registration successful.")
return true;
}
</script>
</head>
<body>
<center><h1>Welcome Black Eye Institution</h1>
<p>Here We Provide The best Quality of Courses For Begginer's </p>
<img src="/home/godfather/Downloads/ble.jpg " width="150"
height ="150"><br><br>
<form name="myForm" onsubmit="return Form()">
Name:<input type="text" name="name" id="name"><br><br>
Phone:<input type="number" name="phone" id="phone"><br><br>
Email:<input type="email" name="email" id="email"><br><br>
Password:<input type="password" name="password" id="password"><br><br>
Gender:<input type="radio" id="male" name="gender" value="male"> Male
<input type="radio" id="female" name="gender" value="female"> Female<br><br>
Interest:<br><input type="checkbox" id="penetration" name="checkbox"
value="penetration">Penetration Testing<br>
<input type="checkbox" id="programming languages"
name="checkbox" value="programming language">Programming<br>
<input type="checkbox" id="Networking" name="checkbox"
value="Networking">Networking<br>
<h4>Contact us:</h4>
<p>Instagram:"blac_keye76"</p>
<p>Blog:"https://blackeye001.blogspot.com/"</p>
<button type="submit">Submit</button></center>
</form>
</body>
</html>



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

code 
<html>
<head>
<title>calculus</title>
<script type = "text/javascript">
function statement()
{
var x = document.myForm.statext.value;
var result = eval(x);
document.myForm.resulttext.value = result;
}
</script>
</head>
<body >
<form name = "myForm">
Satement:<input type = "text" name = "statext"><br><br>
Result :<input type = "text" name = "resulttext">
<input type = "button" value = "calculate"onclick = "statement()">
</form>
</body>
</html>



3. Create a page with dynamic effects. Write the code to include layers and basic
animation.

<html> <head> <title> Basic Animation </title> <style> #layer1 {position:absolute;top:50px;left:50;} #layer2 {position:absolute;top:100px;left:100px;} #layer3 {position:absolute; top:150px;left:150px;} </style> <head> <div id="layer1"> <img src="a.png" onclick="moveImage('layer1')"height="50" width="50" alt="MyImage"></div> <div id="layer2"> <img src="b.png" onclick="moveImage('layer2')"height="50" width="50" alt="MyImage"></div> <div id="layer3"> <img src="c.png" onclick="moveImage('layer3')"height="50" width="50" alt="MyImage"></div> <script type="text/javascript"> function moveImage(layer) { var top=window.prompt("Enter Top value"); var left=window.prompt("Enter Left Value"); document.getElementById(layer).style.top=top+'px'; document.getElementById(layer).style.left=left+'px'; } </script> </body> </html>

4.Write a JavaScript code to find the sum of N natural Numbers. (Use user-defined function)
code:

<html>
<head>
<title>Natural Number</title>
<script>
function sum()
{
var n = parseInt(window.prompt("Enter the Value"));
var sum = n*(n+1)/2;
alert("the sum is"+sum)
}
</script>
</head>
<body>
<input type = "button" value = "findsum" onclick ="sum()">
</body>
</html>

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

code:
<!DOCTYPE html>
<html>
<head>
<script>
let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'];
let months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];
function getCurrentDateInWords() {
let today = new Date();
let day = days[today.getDay()];
let month = months[today.getMonth()];
let date = today.getDate();
let year = today.getFullYear();

return day + ', ' + month + ' ' + date + ', ' + year;
}
</script>
</head>
<body>
<h1 id="date"></h1>

<script>
document.getElementById('date').innerHTML = getCurrentDateInWords();
</script>
</body>
</html>


6.Create a form for Student information. Write JavaScript code to find Total,Average, Result and Grade.

Code:

<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<script>
function calculate() {
var name = document.getElementById('name').value;
var mark1 = parseInt(document.getElementById('mark1').value);
var mark2 = parseInt(document.getElementById('mark2').value);
var mark3 = parseInt(document.getElementById('mark3').value);
var total = mark1 + mark2 + mark3;
var average = total / 3;
var result = "Student Name: " + name + "<br>" +
"Total Marks: " + total + "<br>" +
"Average Marks: " + average + "<br>";
if (average >= 90) {
result += "Result: Pass<br>" +
"Grade: A";
} else if (average >= 80) {
result += "Result: Pass<br>" +
"Grade: B";
} else if (average >= 70) {
result += "Result: Pass<br>" +
"Grade: C";
} else if (average >= 60) {
result += "Result: Pass<br>" +
"Grade: D";
} else {
result += "Result: Fail<br>" +
"Grade: F";
}

document.getElementById('result').innerHTML = result;
}
</script>
<body>
<h2>Student Information</h2>
<form id="studentForm">
Name:<input type="text" id="name" name="name"><br><br>
Mark1:<input type="number" id="mark1" name="mark1"><br><br>
Mark2:<input type="number" id="mark2" name="mark2"><br><br>
Mark3:<input type="number" id="mark3" name="mark3"><br><br>
<input type="button" value="Calculate" onclick="calculate()">
<p id="result"></p>
</body>
</html>





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

Code:
<!DOCTYPE html>
<html>
<head>
<title>Employee Salary Details</title>
<meta charset="utf-8">
<script type = "text/javascript">
function cal()
{
var ename=document.getElementById("empname").value;
var eno=parseInt(document.getElementById("empno").value);
var basic=parseInt(document.getElementById("bpay").value);
var hra=basic*0.15;
var da=basic*0.10;
var gross=parseFloat(basic)+hra+da;
var pf=gross*0.05;
var tax=gross*0.20;
var deductions=pf+tax;
var netsalary=gross-deductions;
var table = "<table border=2><tr><th colspan=2 align='center'>Employee Salary Details</th></tr>
<tr><td>Empname</td><td>"+ename+"</td></tr>
<tr><td>Empno</td><td>"+eno+"</td></tr><tr>
<td>Basic Pay</td><td>"+basic+"</td></tr>
<tr><td>HRA</td><td>"+hra+"</td></tr>
<tr><td>DA</td><td>"+da+"</td></tr>
<tr><td>Gross</td><td>"+gross+"</td></tr>
<tr><td>PFs</td><td>"+pf+"</td></tr>
<tr><td>TAX</td><td>"+tax+"</td></tr>
<tr><td>DEDUCTIONS</td><td>"+deductions+"</td></tr>
<tr><td>NETSALARY</td><td>"+netsalary+"</td></tr></table>";
document.body.innerHTML += table;
}
</script>
<style type="text/css">
table,tr,th,td{
border:3px solid black;
border-collapse:collapse;
}
td{
padding:5px;
}
</style>
</head>
<body>
<form name="myform">
<table>
<tr>
<th colspan=2 align="center">Employee Salary Details</th>
</tr>
<tr><td>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="bpay" /></td>
</tr>
<tr>
<td colspan=2 align="center"><input type="button" value="ShowEmployeeDetails"
onclick="cal()" />
</table>
</form>
</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 .

<!DOCTYPE html>
<html>
<head>
<title>Change Background Color Based on Day</title>
</head>
<body style="background-color: <?php echo getBackgroundColor(); ?>;">

<h1>Welcome to Blackeye001</h1>
<p>Today is <?php echo date("l"); ?>.</p>

<?php
function getBackgroundColor() {
$dayOfWeek = date("l");
$colorMap = array(
"Monday" => "Light Coral",
"Tuesday" => "Light Blue",
"Wednesday" => "Light Gray",
"Thursday" => "Green",
"Friday" => "#Light Brown",
"Saturday" => "Yellow",
"Sunday" => "Light Pink"
);
$defaultColor = "white";
return isset($colorMap[$dayOfWeek]) ? $colorMap[$dayOfWeek] : $defaultColor;
}
?>
</body>
</html>





9.Write a simple program in PHP for i) generating Prime number ii) generate
Fibonacci series.

i:Prime Number

<html>
<body>
<?php
$number = 11;
$count=0;
for ( $i=1; $i <= $number; $i++)
{
if (($number % $i)==0)
{
$count++;
}
}
if ($count < 3)
{
echo "$number is a prime number.";
}
else
{
echo "$number is not a prime number.";
}
?>
</body>
</html>


ii:Fibonacci series.

<html>
<body>
<?php
function Fibonacci($n){
$num1 = 0;
$num2 = 1;
$counter = 0;
while ($counter < $n){
echo ' '.$num1;
$num3 = $num2 + $num1;
$num1 = $num2;
$num2 = $num3;
$counter = $counter + 1;
}
}
$n = 10;
Fibonacci($n);
?>
</body>
</html>

10.Write a PHP program to remove duplicates from a sorted list the below code is to exectue through php environment or command line 

<html>
<body>
<?php
function removeDuplicates($array){
$result=array_values(array_unique($array));
return $result;
}
$List=[1,1,2,2,3,3,4,4,5,6,6,7];
$sortedList=removeDuplicates($List);
echo"Original List:";
print_r($List);
echo"<br>Sorted List:";
print_r($List);
?>
</body>
</html>

 This code you can execute in XAMP server 

11:Write a PHP Script to print the following pattern on the Screen:
*****
****
 ***
  **
  *
<html>
<body>
<?php
$rows=5;
for($i=$rows;$i>0;$i--){
for($j=$rows-$i;$j>0;$j--){
echo"&nbsp;";
}
for($k=0;$k<$i;$k++){
echo"*";
}
echo"<br>";
}
?>
</body>
</html>

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

<?php
$data=[
['id'=>1,'name'=>'blackeye','age'=>39],
['id'=>2,'name'=>'shaz','age'=>26],
['id'=>3,'name'=>'shahin','age'=>32],
['id'=>4,'name'=>'sandy','age'=>59]
];
function serachByCriteria($data,$criteria)
{
$result=[];
foreach($data as $entry){
$match=true;
foreach($criteria as $key => $value){
if(!isset($entry[$key])||$entry[$key]!=$value){
$match=false;
break;
}
}
if($match){
$result[]=$entry;
}
}
return $result;
}
$criteria=['age'=>39];
$searchResult=serachByCriteria($data,$criteria);
echo"Search Result:<br>";
print_r($searchResult);
?>

"This program defines an array of users and provides a simple HTML form for the user to input search criteria (ID, Name, Age, or City) and a corresponding value. The PHP script then searches the data array based on the specified criteria and displays the results." 

13.Write a function in PHP to generate captcha code


<html>
<body>

<?php
function generateCaptcha($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charLength = strlen($characters);
$captchaCode = '';
for ($i = 0; $i < $length; $i++) {
$captchaCode .= $characters[rand(0, $charLength - 1)];
}
return $captchaCode;
}
$captcha = generateCaptcha();
echo "Generated Captcha Code: $captcha";
?>
</body>
</html>

You can adjust the $characters string to include or exclude certain characters based on your requirements. The example usage at the end demonstrates how to call the function and display the generated captcha code."

14.  Write a Program to store and read image from Database.
[while creating with mysql make sure you grant all the persmission to store image and the table name datatype]
step1: start you xampp server enable apache and mysql
step2: go to localhost then navigat to localhost and go the phpmyadmin tab
then click on database 
and create a datbase as "img" click on create
and then create a table click on sql tab
CREATE TABLE image (
    id INT PRIMARY KEY AUTO_INCREMENT,
    image_name VARCHAR(255),
    image_type VARCHAR(255),
    image_data LONGBLOB
);
step3:once creating make sure you give all the permission for the database all privileges
and go to your Code Editor
and type the code 
step4:save the file as img.php 
step5:then enter the follow code 

<?php
error_reporting(E_ALL);
$conn = new mysqli("localhost", "root", "", "img");

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

if (isset($_GET['id'])) {
// display image
$id = intval($_GET['id']);
$stmt = $conn->prepare("SELECT image_type, image_data FROM image WHERE id=?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {
$stmt->bind_result($imageType, $imageData);
$stmt->fetch();
header("Content-Type:" . $imageType);
echo $imageData;
exit;
} else {
die("Error executing statement: " . $stmt->error);
}
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
// upload
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageName = $_FILES["image"]["name"];
$imageType = $_FILES["image"]["type"];

$stmt = $conn->prepare("INSERT INTO image (image_name, image_type, image_data) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $imageName, $imageType, $imageData);

if ($stmt->execute()) {
// Success
} else {
die("Error executing statement: " . $stmt->error);
}
}

function displayImages($conn)
{
$sql = "SELECT id, image_name FROM image";
$stmt = $conn->prepare($sql);

if ($stmt->execute()) {
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
echo "<img src='?id=" . $row["id"] . "' alt='" . $row["image_name"] . "'><br>";
}
} else {
die("Error executing query: " . $stmt->error);
}
}
?>

<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h1>Upload Image</h1>
<form method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="submit" name="submit">
</form>
<h2>Uploaded Images:</h2>
<?php displayImages($conn); ?>
<?php $conn->close(); ?>
</body>
</html>


15.Write a program in PHP to read and write file using form control.
[make sure your XAMPP Server is ready ]
Then follow the steps 
1)Create index.html file and wrtie the code
<!DOCTYPE html>
<html>
<head>
<title>File Read and Write</title>
</head>
<body>
<form action="FileReadWrite.php" method="post">
<label for="textdata">Text Data:</label>
<input type="text" name="textdata" id="textdata">
<input type="submit" value="Write to File"><br><br>
</form>
<form action="FileReadWrite.php" method="post" enctype="multipart/form-data">
<label for="filedata">Select File:</label>
<input type="file" name="filedata" id="filedata">
<input type="submit" value="Read File Contents"><br><br>
</form>
</body>
</html>


2)create FileReadWrite.php make sure you give correct name ans write the code 
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['textdata'])) {
file_put_contents("output.txt", $_POST['textdata']);
echo "Data written to file.<br>";
}

if (!empty($_FILES['filedata']['tmp_name'])) {
$fileContent = file_get_contents($_FILES['filedata']['tmp_name']);
echo "File Content: " . htmlspecialchars($fileContent) . "<br>";
}
}
?>


Make sure you have both files in same directory!!

16:Write a program in PHP to add, update and delete using student database.
Step1: Start you XAMPP Server (start Apache and Mysql server)
Step2:Create Database ans Tables 
->Open your brower and navigate to (http://localhost) which gives an interface click on
[phpmyadmin] tab which give msql database
->create a database as myDB 
steps1->click on database enter myDB and click on create 
steps2->click on sql and create the table
CREATE TABLE student (
    regno VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255),
    age INT,
    course VARCHAR(255)
);
click on Go  then 
go to code Editor and enter the below code  


<?php
$conn = new mysqli("localhost", "root", "", "myDB");


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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$regono = $_POST['regno'];
$name = $_POST['name'];
$age = $_POST['age'];
$course = $_POST['course'];

switch ($_POST['action']) {
case 'Add':
$sql = "INSERT INTO student VALUES('$regono','$name','$age','$course')";
break;
case 'Update':
$sql = "UPDATE student SET name='$name', age='$age', course='$course' WHERE regno='$regono'";
break;
case 'Delete': // Corrected the semicolon here
$sql = "DELETE FROM student WHERE regno='$regono'";
break;
}

if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
function displayStudents($conn)
{
$sql = "SELECT * FROM student";
$result = $conn->query($sql);

if ($result === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>Reg NO</th><th>Name</th><th>Age</th><th>Course</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["regno"] .
"</td><td>" . $row["name"] .
"</td><td>" . $row["age"] .
"</td><td>" . $row["course"] .
"</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
}
error_reporting(E_ALL);
ini_set('display_errors', 1);


?>

<html>

<head>
<title>Student Database Management</title>
</head>

<body>
<h1>Manage Students</h1>
<form method="post">
Reg no:<input type="text" name="regno" required><br><br>
Name :<input type="text" name="name"><br><br>
Age :<input type="number" name="age"><br><br>
Course:<input type="text" name="course"><br><br>

<input type="submit" name="action" value="Add"><br><br>
<input type="submit" name="action" value="Update"><br><br>
<input type="submit" name="action" value="Delete"><br><br>
</form>
<?php
displayStudents($conn);
$conn->close();
?>
</body>

</html>


Make sure the table name database name is correct!!!

17 Write a program in PHP to Validate Input

<html>
<head>
<title>Validation</title>
</head>
<body>
<form method="post">
Name:<input type="text" name="name"><br><br>
Email:<input type="text" name="email"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name=$_POST['name'];
$email=$_POST['email'];

if(empty($name)){
echo "Name is required.<br><br>";

}else{
echo "Name:".$name."<br><br>";
}
if(empty($email)){
echo "Email is required.<br><br>";
}elseif(!filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "Invalid email format.<br><br>";
}else{
echo "Email:".$email."<br><br>";
}
}
?>


18 Write a program in PHP for setting and retrieving a cookie

<?php
// Setting a cookie
$cookie_name = "user";
$cookie_value = "Blackeye";
setcookie($cookie_name, $cookie_value, time() + (24 * 60 * 60)); // Cookie set for 1 day

// Retrieving a cookie
if (isset($_COOKIE[$cookie_name])) {
echo "Cookie '" . $cookie_name . "' has a value: " . $_COOKIE[$cookie_name];
} else {
echo "Cookie named '" . $cookie_name . "' is not set!";
}
?>


The cookie time and be customised 

19 Write a PHP program to Create a simple webpage of a college.
Here we have to create 4 pages 
1. Create index.php file
<html>
<head>
<title>BlackEye Institution</title>
<style>
body{
font-family: Georgia , sans-serif;
}
header{
background-color:#5c5656;
padding: 100px;
text-align: center;
}
nav{
background-color:#fc897e;
margin: 20px 0;
text-align: center;
}
nav a{
background-color:#f2c4bf;
margin: 0 15px;
}
</style>
</head>
<body>
<header>
<img src="icon.png" alt="BlackEye Institution"
width="200">
<h1>BlackEye Institution</h1>
<p>#391 7th Cross, Bhuvaneshwari Nagar, R T Nagar post Bangalore</p>
</header>
<nav>
<a href="index.php">Home</a>
<a href="about.php">About Us</a>
<a href="course.php">Courses</a>
<a href="contact.php">Contact Us</a>
</nav>
<main>
<h2>Welcome to BlackEye Institution</h2>
<p>We also provide training on Computer based courses conducted by
Blackeye Securities</p>
</main>
</body>
</html>

2. about.php file
<html>
<head>
<title>About us</title>
</head>
<body>
<h1>About us</h1>
<p>Blackeye Institution was founded in the year 2020 with the aim
to provide best quality of courses to the students provided by
experts in top most companies</p>
</body>
</html>
 3. create course .php
<html>
<head>
<title>About us</title>
</head>
<body>
<h1>Courses</h1>
<h2>Networking</h2>
<h3>OWSAP</h3>
<h4>Bug-Bounty</h4>
</body>
</html>

4.  create contact.php
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact Us</h1>
<p>Address:#391 6th Cross, Bhuvaneshwari Nagar, R T Nagar post Bangalore</p>
<p>Phone:080-123456,789101112
<p>Email:blackeye@security.com</p>
</body>
</html>

if you want any image to be added make sure you give the proper path if not store the image in store the image in the same directory


20:Write a program in PHP for exception handling for 

i) divide by zero 
<?php

function divide($numerator, $denominator) {
try {
if ($denominator === 0) {
throw new Exception("Cannot divide by zero!");
}

$result = $numerator / $denominator;
echo "Result: $result";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}

// Example usage value can be changed based on user
$numerator = 10;
$denominator = 0;

divide($numerator, $denominator);

?>



ii) checking date format.
<?php function isValidDateFormat($date, $format = 'Y-m-d') { $dateTime = DateTime::createFromFormat($format, $date); return $dateTime && $dateTime->format($format) === $date; } $dateToCheck = '2022-31-03'; if (isValidDateFormat($dateToCheck)) { echo "$dateToCheck is a valid date in the format Y-m-d."; } else { echo "$dateToCheck is not a valid date in the format Y-m-d."; } ?>


Comments

  1. Thanks for this ....It helped very much 🤓

    ReplyDelete
    Replies
    1. thanks!! share it with your friends and support!!

      Delete

Post a Comment

Popular posts from this blog

Mobile Application Development Lab

Python Programming