Skip to content

PHP Tutorial Authentication

How Login Systems Work

Lesson 280 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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

  1. Registration: the visitor creates an account. You store their email and a hash of their password.
  2. Login: the visitor sends an email and password. You check the password against the hash.
  3. Session: if it matches, you remember “this browser is user 42” in a session.
  4. 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

Text
PLAIN
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

PieceWhere it is explained
A users table with a password_hash columnCreating a Database and Table
Registration form and validationRegistration
password_hash()password_hash()
password_verify()password_verify()
Login and sessionLogin Sessions
LogoutLogout
Protecting pagesProtecting 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.

dangerous
Security matters from day one
A login form is the front door of your site. Every lesson in this chapter includes the safe way to do it. Do not skip the parts about hashing, session regeneration and error messages.