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

Lab Session 09 WebEngineering

Uploaded by

Ayesha Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lab Session 09 WebEngineering

Uploaded by

Ayesha Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Web Design and Development

Department of CS and SE

Lab Session 9: PHP Sessions and Cookies

Exercise
1. Create a cookie named 'theme' that stores the user's preferred website theme. Allow the user to
select a theme from a dropdown menu and save it as a cookie. Retrieve the theme from the cookie
and apply it to the website layout.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Theme Selector</title>
</head>
<body>

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the selected theme from the form
if (isset($_POST['theme'])) {
$selectedTheme = $_POST['theme'];

// Set the theme cookie to store the selected theme


setcookie('theme', $selectedTheme, time() + (86400 * 30), "/"); //
Cookie valid for 30 days
}
}
?>
<div class="container">
<h2>Select a Theme</h2>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?


>">

<select name="theme" id="themeSelector">


<option value="light">Light Theme</option>
<option value="dark">Dark Theme</option>
<option value="blue">Blue Theme</option>
</select>
<button type="submit">Save Theme</button>
</form>
Web Design and Development

Department of CS and SE

</div>

<script>
// Retrieve the theme cookie value
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}

// Apply the stored theme when the page loads


document.addEventListener('DOMContentLoaded', () => {
const storedTheme = getCookie('theme');
if (storedTheme) {
document.body.className = storedTheme; // Apply the theme class to body
document.getElementById('themeSelector').value = storedTheme; // Set the
selected theme in dropdown
}
});
</script>

<style>
/* Define styles for different themes */
body {
font-family: Arial, sans-serif;
transition: background-color 0.3s ease;
align-items: center;
justify-content: center;
text-align: center;
}

button {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
outline: none;
Web Design and Development

Department of CS and SE

transition: background-color 0.3s ease;


}

button:hover {
background-color: #2980b9;
}

select {
padding: 10px;
font-size: 16px;
width: 100%;
border: 1px solid #ddd;
border-radius: 4px;
outline: none;
transition: border-color 0.3s ease;
}

.container {
color:black;
text-align: center;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;}

.light {
background-color: #f9f9f9;
color: #333;
}

.dark {
background-color: #333;
color: #f9f9f9;
}

.blue {
background-color: #3498db;
color: #fff;
}
</style>
Web Design and Development

Department of CS and SE

</body>
</html>

Output:
Light theme:

Dark Theme:
Web Design and Development

Department of CS and SE

Blue Theme:

2. Implement a login system using PHP sessions. Create a login form that accepts a username and
password. On successful login, store the user's ID and username in session variables. Restrict
access to certain pages only to authenticated users by checking the session variables.

SignUp Page:
<?php
Web Design and Development

Department of CS and SE

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "inventory";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Handle form submission

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
text-align: center;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
Web Design and Development

Department of CS and SE

h2 {
color: #333;
margin-bottom: 20px;
}

p {
color: #666;
margin-bottom: 20px;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
outline: none;
transition: background-color 0.3s ease;
}

button:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="container">
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?
>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Register</button>
<p>Already have an account? <a href="login.php">Login here</a></p>
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
Web Design and Development

Department of CS and SE

$password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hash


password

// Insert user into database


$sql = "INSERT INTO users (username, password) VALUES ('$username',
'$password')";

if ($conn->query($sql) === TRUE) {


echo "User registered successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} ?>
</form>
</div>
</body>
</html>

<?php
$conn->close();
?>

OUTPUT:
Web Design and Development

Department of CS and SE

LOGIN PAGE:

<?php
session_start();

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "inventory";

$conn = new mysqli($servername, $username, $password, $dbname);

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
text-align: center;
Web Design and Development

Department of CS and SE

background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
}

h2 {
color: #333;
margin-bottom: 20px;
}

p {
color: #666;
margin-bottom: 20px;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
outline: none;
transition: background-color 0.3s ease;
}

button:hover {
background-color: #2980b9;
}
</style>

