Why is it recommended to use a token instead of a password for auto-login mechanisms in PHP?

Using a token instead of a password for auto-login mechanisms in PHP is recommended for security reasons. Tokens are randomly generated strings that are harder to guess than passwords, reducing the risk of unauthorized access. Additionally, tokens can be easily invalidated and regenerated, providing an extra layer of security.

<?php
// Generate a random token
$token = bin2hex(random_bytes(16));

// Store the token in the database for the user
// For example, assuming $userId is the user's ID
$pdo->prepare("UPDATE users SET token = :token WHERE id = :userId")->execute(['token' => $token, 'userId' => $userId]);

// Set the token in a cookie for auto-login
setcookie('token', $token, time() + 3600, '/');

// Verify the token during auto-login
if(isset($_COOKIE['token'])) {
    $token = $_COOKIE['token'];
    $user = $pdo->query("SELECT * FROM users WHERE token = '$token'")->fetch();
    
    if($user) {
        // User is authenticated, proceed with auto-login
    } else {
        // Invalid token, redirect to login page
        header('Location: login.php');
        exit();
    }
}
?>