Mini Login System: Session-Based Authentication
A session-based authentication system in PHP allows you to securely track whether a user is logged in as they navigate between pages. When a user submits their credentials, PHP creates a session that stores their authentication status on the server. This session is referenced on each page load using a unique session ID, typically stored in a session cookie. The workflow involves displaying a login form, validating credentials, creating a session upon successful login, checking session data to protect private pages, and providing a logout mechanism that destroys the session. This approach keeps sensitive data on the server and only exposes a session identifier to the client, reducing the risk of credential leakage.
login.php
dashboard.php
logout.php
1234567891011121314151617181920212223242526272829303132<?php session_start(); $error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; // In real applications, verify against a database and use password_hash if ($username === 'admin' && $password === 'password123') { $_SESSION['loggedin'] = true; $_SESSION['username'] = $username; 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 ($error): ?><p style="color:red;\"><?php echo htmlspecialchars($error); ?></p><?php endif; ?> <form method="post" action="login.php"> <label>Username: <input type="text" name="username"></label><br> <label>Password: <input type="password" name="password"></label><br> <button type="submit">Login</button> </form> </body> </html>
This simple login system demonstrates the typical flow of session-based authentication in PHP. When a user visits login.php, they are presented with a form. Upon submitting valid credentials, the script sets session variables such as loggedin and username. The dashboard.php page checks whether the loggedin session variable is set and true; if not, it redirects the user back to the login page. If the session is valid, it greets the user and displays protected content. The logout.php script clears all session data and destroys the session, logging the user out and redirecting them to the login page. This process ensures that authentication state is managed on the server and only users with a valid session can access protected pages.
login.php
12345678910111213141516171819202122232425262728293031323334353637<?php session_start(); $error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; $remember = isset($_POST['remember']); if ($username === 'admin' && $password === 'password123') { $_SESSION['loggedin'] = true; $_SESSION['username'] = $username; if ($remember) { // Set a cookie for 7 days setcookie('rememberme', $username, time() + (7 * 24 * 60 * 60), "/", "", false, true); } 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 ($error): ?><p style="color:red;"><?php echo htmlspecialchars($error); ?></p><?php endif; ?> <form method="post" action="login.php"> <label>Username: <input type="text" name="username"></label><br> <label>Password: <input type="password" name="password"></label><br> <label><input type="checkbox" name="remember"> Remember me</label><br> <button type="submit">Login</button> </form> </body> </html>
To extend the basic session-based login system, you can add features like a "remember me" option using cookies. The updated login.php script above shows how to set a rememberme cookie if the user selects the checkbox. This cookie can be checked on subsequent visits to offer persistent login, even after the session expires or the browser is closed. By combining sessions for immediate authentication and cookies for long-term persistence, you can balance security and convenience. Always ensure that sensitive information is not stored directly in cookies and that cookies are configured with appropriate flags, as covered in previous chapters. These techniques allow you to build more robust authentication systems by leveraging both PHP sessions and cookies.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you explain how the "remember me" feature works in more detail?
What are the security best practices for using sessions and cookies in PHP authentication?
How can I implement user roles or permissions in this session-based system?
Incrível!
Completion taxa melhorada para 8.33
Mini Login System: Session-Based Authentication
Deslize para mostrar o menu
A session-based authentication system in PHP allows you to securely track whether a user is logged in as they navigate between pages. When a user submits their credentials, PHP creates a session that stores their authentication status on the server. This session is referenced on each page load using a unique session ID, typically stored in a session cookie. The workflow involves displaying a login form, validating credentials, creating a session upon successful login, checking session data to protect private pages, and providing a logout mechanism that destroys the session. This approach keeps sensitive data on the server and only exposes a session identifier to the client, reducing the risk of credential leakage.
login.php
dashboard.php
logout.php
1234567891011121314151617181920212223242526272829303132<?php session_start(); $error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; // In real applications, verify against a database and use password_hash if ($username === 'admin' && $password === 'password123') { $_SESSION['loggedin'] = true; $_SESSION['username'] = $username; 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 ($error): ?><p style="color:red;\"><?php echo htmlspecialchars($error); ?></p><?php endif; ?> <form method="post" action="login.php"> <label>Username: <input type="text" name="username"></label><br> <label>Password: <input type="password" name="password"></label><br> <button type="submit">Login</button> </form> </body> </html>
This simple login system demonstrates the typical flow of session-based authentication in PHP. When a user visits login.php, they are presented with a form. Upon submitting valid credentials, the script sets session variables such as loggedin and username. The dashboard.php page checks whether the loggedin session variable is set and true; if not, it redirects the user back to the login page. If the session is valid, it greets the user and displays protected content. The logout.php script clears all session data and destroys the session, logging the user out and redirecting them to the login page. This process ensures that authentication state is managed on the server and only users with a valid session can access protected pages.
login.php
12345678910111213141516171819202122232425262728293031323334353637<?php session_start(); $error = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; $remember = isset($_POST['remember']); if ($username === 'admin' && $password === 'password123') { $_SESSION['loggedin'] = true; $_SESSION['username'] = $username; if ($remember) { // Set a cookie for 7 days setcookie('rememberme', $username, time() + (7 * 24 * 60 * 60), "/", "", false, true); } 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 ($error): ?><p style="color:red;"><?php echo htmlspecialchars($error); ?></p><?php endif; ?> <form method="post" action="login.php"> <label>Username: <input type="text" name="username"></label><br> <label>Password: <input type="password" name="password"></label><br> <label><input type="checkbox" name="remember"> Remember me</label><br> <button type="submit">Login</button> </form> </body> </html>
To extend the basic session-based login system, you can add features like a "remember me" option using cookies. The updated login.php script above shows how to set a rememberme cookie if the user selects the checkbox. This cookie can be checked on subsequent visits to offer persistent login, even after the session expires or the browser is closed. By combining sessions for immediate authentication and cookies for long-term persistence, you can balance security and convenience. Always ensure that sensitive information is not stored directly in cookies and that cookies are configured with appropriate flags, as covered in previous chapters. These techniques allow you to build more robust authentication systems by leveraging both PHP sessions and cookies.
Obrigado pelo seu feedback!