Persistent Cookies for Secure "Remember Me" Functionality in PHP Login Systems
Introduction
Implementing a "remember me" feature in a PHP login system requires storing a secure cookie in the user's browser. This cookie allows users to remain logged in even after closing their browser or restarting their device.
Database Structure
To store remember me information securely, create a separate table in your 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`) );
The selector and token fields will be used to store the remember me information.
After Logging In
When a user logs in and selects the "remember me" option, generate a random selector (12 characters) and an authenticator (33 bytes) using the random_bytes() function or a similar method to ensure randomness.
Set the remember me cookie using the following code:
setcookie( 'remember', $selector . ':' . base64_encode($authenticator), time() + 864000, // expires in 10 days '/', 'yourdomain.com', true, // TLS-only true // http-only );
Insert the selector, hashed authenticator, user ID, and expiration time into the auth_tokens table.
Re-Authenticating on Page Load
On subsequent page loads, if the user is not already logged in and the remember me cookie is set:
Details
The above is the detailed content of How to Securely Implement 'Remember Me' Functionality in PHP Login Systems Using Persistent Cookies?. For more information, please follow other related articles on the PHP Chinese website!