Project: Login & Registration System

JA JASWANT Updated 04 Nov 2026
10 min read ·Lesson 235 of 238

What You Will Build

A complete user account system: visitors register with name, email, and password; registered users log in, see a personal dashboard, and log out. Protected pages are only accessible when logged in. The project applies the security lessons in practice — password hashing, session security, CSRF protection, and protection against password-guessing attacks.

Features

FeatureTechniqueLesson
Secure password storagepassword_hash(), password_verify(), password_needs_rehash()Password Hashing
Session fixation protectionsession_regenerate_id(true) at loginSession Security
Forged requests blockedCSRF tokens on all forms, including logoutCSRF Protection
Brute-force protectionCounting failed attempts per email and IP—
No account enumerationIdentical messages and timing for unknown emails and wrong passwordsPassword Hashing
Unique emails, even under concurrencyUNIQUE index + error 1062 handlingPDO Error Handling
Protected pagesrequireLogin() guard—

Project Structure

auth-system/
├── public/
│   ├── register.php
│   ├── login.php
│   ├── dashboard.php     ← protected
│   └── logout.php        ← POST only
└── src/
    ├── bootstrap.php     ← session, helpers, pdo()
    └── auth.php          ← validation and authentication functions

src/bootstrap.php contains the helpers from Project: Contact Form with Email (e(), csrfToken(), csrfValid(), flash()), a secure session_start() with use_strict_mode, and the pdo() connection function from PDO Connect.


Step 1: Database Tables

