How can a "Remember Me" feature be implemented securely in a PHP login system?

To implement a "Remember Me" feature securely in a PHP login system, you can generate a unique token for each user when they select the "Remember Me" option. This token should be stored in both the user's browser cookies and the database. When the user returns to the site, you can check the token in the cookie against the database to automatically log them in.

// Generate a unique token for the user
$token = bin2hex(random_bytes(16));

// Store the token in the user's browser cookies
setcookie('remember_token', $token, time() + 3600 * 24 * 30, '/');

// Store the token in the database
$query = "UPDATE users SET remember_token = '$token' WHERE id = '$user_id'";
// Execute the query

// When the user returns to the site, check the token in the cookie against the database
if(isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];
    $query = "SELECT * FROM users WHERE remember_token = '$token'";
    // Execute the query and log the user in if a match is found
}