Password Hashing and Sessions

Password Hashing and Sessions in PHP: --- A bank does not keep a copy of your signature that a thief could photograph and reuse.


The Analogy: The Bank Vault's One-Way Deposit Slot and the Cloakroom Ticket

A bank does not keep a copy of your signature that a thief could photograph and reuse. Instead it uses a one-way process: your signature is checked against a stored impression, but the stored impression cannot be turned back into your actual pen strokes. If the vault is ever burgled, the thief gets impressions, not signatures they can forge elsewhere. Password hashing is that one-way deposit slot. You never store the password; you store a hash from which the password cannot be recovered, and on login you check a fresh attempt against it. Even if the database leaks, attackers get hashes, not passwords.

The one-way process is also deliberately slow and salted. Each deposit gets a unique random marker mixed in, so two customers with identical signatures produce completely different stored impressions -- an attacker cannot tell that two accounts share a password, nor precompute a giant lookup table. And the checking is slow by design, so an attacker who steals the impressions cannot test billions of guesses per second. PHP's password_hash bakes in both the random salt and a tunable cost, and password_verify does the slow, constant-time comparison.

Once you are inside the bank, you do not re-present your signature at every counter. You are given a cloakroom ticket -- a short, unguessable token -- that stands in for your identity for the rest of the visit. Show the ticket, get your service. A session is that ticket: after login, the server issues a session id, stored in a cookie, that represents "this browser is logged in as Ada" without resending the password on every request. The ticket is meaningless to anyone who does not hold it, and it is exchanged for the real identity only inside the bank's own records.

The failure mode has two classic forms. First, the bank that stores actual signatures -- storing plain or reversibly-encrypted passwords -- so one break-in forges every account; this is the cardinal sin password_hash exists to prevent. Second, the cloakroom that hands out a ticket before you have proved who you are, and keeps that same ticket number after you identify yourself. An attacker who plants a known ticket on your coat before login then holds a valid ticket for your session afterwards -- session fixation. The defence is to tear up the pre-login ticket and issue a fresh one the instant identity is established, which is why regenerating the session id on login is not optional. Store no secret you would not want stolen, and never trust a ticket issued before the holder proved who they were.


Syntax or Core Structure

Passwords are hashed with password_hash and checked with password_verify. The hash embeds the algorithm, cost, and a random salt, so verification needs only the hash and the candidate.

<?php
declare(strict_types=1);

$password = 'hunter2';
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);

echo 'verify correct: ', password_verify($password, $hash) ? 'yes' : 'no', "\n";
echo 'verify wrong: ', password_verify('nope', $hash) ? 'yes' : 'no', "\n";

echo 'needs rehash at cost 12: ',
    password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 12]) ? 'yes' : 'no', "\n";
echo 'needs rehash at cost 10: ',
    password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 10]) ? 'yes' : 'no', "\n";

Output:

verify correct: yes
verify wrong: no
needs rehash at cost 12: yes
needs rehash at cost 10: no

password_hash produces a salted bcrypt hash at cost 10. password_verify accepts the right password and rejects the wrong one, comparing in constant time. password_needs_rehash reports yes when checked against a higher cost of 12 -- signalling the stored hash is now weaker than policy wants -- and no at the matching cost of 10. That last function is how you transparently upgrade hashes as hardware improves and you raise the cost.


Technical Depth: Rehashing, Sessions, and Fixation

The password functions

Three functions cover the password lifecycle, and using them together gives forward-compatible storage.

FunctionRole
password_hashCreate a salted hash at a chosen cost
password_verifyConstant-time check of a candidate
password_needs_rehashDetect a hash weaker than current policy

Because password_needs_rehash lets you upgrade stored hashes, you can raise the cost over the years without ever asking users to reset -- the upgrade happens at their next login, when you have the plaintext in hand.

<?php
declare(strict_types=1);

final class Users {
    private array $hashes = [];
    public function register(string $u, string $p): void {
        $this->hashes[$u] = password_hash($p, PASSWORD_BCRYPT, ['cost' => 4]);
    }
    public function login(string $u, string $p): string {
        $hash = $this->hashes[$u] ?? null;
        if ($hash === null || !password_verify($p, $hash)) {
            return 'login failed';
        }
        if (password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 10])) {
            $this->hashes[$u] = password_hash($p, PASSWORD_BCRYPT, ['cost' => 10]);
            return 'login ok (hash upgraded)';
        }
        return 'login ok';
    }
}

