What are the recommended methods for implementing a "remember me" feature in a PHP login form?
To implement a "remember me" feature in a PHP login form, you can use cookies to store a user's login credentials securely. When a user logs in with the "remember me" option checked, you can set a cookie with a unique token that identifies the user. Upon subsequent visits, you can check for this cookie and automatically log in the user if it is present.
// Check if the "remember me" checkbox is checked
if(isset($_POST['remember_me'])){
// Generate a unique token
$token = bin2hex(random_bytes(16));
// Set a cookie with the token that expires in 30 days
setcookie('remember_token', $token, time() + (30 * 24 * 60 * 60), '/');
// Store the token in the database for future reference
// This is just an example, you should adapt this to your database structure
$user->updateRememberToken($token);
}
// When a user visits the site, check for the remember me cookie
if(isset($_COOKIE['remember_token'])){
// Retrieve the user based on the token
$user = $user->getUserByRememberToken($_COOKIE['remember_token']);
// Log in the user if the token is valid
if($user){
$_SESSION['user_id'] = $user->id;
}
}