Lab Manual Web Desigining 3rd Sem-1
Lab Manual Web Desigining 3rd Sem-1
(LAB MANUAL)
Semester Course Code Name of the course L T P Credit
s
III IT Web Development Lab 0 0 2 1
List of Experiment
1. Design an html form for displaying information using interactive css including images, tables.
2. Create a webpage with HTML describing your department with following specification:
a.Change the background color of the page. At the bottom create a link to take user to the top of the page.
b. Insert an image and create a link such that clicking on image takes user to other page.
c. Also apply font styling like italics, underline and two other fonts to words you find appropriate. Also use header
tags.
3. Write a JavaScript to design a simple calculator to perform the following operations: sum, product, difference and
quotient.
4. Write a JavaScript to validate the following fields of employee on html form: email, name, mobile no., address,
salary.
5. Develop and demonstrate a HTML file that includes JavaScript script that uses functions for the following
problems
Parameter: A string Output: Length of the String
Parameter: A number Output: The number with its digits in the reverse order
6. Develop and demonstrate a HTML file that includes JavaScript for the following problems:
Input: A starting and ending number
Output: find all the prime numbers between starting and ending number.
7. Write a PHP program to display a digital clock which displays the current time of the server.
8. Write a PHP program to implement sign-In and Sign-out functionality.
9. Write a PHP program to keep track of the number of visitors visiting the Web page and to display this count of
visitors, with proper headings.
10. Write a PHP code to implement AJAX functionality.
Experiment No : 0
Front-End Technologies:
1. Server-Side Languages:
o Languages like PHP, Python, Ruby, Java, and Node.js are
used for server-side scripting. They handle data processing,
database interactions, and business logic.
2. Web Servers:
o Web servers (e.g., Apache, Nginx) deliver web content to
users' browsers. They handle incoming requests, execute
server-side code, and send back responses.
3. Databases:
o Databases (e.g., MySQL, PostgreSQL, MongoDB) store
and manage structured data used by web applications. They
enable data persistence and retrieval.
4. Server-Side Frameworks:
o Frameworks such as Django (Python), Ruby on Rails
(Ruby), Express.js (Node.js), and Spring (Java) provide
tools and libraries to streamline back-end development.
Types of Websites:
1.E-commerce Websites:
3. Informational Websites:
5. Portfolio Websites:
Examples: Behance, Dribbble, photographer portfolios.
6. Educational Websites:
1. HTTP/HTTPS:
o HTTP (Hypertext Transfer Protocol) and HTTPS (Secure
HTTP) are protocols for transferring data between web
servers and browsers. HTTPS ensures secure
communication via encryption.
2. Web Standards:
o Standards like HTML5, CSS3, and ECMAScript
(JavaScript) are defined by organizations like the W3C
(World Wide Web Consortium) to ensure compatibility and
interoperability across different browsers and devices.
Theory :
1. HTML Structure:
o Form Elements: Standard HTML elements such as
2. CSS Interactivity:
o Interactive CSS: Utilize CSS pseudo-classes (like
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Information Form</title>
<!-- Link to CSS -->
<link rel="stylesheet" href="styles.css">
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}
.container {
max-width: 800px;
margin: auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
h1, h2 {
text-align: center;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
}
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
.image-display {
text-align: center;
margin-top: 20px;
}
#preview {
max-width: 100px;
margin-top: 10px;
display: none;
}
.preview-toggle {
display: inline-block;
padding: 10px;
background-color: #007bff;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
margin-bottom: 10px;
}
.preview-toggle:hover {
background-color: #0056b3;
}
.table-container {
margin-top: 30px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #007bff;
color: white;
}
td img.table-image {
width: 50px;
height: 50px;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="container">
<h1>Interactive Information Form</h1>
<!-- Form Section -->
<form id="infoForm">
<!-- Text Input -->
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
Explanation
1. HTML Structure:
o Form Elements: The form contains text input
3. CSS Tricks:
o Image Preview without JavaScript: The checkbox
Output :
Conclusion :
By utilizing HTML and CSS creatively, we can design an
interactive form that allows users to input information, display
an image, and view data in a structured table format—all
without using JavaScript. The use of CSS pseudo-classes and
properties allows for basic interactivity and a visually
appealing user interface.
Experiment no :02
Aim : Create a webpage with HTML describing your
department with following specification:
a.Change the background color of the page. At the bottom
create a link to take user to the top of the page.
b. Insert an image and create a link such that clicking on image
takes user to other page.
c. Also apply font styling like italics, underline and two other
fonts to words you find appropriate. Also use header tags.
Theory :
Change the Background Color: We will set a background color
for the page using CSS.
Link to Top of the Page: Add a hyperlink at the bottom to allow
the user to scroll back to the top.
Clickable Image: Insert an image that, when clicked, redirects the
user to another page.
Font Styling: Use different font styles, such as italics, underline,
and different font families for specific text. Also, use header tags for
structuring content.
Program :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Overview</title>
<style>
/* Change background color */
body {
background-color: #e8f4f8;
font-family: Arial, sans-serif;
color: #333;
padding: 20px;
}
.top-link:hover {
color: #00334d;
}
.underline {
text-decoration: underline;
}
.font-change {
font-family: 'Courier New', Courier, monospace;
}
</style>
</head>
<body>
</body>
</html>
Explanation of the HTML Code :
Conclusion :
This HTML page is styled and structured to meet the
requirements using HTML and CSS. The use of different font
styles, background color, clickable image, and navigation links
provide a complete and interactive webpage.
Experiment No :03
Aim : Write a JavaScript to design a simple calculator to perform the
following operations: sum, product, difference and quotient.
Theory :
The document type (<!DOCTYPE html>) specifies that this is an HTML5
document.
The <html lang="en"> element specifies that the language of the content is
English.
The <head> section contains metadata about the document, such as character
set (UTF-8) and viewport settings for responsive design.
The <title> tag defines the title of the webpage as "Calculator".
<input type="text" id="text1" placeholder="Enter first number">: A text input
field where the user can enter the first number. The id attribute allows us to access
this element using JavaScript.
<select id="select"> ... </select>: A dropdown menu for selecting the
arithmetic operation (+, -, *).
<input type="text" id="text2" placeholder="Enter second number">: Another
text input field where the user can enter the second number.
<button onclick="ans()">ANS</button>: A button that triggers the ans()
function when clicked.
<input type="text" id="text3" readonly placeholder="Result">: A text input
field that displays the result. It is set to readonly so that users cannot modify its
content manually.
o Function ans(): This function is executed when the user clicks the
"ANS" button.
o Variable Initialization:
▪ var a = parseInt(document.getElementById("text1").value);:
▪ Retrieves the value entered in the first input field
(text1), converts it to an integer using parseInt, and
stores it in the variable a.
▪ var b = parseInt(document.getElementById("text2").value);:
▪ Retrieves the value entered in the second input field
(text2), converts it to an integer, and stores it in the
variable b.
▪ var opt = document.getElementById("select").value;:
Gets the selected operation (+, -, or *) from the
▪
dropdown menu.
▪ var result=document.getElementById("text3").value;:
▪ Initializes the variable result with the current value of
the result input field (text3). However, this line is
unnecessary as it is immediately overwritten in the
subsequent code.
o Conditional Logic for Calculation:
▪ if (opt == "+"): Checks if the selected operation is addition.
▪ else if (opt == "-"): Checks if the selected operation is
subtraction.
▪ else if (opt == "*"): Checks if the selected operation is
multiplication.
▪ For each condition, it performs the corresponding arithmetic
operation and assigns the result to the result variable.
▪ If none of the conditions match, it sets the result to
"Something went wrong" (this should not normally happen
given the dropdown options).
o Display the Result:
▪ document.getElementById("text3").value = result;: Displays
the computed result in the text3 input field.
Program :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<input type="text" id="text1" placeholder="Enter first number"><br>
<select id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
</select><br>
<input type="text" id="text2" placeholder="Enter second number"><br>
<button onclick="ans()">ANS</button><br>
<input type="text" id="text3" readonly placeholder="Result">
</body>
<script>
function ans(){
// Convert input values to numbers
var a = parseInt(document.getElementById("text1").value);
var b = parseInt(document.getElementById("text2").value);
var opt = document.getElementById("select").value;
var result=document.getElementById("text3").value;
if (opt == "+") {a
result = a + b;
} else if (opt == "-") {
result = a - b;
} else if (opt == "*") {
result = a * b;
} else {
result = "Something went wrong";
}
Output :
Conclusion : The HTML and JavaScript code provided creates a
simple calculator that can perform basic arithmetic operations:
addition, subtraction, and multiplication. The calculator takes two input
numbers from the user and an operation from a dropdown menu. When
the user clicks the "ANS" button, the JavaScript function ans() is
executed to perform the selected arithmetic operation and display the
result.
Experiment No :04
Aim : Write a JavaScript to validate the following fields of
employee on html form: email, name, mobile no., address, salary.
Theory :
1. HTML Form Structure:
o The form consists of input fields for Name, Email, Mobile
Number, Address, and Salary.
o Each input field is wrapped in a .form-group div, with an
accompanying <label> for accessibility.
o Each field has a corresponding <div> with the class="error" to
display validation error messages.
2. CSS Styles:
o Basic styling is provided to make the form look clean and readable.
o The. error class styles the error messages in red color and with a
smaller font size.
o The input fields and the submit button have padding and styling for
a better user experience.
3. JavaScript Validation (validate Form function):
o The function clears any previous error messages by setting the
inner text of all error <div> elements to an empty string.
o It then retrieves the values of each input field and trims any extra
whitespace.
o Each field is validated for:
▪ Name: Ensuring it is not empty.
▪ Email: Ensuring it is not empty and contains both '@' and '.'
characters.
▪ Mobile Number: Ensuring it is not empty, is exactly 10
digits, and contains only numbers.
▪ Address: Ensuring it is not empty.
▪ Salary: Ensuring it is not empty, is a number, and is greater
than 0.
o If any validation fails, an error message is displayed next to the
corresponding field and the function returns false to prevent form
submission.
o If all validations pass, the function returns true and the form is
submitted.
Program :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Form</title>
<style>
/* CSS styles for the form */
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"], textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.error {
color: red;
font-size: 12px;
margin-top: 5px;
}
input[type="submit"] {
padding: 10px 15px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form id="employeeForm" onsubmit="return validateForm()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<div id="nameError" class="error"></div>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="mobile">Mobile No.:</label>
<input type="text" id="mobile" name="mobile">
<div id="mobileError" class="error"></div>
</div>
<div class="form-group">
<label for="address">Address:</label>
<textarea id="address" name="address"></textarea>
<div id="addressError" class="error"></div>
</div>
<div class="form-group">
<label for="salary">Salary:</label>
<input type="text" id="salary" name="salary">
<div id="salaryError" class="error"></div>
</div>
<script>
function validateForm() {
// Clear previous errors
document.getElementById("nameError").innerText = "";
document.getElementById("emailError").innerText = "";
document.getElementById("mobileError").innerText = "";
document.getElementById("addressError").innerText = "";
document.getElementById("salaryError").innerText = "";
// Name validation
if (name === "") {
document.getElementById("nameError").innerText = "Please enter your name.";
isValid = false;
}
// Email validation
if (email === "") {
document.getElementById("emailError").innerText = "Please enter your email.";
isValid = false;
} else if (!email.includes('@') || !email.includes('.')) {
document.getElementById("emailError").innerText = "Please enter a valid email address.";
isValid = false;
}
// Address validation
if (address === "") {
document.getElementById("addressError").innerText = "Please enter your address.";
isValid = false;
}
// Salary validation
if (salary === "") {
document.getElementById("salaryError").innerText = "Please enter your salary.";
isValid = false;
} else if (parseFloat(salary) <= 0) {
document.getElementById("salaryError").innerText = "Please enter a valid salary.";
isValid = false;
}
return isValid;
}
</script>
</body>
</html>
Output :
Conclusion :
The provided HTML form and JavaScript validation script offer a straightforward
way to ensure that users enter valid data into each field before submitting the
form. By using simple checks for each input type—such as verifying the presence
of required fields, correct formatting for emails, appropriate number lengths for
mobile numbers, and valid numerical entries for salaries—this solution helps
prevent incorrect or incomplete submissions. The CSS adds basic styling for a
user-friendly interface and clear error messages. This approach improves the
overall user experience by guiding users to provide accurate and complete
information, reducing errors, and making the form more reliable.
Experiment No : 05
Aim : Develop and demonstrate a HTML file that includes JavaScript script that uses
functions for the following problems
Parameter: A string Output: Length of the String
Parameter: A number Output: The number with its digits in the reverse order
Theory :
Problem 1: Length of a String
Input:
The user provides a string input through an HTML input field (text box).
Process:
The length of a string refers to the number of characters it contains, including spaces and special
characters.
JavaScript provides the .length property, which returns the total count of characters in a string. This is
a simple and efficient way to find the length of any string.
Steps involved:
Input:
The user provides a number input through an HTML number input field.
Process:
Reversing the digits of a number is not directly feasible since numbers do not have a built-in reverse
method in JavaScript. To reverse a number, we need to treat the number as a string, as strings can be
manipulated easily.
Steps involved:
1. Convert the number to a string using the value of the input field.
2. Use the split() function to convert the string into an array of individual digits.
3. Use the reverse() function to reverse the array.
4. Use the join() function to convert the reversed array back into a string.
5. Convert the string back to a number if required or display it directly.
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String and Number Operations</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
margin-bottom: 20px;
}
input[type="text"], input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
button {
width: 100%;
padding: 10px;
background-color: #28a745;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.output {
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h2>String Length</h2>
<input type="text" id="stringInput" placeholder="Enter a string">
<button onclick="calculateStringLength()">Get Length</button>
<div class="output" id="stringLengthOutput"></div>
</div>
<div class="container">
<h2>Reverse Number</h2>
<input type="number" id="numberInput" placeholder="Enter a number">
<button onclick="reverseNumber()">Reverse Digits</button>
<div class="output" id="numberReverseOutput"></div>
</div>
<script>
// Function to calculate the length of a string
function calculateStringLength() {
const inputString = document.getElementById('stringInput').value;
const length = inputString.length;
document.getElementById('stringLengthOutput').innerText = `Length: ${length}`;
}
</body>
</html>
Output :
Conclusion: This HTML and JavaScript program successfully demonstrates two
essential JavaScript string and array manipulation techniques:
Through user input and dynamic JavaScript functionality, this program shows the power of
JavaScript in building interactive web applications. It highlights the use of the DOM
(Document Object Model) to interact with HTML elements, retrieve user inputs, process
data, and display results dynamically.
Experiment no :06
Aim: Develop and demonstrate a HTML file that includes JavaScript for the following problems:
Input: A starting and ending number
Output: find all the prime numbers between starting and ending number.
Theory :
1. HTML Structure:
o The user enters a starting number and an ending number into two input boxes.
o There is a button that, when clicked, triggers the findPrimes() function.
2. JavaScript Logic:
o isPrime(n) function:
▪ This function checks if a number is prime. A prime number is a
number greater than 1 that can only be divided by 1 and itself.
▪ It loops from 2 up to the square root of the number (n). If any of these
numbers divide n evenly, it's not prime.
o findPrimes() function:
▪ This function gets the starting and ending numbers from the input
fields.
▪ It loops from the starting number to the ending number and uses the
isPrime(n) function to check if each number is prime.
▪ If a number is prime, it adds it to a list of primes.
▪ Finally, it shows the result on the page by updating the result div with
the list of primes or a message saying no primes were found.
Example:
• Start Number: 10
• End Number: 20
After clicking the "Find Prime Numbers" button, the output will be:
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<br>
<br>
<div id="result"></div>
<script>
function isPrime(n) {
return true;
function findPrimes() {
</script>
</body>
</html>
Output:
Conclusion:
This example demonstrates how to use basic HTML and JavaScript to solve the problem of
finding prime numbers in a given range. The code is simple and easy to understand:
• Input Validation: Ensures the user enters valid numbers (start should be smaller than
or equal to end, and both numbers must be positive).
• Prime Number Calculation: Efficiently finds primes using the fact that divisors of a
number only need to be checked up to its square root.
• Output: Clearly displays either the list of prime numbers or a message saying no
primes were found in the range.
Experiment no :07
Aim : Write a PHP program to display a digital clock which displays the current time of the
server.
1. PHP Basics: PHP is a server-side scripting language, which means the code runs on
the server and not in the user's browser.
2. Date and Time Functions in PHP: PHP has built-in functions to handle date and
time, such as date() and time(). We'll use these to get the current time.
Step-by-Step Explanation
1. Use of date() Function: PHP's date() function is used to format the date and time. You
can specify the format you want. For example:
o H for the hour (24-hour format)
o i for minutes
o s for seconds
2. HTML and CSS for Styling: We can use HTML to display the time and basic CSS
for styling to make the clock look digital.
3. Refreshing the Clock: To update the clock every second, we can use JavaScript to
refresh the displayed time dynamically without refreshing the page.
Here’s a simple PHP program that displays the current server time:
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Digital Clock</title>
<style>
.clock {
font-family: 'Courier New', Courier, monospace;
color: #333;
font-size: 50px;
text-align: center;
margin-top: 20%;
}
</style>
</head>
<body>
<script>
// JavaScript to refresh the time every second
setInterval(function() {
// Get the current time
var xhr = new XMLHttpRequest();
xhr.open('GET', 'time.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// Update the clock div with the new time
document.getElementById("clock").innerHTML = xhr.responseText;
}
};
xhr.send();
}, 1000);
</script>
</body>
</html>
Breakdown of Code
1. HTML Structure:
o We use a <div> element with the class clock to display the time.
o The id="clock" is used to update the clock every second using JavaScript.
2. PHP Script:
o The date() function is used to fetch the current time. We use the format "H:i:s"
which represents hours, minutes, and seconds in 24-hour format.
o This time is initially displayed on the page when it loads.
3. CSS Styling:
o Basic styling is applied to make the clock text look bigger and centered.
4. JavaScript:
o The setInterval() function is used to execute a piece of code every 1000
milliseconds (1 second). This function sends an asynchronous request to the
server to get the updated time.
o The XMLHttpRequest object is used to send an HTTP request to a separate PHP
file (time.php) that will return the current time without refreshing the page.
The time.php file only contains the PHP code that returns the current time, and it will be
requested every second by the JavaScript code in the main file:
<?php
// Return the current time in H:i:s format
echo date("H:i:s");
?>
1. When the page is loaded, the initial server time is shown in the clock.
2. Every second, the JavaScript sends a request to time.php to get the updated time and
refresh the clock display.
3. The PHP code ensures that the time is always based on the server's local time, so it
will not depend on the user's local time.
Conclusion : PHP fetches the server time using the date() function.
JavaScript ensures the time is updated every second by fetching new data from the server
using AJAX.
This is a simple, real-time digital clock using a combination of PHP and JavaScript.
Experiment No: 08
Aim : Write a PHP program to implement sign-In and Sign-out functionality.
1. Theory : Session Management: In PHP, sessions are used to store user
information across multiple pages. We use sessions to remember if a user is signed in
or not.
2. Sign-In: A user provides their credentials (username and password), which are
checked against predefined values (or values from a database). If the credentials
match, the user is signed in, and the session is created.
3. Sign-Out: When the user clicks sign-out, the session is destroyed, logging the user
out.
4. Security Note: In real-world applications, passwords should be hashed, and more
advanced authentication techniques should be used (e.g., database authentication). For
simplicity, this example uses hardcoded values.
<?php
// Start the session
session_start();
// If form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Hardcoded credentials (for demonstration purposes)
$valid_username = 'student';
$valid_password = 'password123';
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign-In</title>
</head>
<body>
<h2>Sign-In</h2>
<?php
// Display the error message if credentials are incorrect
if (isset($error)) {
echo "<p style='color:red;'>$error</p>";
}
?>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
</body>
</html>
<?php
// Start the session
session_start();
</body>
</html>
<?php
// Start the session
session_start();
1. Session Management:
o session_start(): This function is used to start the session. Sessions allow us to
store information (like the username) across different pages.
o Sign-In Flow:
▪ When the user submits the form, the script checks the entered
username and password against the hardcoded credentials.
▪ If they match, the user is signed in by storing their username in the
session ($_SESSION['username']), and they are redirected to the welcome
page.
o Sign-Out Flow:
▪ When the user clicks "Sign Out", the session is destroyed using
session_destroy(), and they are redirected back to the sign-in page.
2. HTML Forms:
o The sign-in form collects the username and password.
o When the form is submitted, it triggers a POST request to the same page, where
PHP processes the form data.
3. Redirection:
o If the user is already signed in, they are automatically redirected to the
welcome.php page.
o If a non-signed-in user tries to access the welcome.php page, they are redirected
back to the signin.php page.
4. Security Notes:
o The passwords should not be stored as plain text in a real-world application.
They should be hashed before storing in the database using password_hash() and
verified using password_verify().
o The session should be managed carefully to prevent attacks like Session
Hijacking.
Output :
When the user accesses the sign-in page (signin.php), they will see a simple form:
Conclusion :
This PHP program demonstrates a simple Sign-In and Sign-Out process using sessions. It
includes the following steps:
Theory :
File Handling in PHP: PHP provides functions for file operations such as reading from
and writing to files. We'll use these functions to store and update the visitor count.
Visitor Count: Every time someone visits the webpage, the PHP script will read the
current visitor count from a file, increase it by one, and save the updated count back to the
file.
Displaying the Count: The updated visitor count will be displayed on the webpage.
Program :
<?php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visitor Counter</title>
</head>
<body>
<h1>Welcome to Our Website</h1>
<p>This page has been visited <strong><?php echo $visitor_count; ?></strong> times.</p>
</body>
</html>
1. File Handling:
o file_exists($file): This
function checks if the file (counter.txt) exists. If it exists, we
read the current visitor count from the file.
o file_get_contents($file): This function reads the content of the file. In our case, it
retrieves the current visitor count stored in the counter.txt file.
o Increment the Visitor Count: Each time the page is loaded, we increase the
visitor count by 1.
o file_put_contents($file, $visitor_count): This function writes the updated visitor
count back to the counter.txt file, ensuring that the count persists across page
reloads.
2. Displaying the Count:
o The updated visitor count is displayed in the <p> tag using PHP's echo
statement (<?php echo $visitor_count; ?>).
3. Creating the Counter File:
o When the program is run for the first time, if the file counter.txt does not exist, it
will be created, and the visitor count will start at 1.
4. Page Layout:
o The webpage displays a simple message: "This page has been visited X
times," where X is the current visitor count.
Output :
How It Works
1. First Visit:
o If this is the first time someone is visiting the page, the file counter.txt will not
exist. The script will create the file and initialize the visitor count to 1.
2. Subsequent Visits:
o For every subsequent visit or refresh, the script reads the current count from
counter.txt, increments it by 1, and writes the updated count back to the file.
3. Persistent Storage:
o The visitor count is stored in the file (counter.txt), ensuring that even if the
server is restarted or the page is closed, the count is maintained and updated
across visits.
Conclusion :
PHP File Handling: We used PHP’s file handling functions (file_exists(), file_get_contents(),
and file_put_contents()) to store and update the visitor count.
Visitor Tracking: Every time the webpage is visited, the script updates the visitor count
by reading from and writing to a file.
Simple and Efficient: This method is simple and efficient for tracking visitors in small-
scale applications.
Experiment No :10
Aim : Write a PHP code to implement AJAX functionality.
Introduction to AJAX
AJAX (Asynchronous JavaScript and XML) allows web pages to be updated asynchronously
by exchanging data with the server in the background. This means that parts of a web page
can be updated without reloading the entire page.
In PHP, we use AJAX to send a request to the server (PHP script) and get a response back, all
without refreshing the webpage.
1. AJAX Workflow:
o A JavaScript function sends a request to the server using the XMLHttpRequest
object (or fetch API in modern JavaScript).
o The server processes this request (in our case, using PHP) and sends back a
response.
o JavaScript updates the page with the new data without refreshing the entire
page.
2. Use Case Example:
o We’ll build a simple example where a user clicks a button, and AJAX fetches
the current time from the server using PHP. The result will be displayed on the
webpage without reloading it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with PHP</title>
<script>
function loadServerTime() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
</body>
</html>
<?php
// Get the current server time
$time = date('H:i:s');
1. AJAX (JavaScript):
• XMLHttpRequest(): This is a built-in JavaScript object used to send and receive data from the
server asynchronously.
• xhr.open('GET', 'time.php', true): This function sets up the request to the server. We are using
the GET method to request data from time.php asynchronously (true).
• xhr.onreadystatechange: This event handler is called whenever the state of the request
changes. When the request is complete (readyState == 4) and successful (status == 200), the
response from the server is processed.
• xhr.responseText: This contains the data (the current time) returned by the server (the PHP
script).
• document.getElementById('result').innerHTML = xhr.responseText;: This updates the content
inside the <span> element with the ID result to display the server's response.
• date('H:i:s'): This PHP function retrieves the current server time in the format
hours:minutes:seconds.
• The time is then sent back to the client (JavaScript) as a response using echo.
3. HTML:
How It Works
1. The user loads the HTML page with a button labeled "Get Server Time."
2. When the user clicks the button, JavaScript sends an AJAX request to time.php.
3. time.php returns the current server time as a string.
4. The JavaScript code receives the response and updates the <span id="result"> element to
display the current time without reloading the page.
Output :
Conclusion :
AJAX allows us to send requests to the server and update parts of a web page without
reloading the whole page.
In this example, we used a simple AJAX call to get the current time from the server using
a PHP script.
AJAX Workflow: