I followed this answer for php login system (Remember me) PHP login system: Remember Me (persistent cookie)
I was able to set the cookie successfully using
$selector = base64_encode(random_bytes(9));
$authenticator = random_bytes(33);
$token = hash('sha256', $authenticator);
$expires = date('Y-m-d\TH:i:s', time() + 864000);
$stmt2 = $pdo->prepare("INSERT INTO auth_tokens (selector,token,userid,expires) VALUES (:selector, :token, :userid, :expires)");
$stmt2->bindParam(':selector', $selector);
$stmt2->bindParam(':token', $token);
$stmt2->bindParam(':userid', $userid);
$stmt2->bindParam(':expires', $expires);
$stmt2->execute();
setcookie(
'remember',
$selector.':'.base64_encode($authenticator),
time()+86400,
'/',
false
);
I dont seem to understand this part. Re-Authenticating On Page Load
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'];
// Then regenerate login token as above
}
}
1. What should be in $selector and $authenticator variables
because from the code, there is a query which says SELECT from auth_tokens where selector = $selector
2. The selector changes everytime on page reload cause its random. So if the $selector = base64_encode(random_bytes(9)); It doesn't match with anything in the selector column when I run this query *"SELECT * FROM auth_tokens WHERE selector = $selector"*
Someone explain the Re-Authenticating On Page Load and some example code.