Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 147 ยท Projects

Project: Login System

Build a secure PHP login system in four stages - registration with password_hash, session login, rate-limited attempts and safe remember-me tokens.

A login system is where small mistakes become headlines. Store passwords the wrong way and one database leak exposes every user's password on every other site where they reused it. Forget to change the session ID at login and an attacker can hijack the account. Let a script try passwords forever and weak ones will fall in hours. None of the defenses are complicated, but you need all of them, in the right order.

In this project you'll build a complete login system in four stages, each a runnable program. First, registration: validating the email and password and storing a hash with password_hash. Second, logging in and out with sessions, including session ID regeneration and automatic rehashing. Third, rate limiting failed attempts. Fourth, remember-me tokens that keep users signed in for weeks without storing anything secret in the cookie. You'll put Password Hashing, Sessions, Cookies and Hashing, Encryption and Random Numbers into practice.

Our editor runs PHP on the command line, without a browser or web server. The demos simulate sessions and cookies with small classes and arrays, and the users live in an SQLite database in memory. The comments in the code and the section after stage 4 show what the real session_start() and setcookie() calls look like. Hashing passwords is deliberately slow, so the stages that hash many times take a second or two to run.

The plan

The system has three tables:

Table Columns Used for
users id, email (unique), password_hash, created_at accounts
login_attempts email, ip, attempted_at rate limiting (stage 3)
remember_tokens selector (unique), validator_hash, user_id, expires_at remember me (stage 4)

And it follows a few rules that every stage respects:

  • Passwords are never stored, logged or printed, only their hashes.
  • Login errors are generic. "Wrong email or password" never reveals which one was wrong.
  • The session ID changes whenever the user's privilege changes: at login and at logout.
  • Every secret token is random (random_bytes) and compared with hash_equals.

Stage 1: registration

Registration has three jobs: validate the input, hash the password and insert the user.

The email is trimmed, lowercased and checked with filter_var(..., FILTER_VALIDATE_EMAIL). Lowercasing means [email protected] and [email protected] are the same account. (Strictly speaking, the part before the @ may be case-sensitive, but no major mail provider treats it that way, and users expect it not to matter.)

The password rules follow modern guidance: a minimum length matters far more than "one uppercase, one digit, one symbol" rules, which mostly produce Password1!. We require at least 12 characters, refuse a short list of very common passwords and refuse the user's own email. There's also a maximum of 72 bytes, for a technical reason: bcrypt, the default algorithm, only uses the first 72 bytes of the password and silently ignores the rest. Rejecting longer passwords is more honest than quietly truncating them. (Argon2id, the other algorithm PHP offers, has no such limit.)

The hash comes from password_hash($password, PASSWORD_DEFAULT). It generates a random salt for every call, runs the deliberately slow bcrypt algorithm and returns a 60-character string that contains everything needed to check the password later: the algorithm ($2y$), the cost (12, the default since PHP 8.4), the salt and the hash itself. You store that one string. password_verify reads the settings back out of it.

Duplicate emails are checked twice. A quick SELECT first avoids spending a quarter of a second on hashing for an address that's taken. But that check alone isn't enough: two requests at the same moment could both see "no such user" and both insert. The real guarantee is the UNIQUE constraint on the email column. Inserting an existing address throws a PDOException with SQLSTATE 23000 (integrity constraint violation), which register turns into the same friendly message.

PHP Stage 1: registering users with password_hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Ada registers as user #1, with her email stored as [email protected]. The next four attempts are refused for an invalid email, a short password, a common password (the check ignores case, so Password1234 matches) and an 80-byte password. [email protected] is normalized to the same address and refused as a duplicate, and Grace finally registers as user #2. The stored hash starts with $2y$12$ and is 60 characters long. password_verify accepts the right password and rejects the one with a capital C, and hashing the same password twice gives two different strings, thanks to the random salt.

Two details in the code deserve a mention:

  • #[\SensitiveParameter] (PHP 8.2) marks the password parameter so it's replaced by a placeholder object in stack traces. If register ever throws an uncaught exception, the password won't appear in your error log. See Attributes.
  • RegistrationError is a small custom exception for problems the user can fix. Anything else, like a broken database, is rethrown and handled as a real error.

"An account with this email already exists" tells an attacker which emails are registered (account enumeration). Many sites accept that trade-off for usability on the registration form. The stricter alternative is to always say "Check your inbox to continue" and email the existing user instead. On the login form, though, never reveal whether the email exists; stage 2 shows how.

Stage 2: logging in and out

Logging in means: find the user by email, check the password with password_verify, and if both succeed, remember the user's id in the session. Every later request reads the id from the session to know who's there.

A real session is started with session_start(), which sends the visitor a cookie containing a random session ID and gives you the $_SESSION array for that ID. In the demo, a tiny FakeSession class plays that role: it has an id and a data array, and regenerateId() replaces the ID the way session_regenerate_id(true) does.