CREATE TABLE users (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_login_at DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE login_attempts (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    email VARCHAR(255) NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    attempted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_attempts_email_time (email, attempted_at),
    KEY idx_attempts_ip_time (ip_address, attempted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • password_hash is VARCHAR(255), so future hashing algorithms fit.
  • The UNIQUE key on email guarantees one account per address, even if two registrations arrive at the same time.
  • login_attempts records failed logins; the indexes make counting recent attempts fast. VARCHAR(45) fits IPv6 addresses.

Step 2: Registration Logic

<?php
// src/auth.php
function validateRegistration(array $input): array
{
    $get = fn(string $key): string => is_string($input[$key] ?? null) ? $input[$key] : '';
    $data = [
        'name' => trim(preg_replace('/\s+/u', ' ', $get('name'))),
        'email' => strtolower(trim($get('email'))),
        'password' => $get('password'),
    ];
    $errors = [];
    if (mb_strlen($data['name']) < 2 || mb_strlen($data['name']) > 100) {
        $errors['name'] = 'Please enter your name (2–100 characters).';
    }
    if (filter_var($data['email'], FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = 'Please enter a valid email address.';
    }
    if (mb_strlen($data['password']) < 8) {
        $errors['password'] = 'Use at least 8 characters.';
    } elseif (strlen($data['password']) > 72) {
        $errors['password'] = 'Use at most 72 bytes (about 72 characters).';
    }
    if (!hash_equals($data['password'], $get('password_confirmation'))) {
        $errors['password_confirmation'] = 'The passwords do not match.';
    }
    return ['data' => $data, 'errors' => $errors];
}
function registerUser(PDO $pdo, array $data): ?int
{
    try {
        $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)')
            ->execute([$data['name'], $data['email'], password_hash($data['password'], PASSWORD_DEFAULT)]);
        return (int) $pdo->lastInsertId();
    } catch (PDOException $e) {
        if (($e->errorInfo[1] ?? null) === 1062) {
            return null;   // email already registered
        }
        throw $e;
    }
}

Testing the Validation

<?php
require __DIR__ . '/src/auth.php';
$result = validateRegistration([
    'name' => 'Asha',
    'email' => 'asha@example.com',
    'password' => 'short',
    'password_confirmation' => 'shorter',
]);
print_r($result['errors']);

Output

Array
(
    [password] => Use at least 8 characters.
    [password_confirmation] => The passwords do not match.
)

The 72-byte limit reflects bcrypt, which ignores everything after the 72nd byte (see Password Hashing). Passwords are never trimmed or otherwise altered — spaces are legitimate characters.


Step 3: Login Logic With Brute-Force Protection

<?php
// src/auth.php (continued)
const MAX_ATTEMPTS_PER_EMAIL = 5;
const MAX_ATTEMPTS_PER_IP = 20;
const ATTEMPT_WINDOW = '15 MINUTE';
function tooManyAttempts(PDO $pdo, string $email, string $ip): bool
{
    $stmt = $pdo->prepare(
        'SELECT
            SUM(email = :email) AS by_email,
            SUM(ip_address = :ip) AS by_ip
         FROM login_attempts
         WHERE attempted_at > NOW() - INTERVAL ' . ATTEMPT_WINDOW . '
           AND (email = :email2 OR ip_address = :ip2)'
    );
    $stmt->execute(['email' => $email, 'ip' => $ip, 'email2' => $email, 'ip2' => $ip]);
    $counts = $stmt->fetch();
    return (int) $counts['by_email'] >= MAX_ATTEMPTS_PER_EMAIL
        || (int) $counts['by_ip'] >= MAX_ATTEMPTS_PER_IP;
}
function attemptLogin(PDO $pdo, string $email, string $password, string $ip): ?array
{
    $email = strtolower(trim($email));
    $stmt = $pdo->prepare('SELECT id, name, email, password_hash FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    $hash = $user['password_hash'] ?? dummyPasswordHash();
    $valid = password_verify($password, $hash) && $user !== false;
    if (!$valid) {
        $pdo->prepare('INSERT INTO login_attempts (email, ip_address) VALUES (?, ?)')->execute([$email, $ip]);
        return null;
    }
    $pdo->prepare('DELETE FROM login_attempts WHERE email = ?')->execute([$email]);
    if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
        $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
            ->execute([password_hash($password, PASSWORD_DEFAULT), $user['id']]);
    }
    $pdo->prepare('UPDATE users SET last_login_at = NOW() WHERE id = ?')->execute([$user['id']]);
    return $user;
}
function dummyPasswordHash(): string
{
    static $hash = null;
    return $hash ??= password_hash('timing-equalizer', PASSWORD_DEFAULT);
}

How It Works

  1. Rate limiting: before checking a password, the login page asks tooManyAttempts(). Five failures for one email, or 20 from one IP address, within 15 minutes block further attempts. The fixed interval is part of the SQL text (a constant), while email and IP are parameters. Each named placeholder is used once, because native prepared statements do not allow repeating a name.
  2. Constant behavior: for unknown emails, password_verify() still runs against a dummy hash, so attackers cannot tell from response times which emails are registered. The result is null in both failure cases. ($user['password_hash'] ?? ... safely handles $user === false.)
  3. Recording and clearing: failures are recorded; a successful login clears the email's failures.
  4. Hash upgrades: outdated hashes are replaced transparently at login. Old rows in login_attempts can be deleted by a daily cron job (DELETE FROM login_attempts WHERE attempted_at < NOW() - INTERVAL 1 DAY).

Step 4: Session Functions

<?php
// src/auth.php (continued)
function logInUser(array $user): void
{
    session_regenerate_id(true);
    $_SESSION['user_id'] = (int) $user['id'];
    $_SESSION['_csrf'] = bin2hex(random_bytes(32));
}
function logOutUser(): void
{
    $_SESSION = [];
    $params = session_get_cookie_params();
    unset($params['lifetime']);   // not a valid setcookie() option
    setcookie(session_name(), '', ['expires' => time() - 3600] + $params);
    session_destroy();
}
function currentUser(PDO $pdo): ?array
{
    static $user = false;
    if ($user === false) {
        $user = null;
        if (isset($_SESSION['user_id'])) {
            $stmt = $pdo->prepare('SELECT id, name, email, created_at FROM users WHERE id = ?');
            $stmt->execute([$_SESSION['user_id']]);
            $user = $stmt->fetch() ?: null;
        }
    }
    return $user;
}
function requireLogin(PDO $pdo): array
{
    $user = currentUser($pdo);
    if ($user === null) {
        flash('Please log in to continue.');
        header('Location: /login.php', true, 303);
        exit;
    }
    return $user;
}
  • The session stores only the user ID. Name and email are loaded fresh from the database, so changes (or a deleted account) take effect immediately.
  • logInUser() regenerates the session ID (fixation protection) and issues a new CSRF token.
  • logOutUser() empties the session, deletes the cookie, and destroys the stored session (see Session Security). session_get_cookie_params() returns path, domain, secure, httponly, and samesite — the values needed to delete the cookie correctly — plus lifetime, which setcookie() does not accept and is therefore removed. The array union ['expires' => ...] + $params combines the rest.

Step 5: The Pages

public/register.php

<?php
require __DIR__ . '/../src/bootstrap.php';
require __DIR__ . '/../src/auth.php';
$data = ['name' => '', 'email' => ''];
$errors = [];
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!csrfValid($_POST['_csrf'] ?? null)) {
        $errors['form'] = 'Your session expired. Please try again.';
    } else {
        ['data' => $data, 'errors' => $errors] = validateRegistration($_POST);
        if ($errors === []) {
            $userId = registerUser(pdo(), $data);
            if ($userId === null) {
                $errors['email'] = 'An account with this email already exists. Try logging in.';
            } else {
                logInUser(['id' => $userId]);
                flash("Welcome, {$data['name']}! Your account has been created.");
                header('Location: /dashboard.php', true, 303);
                exit;
            }
        }
    }
}
?>
<h1>Create an account</h1>
<?php if (isset($errors['form'])): ?><p class="error"><?= e($errors['form']) ?></p><?php endif; ?>
<form method="post">
    <input type="hidden" name="_csrf" value="<?= e(csrfToken()) ?>">
    <label>Name <input name="name" value="<?= e($data['name']) ?>" required autocomplete="name"></label>
    <?php if (isset($errors['name'])): ?><p class="error"><?= e($errors['name']) ?></p><?php endif; ?>
    <label>Email <input type="email" name="email" value="<?= e($data['email']) ?>" required autocomplete="email"></label>
    <?php if (isset($errors['email'])): ?><p class="error"><?= e($errors['email']) ?></p><?php endif; ?>
    <label>Password <input type="password" name="password" required minlength="8" autocomplete="new-password"></label>
    <?php if (isset($errors['password'])): ?><p class="error"><?= e($errors['password']) ?></p><?php endif; ?>
    <label>Repeat password <input type="password" name="password_confirmation" required autocomplete="new-password"></label>
    <?php if (isset($errors['password_confirmation'])): ?><p class="error"><?= e($errors['password_confirmation']) ?></p><?php endif; ?>
    <button type="submit">Register</button>
</form>
<p>Already registered? <a href="/login.php">Log in</a></p>

Password fields are never refilled after an error — passwords must not be echoed back into pages. The autocomplete attributes help password managers.

public/login.php

<?php
require __DIR__ . '/../src/bootstrap.php';
require __DIR__ . '/../src/auth.php';
$email = '';
$error = null;
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $email = is_string($_POST['email'] ?? null) ? strtolower(trim($_POST['email'])) : '';
    $password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    if (!csrfValid($_POST['_csrf'] ?? null)) {
        $error = 'Your session expired. Please try again.';
    } elseif (tooManyAttempts(pdo(), $email, $ip)) {
        $error = 'Too many failed attempts. Please wait 15 minutes and try again.';
    } else {
        $user = attemptLogin(pdo(), $email, $password, $ip);
        if ($user === null) {
            $error = 'Invalid email or password.';
        } else {
            logInUser($user);
            header('Location: /dashboard.php', true, 303);
            exit;
        }
    }
}
$message = flash();
?>
<h1>Log in</h1>
<?php if ($message !== null): ?><p class="info"><?= e($message) ?></p><?php endif; ?>
<?php if ($error !== null): ?><p class="error" role="alert"><?= e($error) ?></p><?php endif; ?>
<form method="post">
    <input type="hidden" name="_csrf" value="<?= e(csrfToken()) ?>">
    <label>Email <input type="email" name="email" value="<?= e($email) ?>" required autocomplete="username"></label>
    <label>Password <input type="password" name="password" required autocomplete="current-password"></label>
    <button type="submit">Log in</button>