$users = new Users();
$users->register('ada', 's3cret');
echo $users->login('ada', 'wrong'), "\n";
echo $users->login('ada', 's3cret'), "\n";
echo $users->login('ada', 's3cret'), "\n";

Output:

login failed
login ok (hash upgraded)
login ok

Registration stores a deliberately weak cost-4 hash, simulating legacy data. The wrong password fails. The first correct login verifies against the old hash, then password_needs_rehash detects the cost is below policy and re-stores a cost-10 hash -- reporting the upgrade. The next login verifies against the already-upgraded hash and needs no further work. Users never notice; their storage silently strengthens.

Sessions and fixation defence

After login, a session id represents the authenticated user. The critical security step is regenerating that id on login, so any id fixed before authentication becomes worthless.

<?php
declare(strict_types=1);

final class Session {
    private string $id;
    private array $data = [];
    public function __construct() { $this->id = bin2hex(random_bytes(8)); }
    public function id(): string { return $this->id; }
    public function regenerateId(): void { $this->id = bin2hex(random_bytes(8)); }
    public function set(string $k, mixed $v): void { $this->data[$k] = $v; }
    public function get(string $k): mixed { return $this->data[$k] ?? null; }
}

$s = new Session();
$before = $s->id();

$s->regenerateId();
$s->set('user_id', 42);

echo 'id changed on login: ', ($before !== $s->id() ? 'yes' : 'no'), "\n";
echo 'logged in user: ', $s->get('user_id'), "\n";
echo 'id length: ', strlen($s->id()), "\n";

Output:

id changed on login: yes
logged in user: 42
id length: 16

Before login the session has one id; regenerateId replaces it with a fresh random value at the moment of authentication, so the pre-login id -- which an attacker might have planted -- no longer identifies the session. The logged-in user id is stored under the new session, and the id is a 16-character hex string from random_bytes. In real PHP this is session_regenerate_id(true), and it is the single most important line in a login handler after the password check.

Remember-me tokens and constant-time comparison

A "remember me" token is a long-lived credential, so it must be treated like a password: stored hashed, and compared in constant time to avoid timing attacks. hash_equals compares two strings in time independent of where they differ.

<?php
declare(strict_types=1);

$raw = bin2hex(random_bytes(16));
$storedHash = hash('sha256', $raw);

function tokenMatches(string $storedHash, string $candidate): bool {
    return hash_equals($storedHash, hash('sha256', $candidate));
}

echo 'correct token: ', tokenMatches($storedHash, $raw) ? 'match' : 'no', "\n";
echo 'wrong token: ', tokenMatches($storedHash, 'deadbeef') ? 'match' : 'no', "\n";

echo 'equal strings: ', hash_equals('abc123', 'abc123') ? 'yes' : 'no', "\n";
echo 'differ at start: ', hash_equals('abc123', 'xbc123') ? 'yes' : 'no', "\n";

Output:

correct token: match
wrong token: no
equal strings: yes
differ at start: no

The raw token is sent to the browser, but only its SHA-256 hash is stored, so a database leak yields no usable tokens. tokenMatches hashes the candidate and compares with hash_equals, accepting the correct token and rejecting the wrong one. The final two lines show hash_equals returning a correct result whether the strings match or differ at the very first character -- and, crucially, taking the same time either way, so an attacker cannot learn how much of a guess was right by measuring response time. A plain === can short-circuit on the first differing byte, leaking exactly that timing signal.


Real World Example: A Complete Auth Flow

Bringing hashing and sessions together, an Auth service handles register, login, current-user, and logout, regenerating the session on both login and logout. This is the shape of a real authentication layer, minus the framework plumbing.

<?php
declare(strict_types=1);

final class Session {
    private string $id;
    public array $data = [];
    public function __construct() { $this->id = bin2hex(random_bytes(8)); }
    public function id(): string { return $this->id; }
    public function regenerate(): void { $this->id = bin2hex(random_bytes(8)); $this->data = []; }
}

final class Auth {
    private array $users = [];
    public function __construct(private Session $session) {}

    public function register(string $u, string $p): void {
        $this->users[$u] = password_hash($p, PASSWORD_DEFAULT);
    }
    public function login(string $u, string $p): bool {
        $hash = $this->users[$u] ?? null;
        if ($hash === null || !password_verify($p, $hash)) {
            return false;
        }
        $this->session->regenerate();
        $this->session->data['user'] = $u;
        return true;
    }
    public function currentUser(): ?string {
        return $this->session->data['user'] ?? null;
    }
    public function logout(): void {
        $this->session->regenerate();
    }
}

