[PHP for Beginners] The Magic of Remembering State! How to Create Login Authentication with Sessions
When Browse websites, "login" functionality is a common feature, right? Once you log in, your "logged-in state" is maintained even when you move to different pages, allowing you to view members-only content. However, web communication (HTTP) is inherently "stateless," meaning each page request is independent and doesn't remember previous states. So, how is the login state maintained?
The secret is a PHP technology called a Session. A session is a mechanism for the server to temporarily remember a "password" for each visitor, signifying "you are logged in." In this article, we'll use this session functionality to explain how to create a simple, password-authenticated "members-only page." By creating just two files, you can experience the core of the login functionality essential for websites. Let's copy, paste, and run the code to feel the magic of remembering state!
To get your PHP running (development environment), if you haven't set up XAMPP yet, please refer to [PHP for Beginners] A Complete Guide to Downloading and Installing XAMPP!. After installation, place your PHP file in the specified folder (like `htdocs`), and you're all set!
1. How Sessions Work: PHP's Memory Trick
A session is a mechanism for temporarily saving information about a user visiting a website on the server side. You can think of it like getting a wristband at the reception of an event. Once you have the wristband (session started), no matter which area (page) of the venue you go to, the staff (server) can recognize you as a legitimate participant (logged-in user).
To handle sessions in PHP, you only need to remember three main commands.
session_start(): This is the starting signal, saying, "I'm going to use a session now!" It must be written at the very beginning of every page that uses sessions.$_SESSION: This is a special array for storing information like login status. You can freely save and check data like so:$_SESSION['key'] = value;.session_destroy(): This completely deletes the session information stored on the server, typically used during logout.
We will build a login system using these three commands.
2. In Practice! Let's Build a Login System
This time, we will create the following two files.
- login.php: A file that displays the login form and performs password authentication.
- member_page.php: A members-only page that only logged-in users can see.
Please save these two files in the same folder.
File 1: login.php (Login Page)
This file contains both the password input form and the logic to check if the submitted password is correct.
<?php
// â‘ Start the session
session_start();
$error_message = '';
// â‘¡ If there is a POST request (form submission)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// â‘¢ Check against the hard-coded password
$correct_password = 'password123'; // In reality, this would be managed in a database
$input_password = $_POST['password'];
if ($input_password === $correct_password) {
// â‘£ If the password matches
$_SESSION['is_logged_in'] = true; // Save login state in the session
header('Location: member_page.php'); // Redirect to the members' page
exit;
} else {
// If the password does not match
$error_message = 'Incorrect password.';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
.login-form { max-width: 300px; margin: 50px auto; padding: 20px; border: 1px solid #ccc; border-radius: 8px; }
input[type="password"] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; }
button { width: 100%; padding: 10px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
.error { color: red; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-form">
<h1>Login</h1>
<?php if ($error_message): ?>
<p class="error"><?php echo $error_message; ?></p>
<?php endif; ?>
<form action="login.php" method="POST">
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
File 2: member_page.php (Members-Only Page)
This page checks for proof of being "logged in" (session information) upon access. If there is no proof, it unceremoniously sends the user back to the login page.
<?php
// â‘ Start the session
session_start();
// â‘¡ Check the login status
// If $_SESSION['is_logged_in'] does not exist or is not true, redirect to the login page
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Members-Only Page</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.content { border: 2px dashed #007bff; padding: 20px; background: #f0f8ff; }
a { color: #d9534f; }
</style>
</head>
<body>
<h1>Welcome, Member!</h1>
<div class="content">
<p>This is special content that only logged-in users can see.</p>
<p>(Members-only information would be displayed here)</p>
</div>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
Now you're all set! Access `login.php` in your browser and try entering "`password123`" as the password. If it's correct, you will be taken to the members' page, and if it's wrong, an error message will be displayed. You can also confirm that if you try to access `member_page.php` directly without logging in, you will be forcibly redirected back to `login.php`.
3. Points to Be Careful About and Applied Examples
This simple mechanism is powerful, but in a real-world application, you need to further enhance security.
Secure Password Storage
In this example, we wrote the password directly in the code as `'password123'` (hard-coding). This is very dangerous. In actual development, passwords must always be processed through **hashing**, which stores them in a form where the original password cannot be figured out, and saved in a database.
PHP provides the `password_hash()` and `password_verify()` functions for this purpose.
<?php
// Hash and save the password (e.g., during user registration)
$hashed_password = password_hash('password123', PASSWORD_DEFAULT);
// Verify if the password entered at login matches the stored hash
if (password_verify('password123', $hashed_password)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
Logout Processing
We've placed a "Logout" link on the members' page. The destination of this link, `logout.php`, needs a process to securely destroy the session.
<?php
session_start();
// Unset all of the session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect to login page after logout
header('Location: login.php');
exit;
?>
By completely destroying the session with `session_destroy()`, the logout is complete.
4. Summary
In this article, we learned how to use PHP's session functionality to make a website "remember" state and build a simple login system. Did you get the hang of the flow: starting a session with `session_start()`, storing information in the `$_SESSION` array, and maintaining that information even when moving between pages?
This session mechanism is a fundamental technology for web applications, applied not only to login authentication but also in various scenarios like multi-page input forms and remembering the contents of a shopping cart. We encourage you to master these basics and take on the challenge of developing more advanced features!