Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

PHP Authentication: Secure Registration, Login and Logout

7 min read Updated By the SkillNewton team

What is authentication in PHP?

Authentication in PHP is the process of confirming who a user is, usually by checking an email and password against a stored hash. A secure system hashes passwords with password_hash(), checks them with password_verify(), stores only the user ID in a regenerated session, limits repeated failed attempts and destroys the session completely on logout.

Authentication terms you need

  • Authentication answers "who are you?"; authorisation answers "what may you do?". The authentication and authorisation guide explains the difference.
  • Password hash: a one-way, deliberately slow transformation of the password with a random salt. You cannot reverse it; you can only check a guess against it.
  • Session: server-side state linked to the browser by a random ID cookie.
  • Throttling: slowing or blocking repeated failed logins to stop password guessing.

Hashing is not encryption: an encrypted value can be decrypted with a key, while a password hash cannot. The encryption versus hashing guide covers this in depth.

Database tables and registration with password_hash()

CREATE TABLE users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE login_attempts (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL,
  ip VARCHAR(45) NOT NULL,
  attempted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX (attempted_at)
);
<?php
// register.php (after checking the CSRF token)
$email = filter_var(strtolower(trim((string) ($_POST['email'] ?? ''))), FILTER_VALIDATE_EMAIL);
$password = (string) ($_POST['password'] ?? '');

if ($email === false || mb_strlen($password) < 12) {
    exit('Enter a valid email and a password of at least 12 characters.');
}

$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)');
$stmt->execute([$email, $hash]);

PASSWORD_DEFAULT currently uses bcrypt and may change to a stronger algorithm in future PHP versions, which is why the column is VARCHAR(255). Favour long passwords over complex composition rules, and consider rejecting passwords known from breaches. Use prepared statements, explained in the MySQL guide, for every query.

Logging in with password_verify() and throttling

The login script checks throttling first, then the password, and records failures. It shows the same message whether the email or the password was wrong, so attackers cannot discover which emails are registered.

<?php
// login.php (after session_start() and the CSRF check)
function isThrottled(PDO $pdo, string $email, string $ip): bool
{
    $stmt = $pdo->prepare(
        'SELECT COALESCE(SUM(email = :email), 0) AS by_email,
                COALESCE(SUM(ip = :ip), 0) AS by_ip
         FROM login_attempts
         WHERE attempted_at > NOW() - INTERVAL 15 MINUTE'
    );
    $stmt->execute(['email' => $email, 'ip' => $ip]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return (int) $row['by_email'] >= 5 || (int) $row['by_ip'] >= 50;
}

$email = strtolower(trim((string) ($_POST['email'] ?? '')));
$password = (string) ($_POST['password'] ?? '');
$ip = $_SERVER['REMOTE_ADDR'];

if (isThrottled($pdo, $email, $ip)) {
    http_response_code(429);
    exit('Too many attempts. Please wait 15 minutes.');
}

$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user === false || !password_verify($password, $user['password_hash'])) {
    $pdo->prepare('INSERT INTO login_attempts (email, ip) VALUES (?, ?)')->execute([$email, $ip]);
    exit('Email or password is incorrect.');
}

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('DELETE FROM login_attempts WHERE email = ?')->execute([$email]);
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $user['id'];
$_SESSION['last_activity'] = time();
header('Location: /account');
exit;

The per-IP limit is higher than the per-account limit because many people can share one IP address behind an office or mobile network. Throttling slows guessing without permanently locking anyone out; an attacker cannot block a real user for longer than the window. Old rows in login_attempts can be deleted by a scheduled job. session_regenerate_id(true) issues a new session ID at login, which defeats session fixation.

Protecting pages and logging out

Include one guard function at the top of every protected page. It redirects anonymous visitors and ends sessions that have been idle too long.

<?php
function requireLogin(int $idleSeconds = 1800): int
{
    $last = $_SESSION['last_activity'] ?? 0;
    if (empty($_SESSION['user_id']) || time() - $last > $idleSeconds) {
        $_SESSION = [];
        session_regenerate_id(true);
        header('Location: /login');
        exit;
    }
    $_SESSION['last_activity'] = time();
    return $_SESSION['user_id'];
}

Logout must be a POST request with a CSRF token. It empties $_SESSION, expires the session cookie, calls session_destroy() and deletes any remember-me tokens for that device. The complete logout code is in the PHP sessions and cookies guide.

