Home >Backend Development >PHP Tutorial >How can I implement a secure 'Remember Me' feature using PHP and cookies?
Introduction
Implementing a "remember me" feature allows users to stay logged in even after closing their browsers. This feature enhances user convenience and improves the overall user experience. In this article, we'll delve into a secure way to store and verify cookies in a user's browser for a persistent login mechanism.
Storing Cookie Securely
To securely store a cookie, we utilize a separate table in the database:
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`) );
Process After Logging In
Upon successful login with the "remember me" option enabled:
Set a cookie with the following values:
'remember': $selector.':'.base64_encode($authenticator)
Re-Authenticating on Page Load
To re-authenticate the user:
if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) { list($selector, $authenticator) = explode(':', $_COOKIE['remember']); $row = $database->selectRow( "SELECT * FROM auth_tokens WHERE selector = ?", [ $selector ] ); if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) { $_SESSION['userid'] = $row['userid']; // Regenerate login token and update database } }
Details of the Approach
The above is the detailed content of How can I implement a secure 'Remember Me' feature using PHP and cookies?. For more information, please follow other related articles on the PHP Chinese website!