php · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Store a of the password, never the password itself.
If your database leaks, every plain password leaks with it, and people reuse passwords everywhere. So never store them. Store a hash instead: a scrambled fingerprint that cannot be turned back. password_hash($password, PASSWORD_DEFAULT) makes one with a slow, strong method chosen by PHP.
Each hash includes a random , so two people with the same password still get different hashes, and an attacker cannot look them up in a ready-made list. To check a login, password_verify($typed, $hash) repeats the scrambling and returns true or false.
<?php
$hash = password_hash("correct horse", PASSWORD_DEFAULT);
echo "Stored: " . strlen($hash) . " characters\n";
if (password_verify("correct horse", $hash)) {
echo "Right password: welcome back!\n";
}
if (!password_verify("wrong horse", $hash)) {
echo "Wrong password: try again.\n";
} The hash itself changes on every run because of its salt, so these lessons show its length instead.
guess first
One password, hashed twice. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$first = password_hash("pa55word", PASSWORD_DEFAULT);
$second = password_hash("pa55word", PASSWORD_DEFAULT);
if ($first === $second) {
echo "Same hash\n";
} else {
echo "Different hashes\n";
}
if (password_verify("pa55word", $first) && password_verify("pa55word", $second)) {
echo "Both still check out\n";
}
your turn
Your turn. Register Ava, then log in.
Choose Ava's password in the first blank. Line 4 pretends a login form was sent, so type the same password to get in, or a different one to be refused.
fix it
The right password is refused every time. Fix it.
- The password matches, yet it says wrong. What do you know about hashing the same password twice?
- Each new hash gets a fresh salt, so it never equals the stored one. Comparing hashes with
===can never work. - On line 4, change the condition to
password_verify($_POST["password"], $stored), then run it.
nailed it
your passwords are hashed and salted. :D
- Never store passwords. Store what
password_hashgives you. - A random salt makes every hash different, even for equal passwords.
- Check logins with
password_verify, never with===.
new words in your collection
- hash
- salt
This lesson isn’t saved. A free account remembers every lesson you finish.