Login Persistence and Remember-Me Cookies
When you want users to stay logged in between visits, you implement login persistence. This means that when a user checks a "remember me" option during login, they do not need to enter their credentials again for a set period. Cookies play a key role in this feature: a unique value identifying the user is stored in their browser as a cookie. When the user returns, your PHP application checks for this cookie and, if valid, automatically logs the user in, creating a seamless experience.
remember_me.php
12345678910111213141516171819202122232425262728293031323334353637383940<?php // Simulated user login $username = 'johndoe'; $password = 'secret'; // Check if form submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_POST['username'] === $username && $_POST['password'] === $password) { // User authenticated if (isset($_POST['remember_me'])) { // Generate a random token $token = bin2hex(random_bytes(16)); // Store token in a simulated user database (here, just a file for demo) file_put_contents('user_token.txt', $token); // Set cookie for 30 days setcookie('rememberme', $token, time() + (86400 * 30), "/"); } echo "Logged in as $username"; } else { echo "Invalid credentials."; } } elseif (isset($_COOKIE['rememberme'])) { // Check token from cookie $savedToken = @file_get_contents('user_token.txt'); if ($savedToken && hash_equals($savedToken, $_COOKIE['rememberme'])) { echo "Welcome back, $username (auto-login with remember me)"; } else { echo "Invalid or expired remember me token."; } } else { ?> <form method="post"> Username: <input name="username"><br> Password: <input name="password" type="password"><br> <label><input type="checkbox" name="remember_me"> Remember me</label><br> <button type="submit">Login</button> </form> <?php } ?>
While the example above demonstrates the basic mechanics of a remember-me cookie, it highlights several important security considerations. Storing a simple token in a cookie and matching it to a value on the server can work, but if an attacker gains access to the token (for example, through XSS or theft of the user's device), they could impersonate the user. Tokens should be random, unique, and securely stored on the server, and cookies should be set with the HttpOnly, Secure, and SameSite flags to reduce risk. Additionally, tokens should be invalidated when the user logs out or changes their password, and you should avoid storing sensitive information directly in cookies.
logout.php
123456789101112<?php // Invalidate the remember-me cookie and token if (isset($_COOKIE['rememberme'])) { // Remove token from simulated database (here, delete the file) if (file_exists('user_token.txt')) { unlink('user_token.txt'); } // Expire the cookie setcookie('rememberme', '', time() - 3600, "/"); } echo "You have been logged out."; ?>
To securely implement remember-me cookies, always generate unpredictable tokens and store them securely on the server, never directly in the cookie. Use the Secure, HttpOnly, and SameSite=Strict or Lax cookie flags wherever possible. Invalidate tokens immediately on logout, as shown in the logout script, and consider expiring old tokens automatically. Never store passwords or sensitive user data in cookies. Regularly review your implementation for vulnerabilities, and always treat persistent authentication as a potential security risk that requires careful handling, as demonstrated in both code examples above.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Чудово!
Completion показник покращився до 8.33
Login Persistence and Remember-Me Cookies
Свайпніть щоб показати меню
When you want users to stay logged in between visits, you implement login persistence. This means that when a user checks a "remember me" option during login, they do not need to enter their credentials again for a set period. Cookies play a key role in this feature: a unique value identifying the user is stored in their browser as a cookie. When the user returns, your PHP application checks for this cookie and, if valid, automatically logs the user in, creating a seamless experience.
remember_me.php
12345678910111213141516171819202122232425262728293031323334353637383940<?php // Simulated user login $username = 'johndoe'; $password = 'secret'; // Check if form submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_POST['username'] === $username && $_POST['password'] === $password) { // User authenticated if (isset($_POST['remember_me'])) { // Generate a random token $token = bin2hex(random_bytes(16)); // Store token in a simulated user database (here, just a file for demo) file_put_contents('user_token.txt', $token); // Set cookie for 30 days setcookie('rememberme', $token, time() + (86400 * 30), "/"); } echo "Logged in as $username"; } else { echo "Invalid credentials."; } } elseif (isset($_COOKIE['rememberme'])) { // Check token from cookie $savedToken = @file_get_contents('user_token.txt'); if ($savedToken && hash_equals($savedToken, $_COOKIE['rememberme'])) { echo "Welcome back, $username (auto-login with remember me)"; } else { echo "Invalid or expired remember me token."; } } else { ?> <form method="post"> Username: <input name="username"><br> Password: <input name="password" type="password"><br> <label><input type="checkbox" name="remember_me"> Remember me</label><br> <button type="submit">Login</button> </form> <?php } ?>
While the example above demonstrates the basic mechanics of a remember-me cookie, it highlights several important security considerations. Storing a simple token in a cookie and matching it to a value on the server can work, but if an attacker gains access to the token (for example, through XSS or theft of the user's device), they could impersonate the user. Tokens should be random, unique, and securely stored on the server, and cookies should be set with the HttpOnly, Secure, and SameSite flags to reduce risk. Additionally, tokens should be invalidated when the user logs out or changes their password, and you should avoid storing sensitive information directly in cookies.
logout.php
123456789101112<?php // Invalidate the remember-me cookie and token if (isset($_COOKIE['rememberme'])) { // Remove token from simulated database (here, delete the file) if (file_exists('user_token.txt')) { unlink('user_token.txt'); } // Expire the cookie setcookie('rememberme', '', time() - 3600, "/"); } echo "You have been logged out."; ?>
To securely implement remember-me cookies, always generate unpredictable tokens and store them securely on the server, never directly in the cookie. Use the Secure, HttpOnly, and SameSite=Strict or Lax cookie flags wherever possible. Invalidate tokens immediately on logout, as shown in the logout script, and consider expiring old tokens automatically. Never store passwords or sensitive user data in cookies. Regularly review your implementation for vulnerabilities, and always treat persistent authentication as a potential security risk that requires careful handling, as demonstrated in both code examples above.
Дякуємо за ваш відгук!