Project: Login & Registration System
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
| Feature | Technique | Lesson |
|---|---|---|
| Secure password storage | password_hash(), password_verify(), password_needs_rehash() | Password Hashing |
| Session fixation protection | session_regenerate_id(true) at login | Session Security |
| Forged requests blocked | CSRF tokens on all forms, including logout | CSRF Protection |
| Brute-force protection | Counting failed attempts per email and IP | — |
| No account enumeration | Identical messages and timing for unknown emails and wrong passwords | Password Hashing |
| Unique emails, even under concurrency | UNIQUE index + error 1062 handling | PDO Error Handling |
| Protected pages | requireLogin() 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_hashisVARCHAR(255), so future hashing algorithms fit.- The
UNIQUEkey onemailguarantees one account per address, even if two registrations arrive at the same time. login_attemptsrecords 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
- 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. - 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 isnullin both failure cases. ($user['password_hash'] ?? ...safely handles$user === false.) - Recording and clearing: failures are recorded; a successful login clears the email's failures.
- Hash upgrades: outdated hashes are replaced transparently at login. Old rows in
login_attemptscan 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()returnspath,domain,secure,httponly, andsamesite— the values needed to delete the cookie correctly — pluslifetime, whichsetcookie()does not accept and is therefore removed. The array union['expires' => ...] + $paramscombines 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
| Test | Expected Result |
|---|---|
| Register with mismatching passwords | Error 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 email | The 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 in | Redirect to the login page with "Please log in to continue." |
| Compare the session cookie before and after login | The session ID changes |
| Submit the logout form from another page without a token | Rejected |
Check the users table | Only $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.
Logout via a GET Link
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