So I store users password in database after hashed by password_hash() (php 5.5+). and then verify user when logging in using password_verify(). but now i want to also store password on users browser with cookies. i hash the same password using password_hash but this time the second part of hash is obviously different. (salt)
because of that, two hashes (the one in database and the one in cookie) are NOT equal. how do i verify them then???
store user credential on cookie is high risk.
If you store hashes password on database so you only need pass username and password then will hashes from other file and match it into your database.
ex. login.php post username and password
usercheck.php md5(password) and check it into database which already hashes password
What you're trying to do is recreate sessions. I'd suggest that you simply use a session.
If you can't for whatever reason, then generate a random string (use a library like random_compat
).
$token = random_bytes(16);
Store the string in the database:
INSERT INTO user_to_token (user_id, token) VALUES (?, ?)
However, store the hash so that if your database leaks, an attacker won't know the original token and hence won't be able to steal the session.
$query->execute([$userId, hash('sha256', $token)]);
Then, set the cookie to the raw value, base64 encoded:
set_cookie("token", base64_encode($token));
Now, to validate, decode and then hash:
$token = hash('sha256', base64_decode($cookie));
Then look up the user id from the DB:
SELECT user_id FROM user_to_token WHERE token = ?
And you're done.