</form>
<p>New here? <a href="/register.php">Create an account</a></p>

public/dashboard.php and public/logout.php

<?php
// public/dashboard.php
require __DIR__ . '/../src/bootstrap.php';
require __DIR__ . '/../src/auth.php';
$user = requireLogin(pdo());
$message = flash();
?>
<h1>Dashboard</h1>
<?php if ($message !== null): ?><p class="success"><?= e($message) ?></p><?php endif; ?>
<p>Hello, <?= e($user['name']) ?>! You are logged in as <?= e($user['email']) ?>.</p>
<p>Member since <?= e((new DateTimeImmutable($user['created_at']))->format('d M Y')) ?>.</p>
<form method="post" action="/logout.php">
    <input type="hidden" name="_csrf" value="<?= e(csrfToken()) ?>">
    <button type="submit">Log out</button>
</form>
<?php
// public/logout.php
require __DIR__ . '/../src/bootstrap.php';
require __DIR__ . '/../src/auth.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST' || !csrfValid($_POST['_csrf'] ?? null)) {
    http_response_code(405);
    exit('Please use the logout button.');
}
logOutUser();
session_start();   // a fresh session, only to carry the flash message
flash('You have been logged out.');
header('Location: /login.php', true, 303);
exit;

Logout is a POST request with a CSRF token, so other websites cannot log users out. Because strict mode is enabled, the destroyed session ID is not reused: session_start() creates a new, empty session for the flash message.


Testing the Project

TestExpected Result
Register with mismatching passwordsError under "Repeat password"; name and email kept, passwords empty
Register the same email twice"An account with this email already exists."
Log in with a wrong password, then with an unknown emailThe same message: "Invalid email or password."
Six wrong passwords for one email"Too many failed attempts…" even with the correct password
Open /dashboard.php without logging inRedirect to the login page with "Please log in to continue."
Compare the session cookie before and after loginThe session ID changes
Submit the logout form from another page without a tokenRejected
Check the users tableOnly $2y$... hashes, never plain passwords

Common Mistakes

Storing More Than the User ID in the Session

Effect: Changed names, roles, or deleted accounts stay active until logout. Fix: Store the ID; load user data per request.

Different Messages for Unknown Emails and Wrong Passwords

Effect: Attackers learn which emails have accounts. Fix: Use one generic message and equal timing.

No Rate Limiting

Effect: Unlimited password guessing. Fix: Limit failures per account and per IP, and consider CAPTCHA or MFA for repeated failures.

Effect: Any page can log users out with an image tag. Fix: Use a POST form with a CSRF token.


Best Practices

  • Hash passwords with password_hash() and upgrade hashes at login.
  • Regenerate the session ID at login and destroy sessions completely at logout.
  • Protect all forms with CSRF tokens and limit login attempts.
  • Enforce unique emails in the database and keep error messages generic.
  • Guard protected pages centrally with a function such as requireLogin(). Official reference: https://www.php.net/manual/en/features.sessions.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Project: Login & Registration System and get answers drawn from it.

Signed-in readers only.