PHP Login System with "Remember Me" Functionality [Duplicate]
To enhance the user experience, you can implement a "remember me" feature in your PHP login system, allowing users to stay logged in across multiple sessions.
Secure Cookie Storage
The best practice for storing a persistent cookie is to use a separate table in the database called auth_tokens:
CREATE TABLE `auth_tokens` ( `id` integer(11) not null UNSIGNED AUTO_INCREMENT, `selector` char(12), `token` char(64), `userid` integer(11) not null UNSIGNED, `expires` datetime, PRIMARY KEY (`id`) );
After Login
Upon login, generate unique random values for selector and token:
if ($login->success && $login->rememberMe) { $selector = base64_encode(random_bytes(9)); $authenticator = random_bytes(33); setcookie( 'remember', $selector . ':' . base64_encode($authenticator), time() + 864000, // 10 days '/', 'yourdomain.com', true, // TLS-only true // http-only ); // Insert data into the database $database->exec( "INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)", [ $selector, hash('sha256', $authenticator), $login->userId, date('Y-m-d\TH:i:s', time() + 864000) ] ); }
Re-Authentication
if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) { list($selector, $authenticator) = explode(':', $_COOKIE['remember']); // Retrieve row from the database $row = $database->selectRow( "SELECT * FROM auth_tokens WHERE selector = ?", [ $selector ] ); // Verify hash and set session if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) { $_SESSION['userid'] = $row['userid']; // Regenerate a login token as per previous example } }
Details
The above is the detailed content of How to Implement 'Remember Me' Functionality in a PHP Login System for Enhanced User Experience?. For more information, please follow other related articles on the PHP Chinese website!