Using Real-World Sessions
In a real-world scenario, sessions are often used to manage user authentication, store user-specific data, and maintain a user's state across different pages or requests. Here's an example of using sessions in a simple PHP application for user authentication:
Login Page (login.php
):
<?php
session_start();
// Check if the user is already logged in
if (isset($_SESSION['user_id'])) {
header("Location: dashboard.php");
exit();
}
// Process login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Perform authentication (in a real application, you would validate credentials against a database)
$validUser = ($username === 'demo' && $password === 'password');
if ($validUser) {
// Set user ID in the session
$_SESSION['user_id'] = 123; // Use the actual user ID from your database
header("Location: dashboard.php");
exit();
} else {
$error = "Invalid username or password";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<?php if (isset($error)) { echo "<p>$error</p>"; } ?>
<form method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" name="username" required><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Dashboard Page (dashboard.php
):
<?php
session_start();
// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
// Retrieve user-specific data from a database or other source
$userId = $_SESSION['user_id'];
// Additional logic to fetch user data using $userId
// Display user dashboard
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome to the Dashboard, User <?php echo $userId; ?></h2>
<p>Dashboard content goes here.</p>
<a href="logout.php">Logout</a>
</body>
</html>
Logout Page (logout.php
):
<?php
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect to the login page
header("Location: login.php");
exit();
?>
In this example:
login.php
page handles user authentication and sets the user_id
in the session upon successful login.dashboard.php
page checks if the user is logged in. If not, it redirects them to the login page. Otherwise, it displays the user dashboard.logout.php
page unsets all session variables, destroys the session, and redirects the user to the login page.
This is a simplified example, and in a real-world application, you would likely use a database to store user credentials, implement password hashing, and have more sophisticated authentication logic. Additionally, you might use session variables to store user preferences, access levels, or other user-specific data.
Thank you.