The login function has four security details:

  1. Generic errors. Wrong email and wrong password produce the same message.
  2. Equal timing. If no user has that email, the function still runs password_verify against a dummy hash. Otherwise "unknown email" would answer in a millisecond and "wrong password" in a quarter of a second, and an attacker could time responses to find registered emails.
  3. A new session ID at login. If an attacker managed to plant a known session ID in the victim's browser before login (session fixation), that ID becomes worthless the moment the victim signs in. Logout regenerates it too, and clears the data.
  4. Automatic rehashing. password_needs_rehash reports whether a stored hash uses older settings than today's PASSWORD_DEFAULT. Right after a successful login is the only moment you have the plain password, so that's when you upgrade the hash. The demo creates Linus's account with cost 10, as if it was registered years ago, and his first login upgrades it to cost 12.
PHP Stage 2: session login, logout and rehashing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unknown email and the wrong password both print "Wrong email or password.", and both take about the same time because both run password_verify. The third attempt succeeds even with a leading space and capital letters, because the email is normalized exactly as at registration. That login also upgrades the stored hash from cost 10 to 12. Afterward the session holds user id 1 and has a new ID, and logout clears the data and changes the ID once more.

On a real server, the same steps use PHP's session functions:

PHP
// Login, after password_verify() succeeded:
session_regenerate_id(true);          // new ID, delete the old session file
$_SESSION['user_id'] = $user['id'];

// Logout:
$_SESSION = [];
session_regenerate_id(true);
// or end the session completely:
// session_destroy(); and delete the session cookie with setcookie(session_name(), '', ...)

Pages that need a logged-in user check the session at the top and redirect guests to the login form:

PHP
if (!isset($_SESSION['user_id'])) {
    header('Location: /login?return=' . urlencode($_SERVER['REQUEST_URI']), true, 303);
    exit;
}

If you use a return parameter like this, make sure the login page only redirects to local paths (starting with a single /), or attackers can build login links that send users to their own site afterward. Secure Coding Checklist calls this an open redirect.

Stage 3: rate limiting login attempts

password_hash makes each guess slow for an attacker who has stolen your database. But an attacker who simply sends guesses to your login form needs a different defense: a limit on how many attempts you accept.

Our limiter records every failed attempt in a login_attempts table with the email, the client's IP address and the time. Before checking a password, attempt counts the recent failures and refuses to even look at the password when either limit is reached:

  • 5 failures per email in 15 minutes protects one account against guessing.
  • 20 failures per IP address in 15 minutes slows down one machine trying many accounts (a "password spraying" attack).

A successful login deletes that email's failures, so a user who mistypes twice and then gets it right starts fresh. The waiting time is calculated from the oldest failure in the window: once it's older than 15 minutes, it no longer counts, and the user can try again. That's a sliding window, the same idea the contact form used.

As in earlier projects, the current time is passed in ($now, a Unix timestamp), so the demo can jump forward 15 minutes without waiting. The hashes in this stage use cost 10 to keep the demo quick, since it verifies a password several times; production code keeps the default.

PHP Stage 3: rate-limited login attempts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first five wrong guesses, 30 seconds apart, are answered with the usual "Wrong email or password." The sixth attempt, at 00:02:30, has the right password, but it's refused with "Too many failed attempts. Try again in 13 minute(s).", and the password isn't checked at all. That's the point: during a lockout, a correct guess must look exactly like a wrong one, or the attacker could keep guessing. At 00:10:00 the wait is down to 5 minutes. At 00:15:01 the first failure has left the window, so the login succeeds and clears the failures, and the typo at 00:16:00 is an ordinary failure again.

A few design notes:

  • LoginResult is a backed enum. Each case carries its message, and match or === comparisons can't be fooled by a typo the way string results can.
  • $column goes into the SQL string, but only ever as email or ip from our own array, never from input.
  • fetchColumn(1) reads the second column (password_hash) of the first row, or returns false if there's no row.
  • Lockouts can be abused. Anyone can lock Mira out for 15 minutes by typing her email with wrong passwords. That's why the limit is short and temporary rather than "locked until an admin resets it". Larger sites add a CAPTCHA after a few failures instead of blocking.
  • The IP address on a real server comes from $_SERVER['REMOTE_ADDR']. Behind a proxy or CDN that's the proxy's address, and the client's address is in a header like X-Forwarded-For, which you should only trust when it's set by your own proxy.

Stage 4: remember-me tokens

Sessions usually end when the browser closes or after some idle minutes. A "Remember me" checkbox keeps the user signed in for weeks with a separate, long-lived cookie. That cookie is as powerful as a password, so it must be designed carefully.

The naive version stores the user id in a cookie: remember=42. Anyone can change it to 43. Storing a random token is better, but if the database stores the token itself, anyone who reads the database (through a backup, an SQL injection, a curious employee) can log in as every user. The standard design is the selector and validator pattern:

  • The cookie holds two random values, selector:validator.
  • The database stores the selector in plain text (to find the row quickly) and only a SHA-256 hash of the validator.
  • To check a cookie, look up the row by selector, hash the cookie's validator and compare with hash_equals.

