A login system answers one question on every request: who is this visitor?
Because HTTP forgets everyone between requests, the answer must be stored somewhere. Here is the whole picture.
The four parts
- Registration: the visitor creates an account. You store their email and a hash of their password.
- Login: the visitor sends an email and password. You check the password against the hash.
- Session: if it matches, you remember “this browser is user 42” in a session.
- Protection: pages that need a login check the session, and send visitors who are not logged in to the login page.
And a fifth, logout, which forgets the session.
The flow
Register -> INSERT user (email, password_hash)
Login -> find user by email
password_verify($typed, $user["password_hash"])
session_regenerate_id(true)
$_SESSION["user_id"] = $user["id"]
Each page -> if (!isset($_SESSION["user_id"])) redirect to login
Logout -> destroy the session
The most important rule
Never store the password itself. If your database leaks, every user’s password leaks too, and people reuse passwords across sites. Store a one-way hash. You can check a password against it, but you cannot get the password back. See Password Hashing.
What you need
| Piece | Where it is explained |
|---|---|
A users table with a password_hash column | Creating a Database and Table |
| Registration form and validation | Registration |
password_hash() | password_hash() |
password_verify() | password_verify() |
| Login and session | Login Sessions |
| Logout | Logout |
| Protecting pages | Protecting Pages |
Authentication vs authorization
Two different words that people mix up:
- Authentication is “who are you?” (the login).
- Authorization is “what are you allowed to do?” (an admin can delete users, a normal user cannot).
This chapter covers authentication, with a simple role column for the basics of authorization.
Should you build your own?
Learning how a login works is valuable. For a real product, use a well-tested library or framework feature (Laravel Breeze or Fortify, Symfony Security, WordPress’s user system). They handle many edge cases for you. Understanding the basics lets you use them well, and review them critically.
A word about “social login”
“Log in with Google” and similar buttons use OAuth / OpenID Connect. They are a different mechanism, where another service proves who the user is. The session part afterwards is the same as here.