Remember-me tokens stored as hashes

A remember-me cookie must never contain a user ID or password. Use a random selector and validator, store only a SHA-256 hash of the validator, and replace the token every time it is used.

<?php
// On a visit with no session but a "remember" cookie
[$selector, $validator] = explode(':', (string) ($_COOKIE['remember'] ?? ''), 2) + ['', ''];

$stmt = $pdo->prepare(
    'SELECT id, user_id, token_hash FROM auth_tokens WHERE selector = ? AND expires_at > NOW()'
);
$stmt->execute([$selector]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row && hash_equals($row['token_hash'], hash('sha256', $validator))) {
    $pdo->prepare('DELETE FROM auth_tokens WHERE id = ?')->execute([$row['id']]);
    session_regenerate_id(true);
    $_SESSION['user_id'] = (int) $row['user_id'];
    $_SESSION['last_activity'] = time();
    // Issue a fresh selector and validator and set a new cookie here
}

A fast hash such as SHA-256 is fine here because the validator is 32 random bytes, not a human-chosen password. Delete all of a user's tokens when they change their password.

PracticeWhy
Serve every page over HTTPSPasswords and session cookies cannot be read in transit
Use the same error for unknown email and wrong passwordHides which accounts exist
Require the current password to change email or passwordA stolen session alone cannot take over the account
Offer two-factor authentication for sensitive accountsA leaked password alone is not enough
Use single-use, expiring tokens for password resetReset links cannot be reused or guessed
Log logins and failures without logging passwordsSupports investigation without exposing secrets

Password reset without weakening security

A forgotten-password feature is a second way into every account, so it needs the same care as the login form. The safe pattern uses a single-use token sent by email and never reveals whether an address is registered.

  1. Show the same message, such as "If that email is registered, we have sent a link", whatever the user enters.
  2. For a registered email, generate bin2hex(random_bytes(32)), store only its SHA-256 hash with the user ID and an expiry of an hour or less, and email the plain token in a link.
  3. When the link is opened, hash the token from the URL, look it up and check it has not expired.
  4. Ask for the new password, save it with password_hash() and delete the reset token so it cannot be used again.
  5. Delete the user's remember-me tokens and other sessions, then send a "your password was changed" email.
  6. Throttle reset requests per email and per IP address, just like login attempts.

Never email the password itself and never let users set a new password from a link that is older than its expiry. These rules follow the same idea as the remember-me tokens above: the database holds hashes, and the plain secret exists only in the user's hands.

Practical exercise: build and attack-test your own login

On your own local machine, build register.php, login.php, account.php and logout.php using the code above.

  • Register a test user and confirm the database stores a hash starting with $2y$, never the password.
  • Enter a wrong password six times and confirm the sixth attempt is refused with status 429.
  • Compare the session ID cookie before and after login in your browser developer tools.
  • Leave account.php idle past the timeout and confirm you are sent to the login page.

You are done when all four checks pass and logging out followed by the back button no longer shows account content. Authentication is built in depth in the advanced PHP course.

Common mistakes

  • Hashing passwords with md5(), sha1() or a plain SHA-256 call instead of password_hash().
  • Storing the hash in a short column such as VARCHAR(60), which breaks when the default algorithm changes.
  • Telling users "email not found", which reveals registered accounts.
  • Forgetting session_regenerate_id(true) after login.
  • Saving remember-me tokens in plain text, so a database leak lets attackers sign in.
  • Allowing unlimited login attempts, which invites password guessing.

Frequently asked questions

Should I add my own salt to password_hash()?

No. password_hash() generates a random salt for every password and stores it inside the hash string. Supplying your own salt is deprecated and unnecessary.

Is Argon2 better than bcrypt?

Argon2id is a modern, memory-hard algorithm and PHP supports it with PASSWORD_ARGON2ID when compiled with the required library. PASSWORD_DEFAULT remains a safe choice because PHP updates it over time.

Can I use sessions to authenticate an API?

Session cookies suit a browser front end on the same site. Mobile apps and other servers usually send a token in the Authorization header, as shown in the REST API development guide.

How do I add two-factor authentication?

A common approach is time-based one-time passwords from an authenticator app, checked after the password step. Use a maintained library rather than writing the algorithm yourself.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.