Hey all 🙂 I'm learning PHP with a tiny members page (no framework, just to understand how it works). Tutorials online are all over the place: some use md5, some sha1, some password_hash. What's the current right way to store passwords? And what should I know about sessions so logout actually logs out?
QuestionSimple login in plain PHP: password_hash and sessions, am I on the right track?
password_hash, nothing else. md5 and sha1 are fast hashes, which is exactly what you do not want for passwords.
<?php
// sign-up
$hash = password_hash($password, PASSWORD_DEFAULT);
// store $hash (VARCHAR(255)), never the password itself
// sign-in
if (!password_verify($password, $row['password_hash'])) {
http_response_code(401);
exit('Wrong login or password');
}
if (password_needs_rehash($row['password_hash'], PASSWORD_DEFAULT)) {
// PHP changed the default algorithm or cost: store a fresh hash
$newHash = password_hash($password, PASSWORD_DEFAULT);
}
PASSWORD_DEFAULT can change between PHP versions, that is why the column should be wide and why the rehash check exists. Same error text for "no such user" and "wrong password", so the form does not tell which logins exist.
Thanks! That part makes sense now. Sessions are where I'm lost: after "logout" the cookie is still there in the browser. Is that a problem?
Also a question from me: is a "remember me" checkbox safe to do with a long session cookie, or is it different?
>>3 The cookie itself is not the problem, the session data on the server is. Logout should destroy it:
<?php
// before session_start(), e.g. in a bootstrap file
ini_set('session.use_strict_mode', '1');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true, // https only
'httponly' => true, // not readable from JavaScript
'samesite' => 'Lax',
]);
session_start();
// after a successful password_verify()
session_regenerate_id(true); // new id, protects against session fixation
$_SESSION['user_id'] = $row['id'];
// logout
$_SESSION = [];
session_destroy();
setcookie(session_name(), '', ['expires' => 1, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
>>4 Do not just make the session live for months. The usual way is a separate random token (bin2hex(random_bytes(32))) in its own cookie, with only its hash stored in the database, an expiry date, and a new token every time it is used. On password change, delete all such tokens of that user.
This is gold, thank you both. Going to rebuild the login part properly before I add anything else.
Only signed-in members can write. Sign in