</head>
<body>
<div class="container">
<h2>Login</h2>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?


>">
<label for="username">Username:</label>
Web Design and Development

Department of CS and SE

<input type="text" id="username" name="username" required><br><br>


<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
<p>Don't have an account? <a href="signUp.php">Register here</a></p>
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

// Retrieve user from database


$sql = "SELECT id, username, password FROM users WHERE username =
'$username'";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
// Authentication successful, set session variables
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['username'];

// Redirect to restricted page or dashboard


header("Location: dashboard.php");
exit();
} else {
echo "Invalid username or password.";
}
} else {
echo "Invalid username or password.";
}
}
?>
</form>
</div>
</body>
</html>

<?php
$conn->close();
?>

OUTPUT:
Web Design and Development

Department of CS and SE

RESTRICTED PAGE (DASHBOARD):

<?php
session_start();

// Check if user is not logged in, redirect to login page


if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Blog Page</title>
Web Design and Development

Department of CS and SE

<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f9f9f9;
}

header {
background-color: #333;
color: #fff;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}

.logo {
font-size: 24px;
font-weight: bold;
}

nav ul {
list-style-type: none;
margin: 0;
padding: 0;
}

nav ul li {
display: inline-block;
margin-right: 20px;
}

nav ul li a {
color: #fff;
text-decoration: none;
transition: color 0.3s ease;
}

nav ul li a:hover {
color: #ffd700;
}
Web Design and Development

Department of CS and SE

main {
padding: 20px;
display: flex;
justify-content: space-between;
}

#content {
flex-grow: 2;
}

.blog-post {
background-color: #fff;
padding: 20px;
margin-bottom: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}

.blog-post:hover {
transform: scale(1.03);
}

aside {
width: 250px;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

#search {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
transition: border-color 0.3s ease;
}

#search:focus {
Web Design and Development

Department of CS and SE

border-color: #007bff;
}

button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}

button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>

<header>
<div class="logo"><b><span style="color: #007bff;"><i>Write</i></span>
Wise</b></div>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
<li><a href="logout.php">LogOut</a></li>
</ul>
</nav>
</header>

<main>
<section id="content">
<div class="blog-post">
<h2 ><a href="#">Data Domain System</a></h2>
<p>Date: May 1, 2024</p>
<p>Summary: The article explains how the Domain Name System (DNS)
provides a human-friendly way to identify websites on the Internet. Instead of
Web Design and Development

Department of CS and SE

remembering complex IP addresses, users can type in domain names (e.g.,


“www.wikipedia.org”) to access websites. The article also discusses the anatomy
of domain names, the mapping between domains and IP addresses, and the multi-step
process involved in resolving domain names.</p>
</div>
<div class="blog-post">
<h2><a href="#">Data Structure API'S</a></h2>
<p>Date: December 28, 2018</p>
<p>Summary: This article offers a brief overview of APIs
(Application Programming Interfaces) as they relate to JavaScript data
structures. It discusses how APIs play a role in web development and computer
science.</p>
</div>
<div class="blog-post">
<h2 ><a href="#">Deep Learning</a></h2>
<p>Date: May 18, 2020</p>
<p>Summary: The review article provides a comprehensive overview of
deep learning techniques, taxonomy, applications, and research directions. It
covers topics related to deep learning and its impact across various domains.</p>
</div>
<div class="blog-post">
<h2 ><a href="#">Data Augmentation with_in Context
Learning</a></h2>
<p>Date: June 1, 2022</p>
<p>Summary: This article explores data augmentation techniques in
the context of math word problem solving. It discusses how in-context learning
can enhance data augmentation and evaluates its effectiveness.</p>
</div>
</section>

<aside style="height:50%;">
<input type="text" id="search" placeholder="Search...">
<button id="filterButton">Filter</button>

</aside>

</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Fade in the header section
Web Design and Development

Department of CS and SE

$('header').fadeIn('slow');

// Slide down the main content section


$('#content').slideDown('slow');

// Hover effect on navigation menu items


$('nav a').hover(function() {
$(this).css('color', '#ffd700');
}, function() {
$(this).css('color', '#fff');
});

// Accordion effect on blog post items


$('.blog-post').click(function() {
$(this).find('p').slideToggle('fast');
});

// Slide in the sidebar section


$('#filterButton').click(function() {
$('aside').slideDown('slow');
});

// Fade out the main content section


$('#filterButton').click(function() {
$('#content').fadeOut('slow');
});

// Shake effect on search bar for invalid query


$('#search').on('input', function() {
var query = $(this).val().toLowerCase();
if (query !== 'valid') {
$(this).effect('shake');
}
});

// Bounce effect on submit button


$('button').hover(function() {
$(this).effect('bounce', { times: 3 }, 'slow');
});

// Pulsating effect on search bar


$('#search').hover(function() {
Web Design and Development

Department of CS and SE

$(this).effect('pulsate', { times: 3 }, 'slow');


});

// Zoom effect on blog post items


$('.blog-post').hover(function() {
$(this).toggleClass('zoom-effect');
});
});
</script>

</body>
</html>

OUTPUT:

LOGOUT:

<?php
// Initialize session
session_start();

// Unset all session variables


$_SESSION = array();

// Destroy the session


session_destroy();
Web Design and Development

Department of CS and SE

// Redirect to login page after logout


header("Location: login.php");
exit();
?>
Web Design and Development

Department of CS and SE

3. Add validation to the cookie creation process. Ensure that the cookie value meets certain criteria,
such as being alphanumeric and having a minimum length. Display an error message if the cookie
value is invalid.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Validation</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.error {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h2>Cookie Validation</h2>
<?php
// Check if form is submitted
if (isset($_POST['submit'])) {
$cookie_value = $_POST['cookie_value'];

// Validate the cookie value


if (ctype_alnum($cookie_value) && strlen($cookie_value) >= 6) {
// Set cookie if valid
setcookie('my_cookie', $cookie_value, time() + (86400 * 30), '/');
echo '<p>Cookie set successfully!</p>';
} else {
// Display error message if invalid
echo '<p class="error">Error: Cookie value must be alphanumeric and
at least 6 characters long.</p>';
}
}
?>
Web Design and Development

Department of CS and SE

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">


<label for="cookie_value">Enter Cookie Value:</label>
<input type="text" id="cookie_value" name="cookie_value" required>
<br><br>
<button type="submit" name="submit">Set Cookie</button>
</form>
</body>
</html>

OUTPUT:
Web Design and Development

Department of CS and SE

4. Implement a session timeout mechanism. Set an expiration time for the session and automatically
log out the user when the session expires. Display a countdown timer to notify the user before the
session timeout occurs.
CODE:
<?php
// Set session expiration time to 30 minutes (1800 seconds)
$session_lifetime = 1800; // 30 minutes in seconds

// Start or resume session


session_start();

// Check if session expiration time is reached


if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] >
$session_lifetime)) {
// Session expired, destroy session and logout user
session_unset();
session_destroy();
// Redirect user to logout page or login page
header("Location: logout.php");
exit;
} else {
// Update the last activity time
$_SESSION['last_activity'] = time();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Timeout</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
</style>
<script>
// Countdown timer function
Web Design and Development

Department of CS and SE

function startTimer(duration, display) {


var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;


seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;

if (--timer < 0) {
// Session expired, redirect user to logout page
window.location.href = "logout.php";
}
}, 1000);
}

// Start countdown timer when document is loaded


document.addEventListener("DOMContentLoaded", function () {
var sessionTimeout = <?php echo $session_lifetime; ?>; // Session
timeout in seconds
var display = document.querySelector('#timer');
startTimer(sessionTimeout, display);
});
</script>
</head>
<body>
<h2>Session Timeout</h2>
<p>Your session will expire in: <span id="timer"></span></p>
</body>
</html>

OUTPUT:
Web Design and Development

Department of CS and SE

You might also like