PHP Session Tutorial with Login and Logout Example
This tutorial is designed for beginners to understand PHP sessions and implement a simple login and logout system. It includes step-by-step explanations and complete code examples.
What is a PHP Session?
A PHP session is a way to store information (in variables) to be used across multiple pages. Unlike cookies, session data is stored on the server, and a unique session ID is sent to the client’s browser to maintain the session. Sessions are commonly used for user authentication, such as keeping a user logged in while navigating a website.
Key Points:
- Sessions are started using
session_start(). - Session data is stored in the
$_SESSIONsuperglobal array. - Sessions can be destroyed (e.g., on logout) using
session_destroy().
Step-by-Step Tutorial
Step 1: Understanding session_start()
Every PHP script that uses sessions must call session_start() at the beginning of the file (before any output is sent to the browser). This function initializes the session or resumes an existing one.
Step 2: Storing Data in a Session
You can store data in the $_SESSION array. For example, after a user logs in, you might store their username or user ID in the session.
Step 3: Checking Session Data
You can check if a session variable exists to verify if a user is logged in. For example, isset($_SESSION['username']) checks if the user is authenticated.
Step 4: Destroying a Session
When a user logs out, you can destroy the session using session_destroy() and unset session variables with session_unset() or by unsetting specific variables.
Example: Login and Logout System Using PHP Sessions
Below is a complete example of a login and logout system using PHP sessions. This example includes:
- A login page (
login.php) to authenticate users. - A dashboard page (
dashboard.php) accessible only to logged-in users. - A logout script (
logout.php) to end the session. - A simple database simulation (using an array) for user credentials.
Prerequisites
- A web server with PHP installed (e.g., XAMPP, WAMP, or a hosting provider).
- Basic knowledge of HTML and PHP.
Project Structure
Create the following files in your web server’s root directory (e.g., htdocs in XAMPP):
- login.php
- dashboard.php
- logout.php
Step 1: Create the Login Page (login.php)
This page contains a form for users to enter their username and password. It checks the credentials and starts a session if the login is successful.
<?php
// Start the session
session_start();
// Check if the user is already logged in, redirect to dashboard
if (isset($_SESSION['username'])) {
header("Location: dashboard.php");
exit();
}
// Simulated database (replace with actual database in production)
$users = [
'admin' => 'password123',
'user1' => 'pass456'
];
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Check if username exists and password matches
if (isset($users[$username]) && $password === $users[$username]) {
// Store username in session
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
$error = "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; }
.error { color: red; }
input { width: 100%; padding: 8px; margin: 10px 0; }
button { padding: 10px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
button:hover { background-color: #45a049; }
</style>
</head>
<body>
<h2>Login</h2>
<?php if (isset($error)) { echo "<p class='error'>$error</p>"; } ?>
<form method="post" action="">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Explanation:
session_start()initializes the session.- If the user is already logged in (
$_SESSION['username']exists), they are redirected todashboard.php. - A simulated user database (array) stores usernames and passwords. In a real application, use a database (e.g., MySQL) with proper password hashing.
- The form submits to itself (
action=""). If the credentials are valid, the username is stored in$_SESSION, and the user is redirected to the dashboard.
Step 2: Create the Dashboard Page (dashboard.php)
This page is only accessible to logged-in users. It displays a welcome message and a logout link.
<?php
// Start the session
session_start();
// Check if the user is logged in, if not redirect to login page
if (!isset($_SESSION['username'])) {
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>Dashboard</title>
<style>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; }
a { color: #4CAF50; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h2>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h2>
<p>This is your dashboard.</p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
Explanation:
session_start()resumes the session.- If
$_SESSION['username']is not set, the user is redirected tologin.php. - The username is displayed using
htmlspecialchars()to prevent XSS attacks. - A logout link directs the user to
logout.php.
Step 3: Create the Logout Script (logout.php)
This script destroys the session and redirects the user to the login page.
<?php
// Start the session
session_start();
// Unset all session variables
$_SESSION = [];
// Destroy the session
session_destroy();
// Redirect to login page
header("Location: login.php");
exit();
?>
Explanation:
session_start()resumes the session.$_SESSION = []clears all session variables.session_destroy()destroys the session.- The user is redirected to
login.php.
Step 4: Testing the Application
- Place the three files (
login.php,dashboard.php,logout.php) in your web server’s root directory. - Access
http://localhost/login.phpin your browser. - Try logging in with:
- Username:
admin, Password:password123 - Username:
user1, Password:pass456
- Username:
- Upon successful login, you’ll be redirected to the dashboard.
- Click the “Logout” link to end the session and return to the login page.
- Try accessing
dashboard.phpdirectly without logging in; you should be redirected tologin.php.
Important Notes
- Security: This is a basic example. In a production environment:
- Use a real database (e.g., MySQL) and hash passwords with
password_hash()andpassword_verify(). - Implement CSRF protection for forms.
- Use HTTPS to secure session data.
- Validate and sanitize all user inputs.
- Use a real database (e.g., MySQL) and hash passwords with
- Session Timeout: You can set a session timeout by checking the last activity time in
$_SESSIONor usingsession.gc_maxlifetimein PHP configuration. - Error Handling: Add more robust error handling for production use.
Conclusion
This tutorial covered the basics of PHP sessions and demonstrated a practical login and logout system. You learned how to:
- Start and manage sessions with
session_start()and$_SESSION. - Store and retrieve session data.
- Secure pages by checking session variables.
- Destroy sessions on logout.
You can extend this example by adding a database, user registration, or additional features like session timeouts.