← Вернуться к курсу: PHP from scratch

Secure passwords, login and week 7 review

Видео скоро появится

Storing passwords is one of the most serious responsibilities of a developer. If your database leaks and the passwords are in plain text, the damage is enormous, because many people reuse the same password on several sites. That is why the password is never stored, but a hash: the result of a one-way mathematical function that cannot be reversed. When logging in, you compute the hash of what the user types and compare it with the stored one. PHP solves all this with two functions: password_hash and password_verify.

password_hash and password_verify

password_hash($password, PASSWORD_DEFAULT) currently uses the bcrypt algorithm, adds a unique random salt (which is why two hashes of the same password differ) and includes the algorithm and cost in the result, so you need to store nothing else. password_verify checks a password against a hash, in constant time. With password_needs_rehash you can detect old hashes and update them when the user logs in. Never use md5, sha1 or a plain hash() for passwords: they are too fast and break under brute force. Store the hash in a TEXT or VARCHAR(255) column.

php
<?php

declare(strict_types=1);

$password = 'correct horse battery staple';

$hash = password_hash($password, PASSWORD_DEFAULT);
echo strlen($hash), "\n";                       // 60
echo substr($hash, 0, 4), "\n";                 // $2y$  (bcrypt)

var_dump(password_verify($password, $hash));    // bool(true)
var_dump(password_verify('wrong', $hash));      // bool(false)

// Two hashes of the same password differ because of the random salt
var_dump($hash === password_hash($password, PASSWORD_DEFAULT)); // bool(false)

if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $hash = password_hash($password, PASSWORD_DEFAULT);        // update stored hash
}

Registration and login

Let us put it all together: PDO, prepared statements, password_hash and sessions. At registration you validate the data, check that the email does not exist and store the hash. At login you look up the user by email, verify the password and, if correct, call session_regenerate_id(true) and store only their id in the session. Two good practices: always use the same generic message ("Invalid email or password") whether the email does not exist or the password is wrong, so you do not reveal which accounts exist; and limit failed attempts to slow down brute-force attacks.

php
<?php
// File: src/auth.php
declare(strict_types=1);

function registerUser(PDO $pdo, string $email, string $password): bool
{
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false || mb_strlen($password) < 8) {
        return false;
    }

    $exists = $pdo->prepare('SELECT 1 FROM users WHERE email = :email');
    $exists->execute([':email' => $email]);
    if ($exists->fetchColumn() !== false) {
        return false;
    }

    $insert = $pdo->prepare('INSERT INTO users (email, password_hash) VALUES (:email, :hash)');
    $insert->execute([
        ':email' => $email,
        ':hash' => password_hash($password, PASSWORD_DEFAULT),
    ]);
    return true;
}

function attemptLogin(PDO $pdo, string $email, string $password): bool
{
    $stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = :email');
    $stmt->execute([':email' => $email]);
    $user = $stmt->fetch();

    if ($user === false || !password_verify($password, $user['password_hash'])) {
        return false;                       // same result for both cases
    }

    session_regenerate_id(true);            // prevents session fixation
    $_SESSION['user_id'] = (int) $user['id'];
    return true;
}

function currentUserId(): ?int
{
    return isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;
}
sql
-- Schema for the users table (SQLite)
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

One last precaution: do not impose absurd rules such as "one uppercase, one number and one symbol" while setting a short maximum length. It is better to require a reasonable minimum length, allow long phrases and any character, and encourage the use of a password manager. If you later add two-step verification, account security will improve far more than with any format rule. And never send the password by email nor write it to logs.

Проверьте себя

Вопрос 1 из 6

Which function verifies a password against its hash?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →