Assignments On Class 14
Sessions and Cookies
Here are some assignments related to sessions and cookies in PHP, along with their solutions and explanations.
Assignment 1: User Login Tracking with Sessions
Objective: Create a simple PHP application that allows users to log in, and tracks their login status using sessions.
Task:
- Create an HTML form to collect username and password.
- Upon submission, store the username in a session variable.
- Display a welcome message with the username on a new page.
Solution:
login.php (Login Form)
php
Copy code
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="welcome.php">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
welcome.php (Processing and Displaying Session)
php
Copy code
<?php
session_start();
// Simulate password checking (in real applications, use hashed passwords)
if ($_POST['password'] === 'password123') {
$_SESSION['username'] = $_POST['username']; // Store username in session
echo 'Welcome, ' . $_SESSION['username'] . '!';
echo '<br><a href="logout.php">Logout</a>'; // Link to logout
} else {
echo 'Invalid password. Please try again.';
}
?>
logout.php (Logout)
php
Copy code
<?php
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
header('Location: login.php'); // Redirect to login page
?>
Explanation:
- The login.php file contains a simple HTML form where users can input their username and password.
- When the form is submitted, it sends data to welcome.php.
- In welcome.php, if the password is correct, the username is stored in a session variable, and a welcome message is displayed.
- The user can log out by clicking on the "Logout" link, which directs them to logout.php, clearing the session data.
Assignment 2: Remember User Preferences with Cookies
Objective: Create a PHP application that remembers user preferences (like theme selection) using cookies.
Task:
- Create an HTML form to allow users to select a theme (light/dark).
- Store the selected theme in a cookie.
- On page reload, apply the selected theme and display a message showing the user's choice.
Solution:
index.php (Theme Selection Form)
php
Copy code
<?php
if (isset($_COOKIE['theme'])) {
$theme = $_COOKIE['theme']; // Retrieve theme from cookie
} else {
$theme = 'light'; // Default theme
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Theme Selector</title>
<style>
body {
background-color: <?= ($theme == 'dark') ? '#333' : '#fff' ?>;
color: <?= ($theme == 'dark') ? '#fff' : '#000' ?>;
}
</style>
</head>
<body>
<h2>Select Your Theme</h2>
<form method="post" action="set_theme.php">
<select name="theme">
<option value="light" <?= ($theme == 'light') ? 'selected' : '' ?>>Light</option>
<option value="dark" <?= ($theme == 'dark') ? 'selected' : '' ?>>Dark</option>
</select>
<input type="submit" value="Set Theme">
</form>
<p>Your current theme is: <strong><?= $theme ?></strong></p>
</body>
</html>
set_theme.php (Set Cookie)
php
Copy code
<?php
if (isset($_POST['theme'])) {
$theme = $_POST['theme'];
setcookie('theme', $theme, time() + (86400 * 30), "/"); // Cookie expires in 30 days
header('Location: index.php'); // Redirect to index page
}
?>
Explanation:
- index.php displays a form with a dropdown for theme selection.
- If a theme cookie exists, it retrieves the theme value and applies it to the page. The selected theme is used to style the page dynamically.
- set_theme.php sets the selected theme in a cookie that expires in 30 days. After setting the cookie, it redirects back to index.php to display the selected theme.
Assignment 3: Display User Information with Sessions
Objective: Create a PHP application that allows users to enter their name and email, storing this information in a session.
Task:
- Create an HTML form to collect the user's name and email.
- Store the data in session variables.
- Display the user's name and email on a new page.
Solution:
user_info.php (User Info Form)
php
Copy code
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>User Information</title>
</head>
<body>
<h2>User Information Form</h2>
<form method="post" action="display_info.php">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
display_info.php (Display Session Data)
php
Copy code
<?php
session_start();
$_SESSION['name'] = $_POST['name']; // Store name in session
$_SESSION['email'] = $_POST['email']; // Store email in session
echo 'Name: ' . $_SESSION['name'] . '<br>';
echo 'Email: ' . $_SESSION['email'] . '<br>';
echo '<a href="logout.php">Logout</a>'; // Link to logout
?>
Explanation:
- user_info.php allows users to enter their name and email.
- When the form is submitted, display_info.php stores the entered data in session variables and displays the information. A logout link is provided to end the session.
These assignments will help students practice managing sessions and cookies in PHP effectively while enhancing their understanding of user tracking and preferences.
4o mini
You said:
give more
ChatGPT said:
ChatGPT
Here are additional assignments with solutions and explanations focused on sessions and cookies in PHP.
Assignment 4: Session-Based Shopping Cart
Objective: Create a simple shopping cart using sessions to track selected products.
Task:
- Create an HTML page with a list of products (e.g., Product Name and Price).
- Allow users to add products to the cart (stored in session).
- Display the cart contents on a separate page.
Solution:
products.php (Product List)
php
Copy code
<?php
session_start();
$products = [
['id' => 1, 'name' => 'Product 1', 'price' => 10],
['id' => 2, 'name' => 'Product 2', 'price' => 20],
['id' => 3, 'name' => 'Product 3', 'price' => 30],
];
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Add product to cart
if (isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$_SESSION['cart'][] = $products[$product_id - 1]; // Add product to session cart
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h2>Available Products</h2>
<ul>
<?php foreach ($products as $product): ?>
<li>
<?= $product['name'] ?> - $<?= $product['price'] ?>
<form method="post" style="display:inline;">
<input type="hidden" name="product_id" value="<?= $product['id'] ?>">
<input type="submit" name="add_to_cart" value="Add to Cart">
</form>
</li>
<?php endforeach; ?>
</ul>
<a href="cart.php">View Cart</a>
</body>
</html>
cart.php (View Cart)
php
Copy code
<?php
session_start();
if (empty($_SESSION['cart'])) {
echo 'Your cart is empty.';
} else {
echo '<h2>Your Cart</h2>';
foreach ($_SESSION['cart'] as $item) {
echo $item['name'] . ' - $' . $item['price'] . '<br>';
}
echo '<a href="products.php">Continue Shopping</a>';
}
?>
Explanation:
- products.php lists available products with an "Add to Cart" button.
- When a product is added, its details are stored in the session cart.
- cart.php displays the contents of the cart by iterating through the session variable. If the cart is empty, it shows a relevant message.
Assignment 5: Remember Me Functionality with Cookies
Objective: Implement a "Remember Me" functionality for user login using cookies.
Task:
- Create a login form that allows users to check a "Remember Me" option.
- If checked, store the username in a cookie for 30 days.
- On returning to the page, automatically fill in the username if the cookie exists.
Solution:
login.php (Login Form with Remember Me)
php
Copy code
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="process_login.php">
Username: <input type="text" name="username" value="<?php echo isset($_COOKIE['username']) ? $_COOKIE['username'] : ''; ?>" required><br>
Password: <input type="password" name="password" required><br>
<input type="checkbox" name="remember_me" /> Remember Me<br>
<input type="submit" value="Login">
</form>
</body>
</html>
process_login.php (Login Processing)
php
Copy code
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password']; // Simulated password check
if ($password === 'password123') {
$_SESSION['username'] = $username; // Store in session
// Set cookie if "Remember Me" is checked
if (isset($_POST['remember_me'])) {
setcookie('username', $username, time() + (86400 * 30), "/"); // 30 days
} else {
setcookie('username', '', time() - 3600, "/"); // Delete cookie
}
echo 'Welcome, ' . $_SESSION['username'] . '!';
} else {
echo 'Invalid username or password.';
}
?>
Explanation:
- login.php retrieves the username from the cookie (if it exists) and pre-fills the input field.
- process_login.php checks the password and, if valid, stores the username in the session. If "Remember Me" is checked, it also sets a cookie for the username.
Assignment 6: Cookie-Based Language Preference
Objective: Allow users to select their language preference, storing the choice in a cookie.
Task:
- Create a form to select a language (e.g., English, Spanish).
- Store the selected language in a cookie.
- Display a welcome message in the selected language.
Solution:
language.php (Language Selection)
php
Copy code
<?php
if (isset($_COOKIE['language'])) {
$language = $_COOKIE['language']; // Retrieve language from cookie
} else {
$language = 'English'; // Default language
}
// Messages
$messages = [
'English' => 'Welcome!',
'Spanish' => '¡Bienvenido!'
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Select Language</title>
</head>
<body>
<h2>Select Your Language</h2>
<form method="post" action="set_language.php">
<select name="language">
<option value="English" <?= ($language == 'English') ? 'selected' : '' ?>>English</option>
<option value="Spanish" <?= ($language == 'Spanish') ? 'selected' : '' ?>>Spanish</option>
</select>
<input type="submit" value="Set Language">
</form>
<p><?= $messages[$language] ?></p> <!-- Display welcome message -->
</body>
</html>
set_language.php (Set Language Cookie)
php
Copy code
<?php
if (isset($_POST['language'])) {
$language = $_POST['language'];
setcookie('language', $language, time() + (86400 * 30), "/"); // Cookie expires in 30 days
header('Location: language.php'); // Redirect to language page
}
?>
Explanation:
- language.php displays a dropdown to select a language, defaulting to English if no cookie exists.
- When a language is selected, set_language.php stores the choice in a cookie, which is then used to display a welcome message in the chosen language.
Assignment 7: Session Timeout Management
Objective: Implement a session timeout feature to enhance security.
Task:
- Create a PHP script that tracks user activity.
- End the session if there’s no activity for a specified duration (e.g., 5 minutes).
Solution:
session_timeout.php (Main Page)
php
Copy code
<?php
session_start();
// Set session timeout duration (5 minutes)
$timeout_duration = 300; // 5 minutes
// Check if the user is already logged in and if session has expired
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset(); // Unset session variables
session_destroy(); // Destroy session
echo "Session timed out. Please <a href='login.php'>log in again</a>.";
exit;
}
// Update last activity time
$_SESSION['LAST_ACTIVITY'] = time();
// Simulated login check
if (!isset($_SESSION['username'])) {
echo "You are not logged in. Please <a href='login.php'>log in</a>.";
exit;
}
echo "Welcome, " . $_SESSION['username'] . ". You are active!";
?>
Explanation:
- In session_timeout.php, the script checks the last activity time stored in the session.
- If the difference between the current time and the last activity exceeds the specified timeout duration (5 minutes), the session is destroyed.
- If the session is still active, it updates the last activity time and displays a welcome message.
Assignment 8: Storing Shopping Cart in Cookies
Objective: Store the shopping cart in cookies instead of sessions.
Task:
- Allow users to add items to a cart.
- Store the cart items in a cookie.
- Display the cart contents from the cookie.
Solution:
products_cookie.php (Product List with Cookie Cart)
php
Copy code
<?php
if (isset($_COOKIE['cart'])) {
$cart = json_decode($_COOKIE['cart'], true); // Decode cart cookie
} else {
$cart = []; // Initialize empty cart
}
$products = [
['id' => 1, 'name' => 'Product 1', 'price' => 10],
['id' => 2, 'name' => 'Product 2', 'price' => 20],
['id' => 3, 'name' => 'Product 3', 'price' => 30],
];
// Add product to cookie cart
if (isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$cart[] = $products[$product_id - 1]; // Add product to cart
setcookie('cart', json_encode($cart), time() + (86400 * 30), "/"); // Store cart in cookie
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h2>Available Products</h2>
<ul>
<?php foreach ($products as $product): ?>
<li>
<?= $product['name'] ?> - $<?= $product['price'] ?>
<form method="post" style="display:inline;">
<input type="hidden" name="product_id" value="<?= $product['id'] ?>">
<input type="submit" name="add_to_cart" value="Add to Cart">
</form>
</li>
<?php endforeach; ?>
</ul>
<h3>Your Cart</h3>
<ul>
<?php foreach ($cart as $item): ?>
<li><?= $item['name'] ?> - $<?= $item['price'] ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
Explanation:
- products_cookie.php allows users to add products to a shopping cart that is stored in a cookie.
- The cart is encoded in JSON format to handle multiple items and stored in the cookie.
- Each time a product is added, the cookie is updated, and the current cart contents are displayed.