$auth = new Auth(new Session());
$auth->register('ada', 'pw123');

echo 'before login: ', var_export($auth->currentUser(), true), "\n";
echo 'bad login: ', $auth->login('ada', 'wrong') ? 'ok' : 'denied', "\n";
echo 'good login: ', $auth->login('ada', 'pw123') ? 'ok' : 'denied', "\n";
echo 'current: ', $auth->currentUser(), "\n";
$auth->logout();
echo 'after logout: ', var_export($auth->currentUser(), true), "\n";

Output:

before login: NULL
bad login: denied
good login: ok
current: ada
after logout: NULL

Before login there is no current user. A wrong password is denied by password_verify. A correct login regenerates the session -- defeating fixation -- and stores the username, so currentUser returns ada. Logout regenerates again, clearing the data, so the current user is null once more. Both hashing and session regeneration are handled in the one place responsible for authentication.

The design flaw is that regenerating the session on logout does not actually end the old session server-side; it only points this object at a new empty id. In a real deployment, if the previous session id was captured -- via an insecure cookie, a shared machine, or an XSS leak -- the server may still consider that old id valid unless it is explicitly invalidated in the session store. This model "logs out" by abandoning the reference, but abandoning a reference is not destroying the record: a genuine logout must invalidate the old session id on the server (PHP's session_destroy plus clearing the cookie), not merely mint a new one. There is a parallel gap on login: regenerating defeats fixation for this process, but a robust system also needs an absolute session lifetime, idle timeout, and the cookie flags HttpOnly, Secure, and SameSite so the ticket cannot be read by script, sent over plain HTTP, or ridden by a cross-site request. The lesson's model captures the two headline moves -- hash passwords, regenerate on login -- but treating "make a new session" as equivalent to "destroy the old one" is a real security gap, because the old ticket may still open the door until the server itself tears it up.


Common Mistakes

  1. Storing plain or encrypted passwords. Both are catastrophic on a breach. Hash with password_hash, which is a one-way salted hash.
  1. Rolling your own hashing. md5, sha1, or a static salt are broken for passwords. Use password_hash/password_verify, correct by design.
  1. Comparing hashes with ==. Naive comparison risks timing leaks and type juggling. Always use password_verify.
  1. Never rehashing. Leaving old, weak-cost hashes forever weakens security over time. Use password_needs_rehash to upgrade on login.
  1. Not regenerating the session id on login. Skipping this leaves you open to session fixation. Regenerate the id the moment identity is established.
  1. Thinking logout means abandoning the id. Pointing at a new session does not destroy the old one. Invalidate the old session server-side and clear the cookie.
  1. Insecure session cookies. Cookies without HttpOnly, Secure, and SameSite are exposed to script, plain HTTP, and cross-site rides. Set all three.
  1. No session timeout. A session that never expires is a standing risk. Enforce idle and absolute lifetimes.
  1. Leaking which half of login failed. Telling attackers "wrong password" versus "no such user" aids enumeration. Use one generic failure message.

Best Practices

  • Hash passwords with password_hash and verify with password_verify, never storing or comparing plaintext.
  • Choose a cost appropriate to your hardware, and use password_needs_rehash to upgrade stored hashes transparently at login.
  • Regenerate the session id on login to defeat fixation, and on logout invalidate the old session server-side, not just abandon it.
  • Set session cookies HttpOnly, Secure, and SameSite so the id cannot be read by script, sent over plain HTTP, or ridden cross-site.
  • Enforce both idle and absolute session lifetimes, expiring stale sessions.
  • Return one generic message for any login failure, so attackers cannot tell whether the user or the password was wrong.
  • Keep the authentication logic in one service, so hashing and session handling are applied consistently.
  • Use random_bytes or the platform's secure session id generation, never predictable values, for tokens and ids.

Practice Exercises

  1. Hash a password with a chosen cost, verify a correct and an incorrect attempt, and use password_needs_rehash to show it reports yes for a higher cost and no for the same cost.
  1. Write a Users class that stores a weak-cost hash on registration and upgrades it on successful login when password_needs_rehash says so, demonstrating the transparent upgrade.
  1. Model a session with a regenerateId method and show that the id changes on login while the stored user data is preserved under the new id.
  1. Build an Auth service with register, login, current-user, and logout, regenerating the session on login, and then extend logout to also record that the old id must be invalidated server-side.