I'm trying to securely keep a user logged in using php but am worried about security.
So I've been going by this question/answer. But There's still a few things I don't quite understand. Please keep in mind I'm not an expert by any means, so please speak as if you were talking to a child.
function onLogin($db, $user) {
$token = GenerateRandomToken($db); // generate a token, should be 128 - 256 bit
storeTokenForUser($db, $user, $token);
$cookie = $user . ':' . $token;
$mac = hash_hmac('sha256', $cookie, 'SECRET_KEY');
$cookie .= ':' . $mac;
setcookie('rememberme', $cookie, time() + (86400 * 7));
}
My question is, how is this secure? I will be storing it in a cookie, which under my knowledge is viewable by users. The "SECRET_KEY" in hash_hmac must have something to do with it but I didn't find much information on how to use it in the manual.
Will the "SECRET_KEY" in hash_hmac be the way that I can secure my cookies? If so, how do I use it? Will it be the same everytime? or should I generate a random ID for it?
Thanks for your time. Greatly appreciated.