A database leak now reveals selectors and hashes, and neither is enough to build a working cookie. Plain SHA-256 is fine here, unlike for passwords, because the validator is 32 random bytes that nobody can guess, not a human-chosen word.

Two more rules complete the design:

  • Rotate on use. Each time the cookie logs someone in, the old token is deleted and a new one issued. A stolen cookie therefore works at most once, and only until the real user returns.
  • Detect theft. If a selector exists but its validator doesn't match, someone is presenting a forged or old cookie for that row. The safe reaction is to delete all of that user's tokens, signing them out everywhere.

The demo's Browser class holds the cookies and the session, so you can "close" the browser (drop the session but keep the cookies) and watch the remember-me cookie log the user back in.

PHP Stage 4: remember-me tokens with rotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Step by step: the login creates one token. The cookie is a 24-character selector and a 64-character validator. After reopening the browser, the cookie logs user 7 back in and is rotated: still one token in the database, but a different cookie. The attacker's copy of the old cookie no longer matches any selector, so it's simply ignored. The forged cookie has a real selector with a wrong validator, which looks like theft, so all of user 7's tokens are deleted. That also signs out the real laptop, which is the cautious choice. Finally, a fresh login on the phone issues a new token and logout removes it again, leaving zero tokens.

Notice that the code never compares validators with ===. hash_equals takes the same time however many characters match, so response times leak nothing. And because the cookie is split with explode(':', ..., 2) + ['', ''], a missing or malformed cookie becomes two empty strings instead of a warning about an undefined array key.

Running it on a real server

The real versions replace FakeSession with session_start() and the Browser class with setcookie() and $_COOKIE. Configure the session cookie before starting the session:

PHP
session_start([
    'cookie_httponly' => true,   // JavaScript can't read the session cookie
    'cookie_secure' => true,     // only sent over HTTPS
    'cookie_samesite' => 'Lax',  // not sent with cross-site POST requests
    'use_strict_mode' => true,   // refuse session IDs the server didn't create
]);

and set the remember-me cookie with the same protections:

PHP
setcookie('remember', "$selector:$validator", [
    'expires' => time() + REMEMBER_DAYS * 86400,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

The login, registration and logout forms also need a CSRF token, exactly as in the contact form project. A forged logout is merely annoying, but a forged login can sign the victim into the attacker's account and capture whatever they type next. And serve everything over HTTPS: without it, the session cookie and the password travel in plain text.

Before building your own login for a production site, look at what your framework provides. Laravel, Symfony and others ship authentication with all of these defenses plus password resets, email verification and two-factor authentication. Building it once yourself, as here, is the best way to understand and review what they do. See PHP Frameworks and CMSs.

Ideas for extending the system

  • Password reset by email: a single-use, expiring token stored as a hash, exactly like the remember-me validator.
  • Email verification: a signed link with hash_hmac that marks the account as verified.
  • "Sign out everywhere" in the account settings, using forgetUser() plus a per-user counter stored in the session that invalidates old sessions.
  • Breached password check: refuse passwords that appear in known data breaches, using a downloaded list of SHA-1 prefixes.
  • Argon2id: switch PASSWORD_DEFAULT to PASSWORD_ARGON2ID and watch password_needs_rehash upgrade users as they log in.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does stage 2 call password_verify against a dummy hash when the email isn't found?

    Without the dummy check, unknown emails would be answered much faster than wrong passwords, letting an attacker discover registered accounts by measuring response times.
  2. 2. What does password_hash('same', PASSWORD_DEFAULT) === password_hash('same', PASSWORD_DEFAULT) evaluate to?

    Every hash includes a fresh salt, so the strings differ. password_verify reads the salt from the stored hash, which is why you never compare hashes yourself.
  3. 3. Why is session_regenerate_id(true) called right after a successful login?

    Changing the ID when privileges change means any ID known before login is worthless afterward. The old session file is deleted because of the true argument.
  4. 4. During a lockout, the user types the correct password. What does stage 3 answer?

    If a correct password could get through or produce a different answer during the lockout, the attacker could keep guessing. The throttle check runs before password_verify.
  5. 5. In the remember-me design, what is stored in the database?

    The selector finds the row, and only a hash of the validator is stored, so a database leak can't be turned into working cookies.

Summary

  • Hash passwords with password_hash($password, PASSWORD_DEFAULT), check them with password_verify, and upgrade old hashes with password_needs_rehash after a successful login.
  • Require long passwords (at least 12 characters), refuse common ones, and mind bcrypt's 72-byte limit. Let a UNIQUE constraint catch duplicate emails.
  • Keep login errors generic and timing equal, and call session_regenerate_id(true) at login and logout.
  • Rate-limit failed attempts per email and per IP with a sliding window, and check the limit before the password.
  • Build remember-me cookies from a selector and a validator, store only the validator's hash, compare with hash_equals, rotate on every use and revoke everything when theft is suspected.
  • Mark cookies HttpOnly, Secure and SameSite, protect auth forms with CSRF tokens and serve everything over HTTPS.

Next: Project: REST API