Blog

Email OTP Login in PHP and MySQL with PHPMailer

Email OTP login illustration with an envelope, six code placeholders, and MySQL database

To build email OTP login in PHP and MySQL, generate a short-lived code on the server, send it to a registered email address, bind it to a specific login challenge, and consume that challenge once before creating an authenticated session. OTP means one-time password. Checking a code in browser JavaScript does not authenticate a real user.

This tutorial replaces the legacy email-login code with PHPMailer SMTP, prepared queries, keyed OTP storage, expiry and attempt limits, and transaction-based verification. The public demo is a fictional browser practice flow. The ZIP contains a separate PHP/MySQL starter for your staging environment.

Live demo: practice email OTP login

Generate a practice code and test wrong-code, expiry, lockout and reuse states. No email address is requested, no message is sent, and no real account is signed in. The visible inbox code is a teaching aid that must never be returned by a real login endpoint.

Practice email OTP login

Browser simulation — no email and no real login. Use the fictional account below. Do not enter an email address or a real one-time password.

Demo account: Sample member

Generate a demo code to begin.

Everything stays in page memory. The visible code is a teaching aid; a real server must never return its OTP to the browser.

How the server-side login flow works

  1. Accept a registered email address and validate CSRF and request limits.
  2. Find an active account using a prepared query.
  3. Generate a six-digit code and separate random challenge ID.
  4. Store a keyed digest, expiry and attempt state; send the code only by email.
  5. Verify this session’s challenge inside a database transaction.
  6. Consume it, rotate the session ID and establish the authenticated account.

The practice UI uses a 60-second expiry. The PHP starter uses five minutes and keeps the real code out of browser responses and database plaintext.

1. Prepare PHP, MySQL and PHPMailer

Use a supported PHP 8.x release, at least PHP 8.2, with PDO MySQL, OpenSSL and sessions; MySQL with InnoDB; Composer; and an authenticated SMTP service. The adapter uses STARTTLS on port 587. Keep credentials in the PHP process environment outside the public document root.

cd server
composer install

The ZIP declares phpmailer/phpmailer with a ^7.0.0 constraint. The official PHPMailer project documents Composer installation and SMTP configuration. Dependencies are installed separately; review and retain Composer’s generated lockfile in your application.

2. Create account, challenge and request-limit tables

CREATE TABLE users (
 id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 email VARCHAR(254) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL UNIQUE,
 active BOOLEAN NOT NULL DEFAULT TRUE,
 current_challenge CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL
) ENGINE=InnoDB;
CREATE TABLE email_otp_challenges (
 id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
 user_id BIGINT UNSIGNED NOT NULL,
 code_digest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
 expires_at BIGINT NOT NULL,
 attempts TINYINT UNSIGNED NOT NULL DEFAULT 0,
 used BOOLEAN NOT NULL DEFAULT FALSE,
 INDEX(user_id, used),
 FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE otp_limits (
 bucket CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
 window_start BIGINT NOT NULL,
 hits INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
-- Seed only an email address you own via a trusted admin process.
-- No public registration endpoint or credentials are included.

This example signs in pre-existing users; it does not implement public registration. Each challenge stores an account ID, code digest, expiry, attempt count and used flag. The account’s current-challenge pointer prevents an older challenge from authenticating after a resend.

The starter uses ASCII, lowercased, case-insensitive email identifiers. Seed test accounts with the same policy and only addresses you own. Internationalized email and provider-specific aliases require separate normalization rules.

3. Generate and protect a six-digit code

$challengeId = bin2hex(random_bytes(32));
$code = sprintf('%06d', random_int(0, 999999));
$digest = hash_hmac(
    'sha256',
    'otp:' . $challengeId . ':' . $code,
    $serverSecret
);

PHP’s random_int reference describes cryptographically secure integer generation. Formatting preserves leading zeros. The small code space still requires expiry and attempt limits.

The hash_hmac reference documents the keyed digest. Keep its secret separate from the database. Including the random challenge ID prevents treating the same digits as a globally searchable login credential. Keyed storage helps against a database-only leak; it does not help if the attacker also obtains the key.

4. Send through authenticated SMTP

The full server/mailer.php reads SMTP configuration from environment variables and sends plain text with PHPMailer. Certificate verification stays enabled and web SMTP debug output stays off.

$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom($verifiedSender, 'Website sign-in');
$mail->addAddress($registeredEmail);
$mail->Subject = 'Your sign-in code';
$mail->Body = 'Your sign-in code is: ' . $code;
$mail->send();

This is an excerpt; the ZIP includes configuration loading and failure handling. SMTP acceptance does not guarantee inbox delivery. Configure a verified sender and your provider’s domain-authentication requirements, then test staging delivery. A sending exception invalidates the challenge and never creates a login.

5. Verify and consume atomically

Never search for any row with a matching OTP. Check the challenge associated with the current session, email and active user. The starter locks the user and challenge rows with SELECT ... FOR UPDATE, checks expiry and attempts, compares the keyed digest, and persists state before committing.

$decision = otpDecision($row, $submittedCode, time());
// While holding the transaction's row locks:
$update->execute([
    $decision['attempts'],
    $decision['approved'] ? 1 : (int) $row['used'],
    $row['id']
]);
// Clear the current pointer on success, then commit.

The full implementation is in server/bootstrap.php. Issuing and checking use the same user-first lock order. Resending invalidates earlier active challenges for that account. Do not split verification into an unlocked read and later consume operation.

Expiry, attempts and resend limits

Control PHP starter behavior
Expiry Five minutes; exact expiry boundary and later are rejected.
Attempt cap Five valid-format checks per challenge; used or locked challenges cannot authenticate.
Resend wait 30 seconds per session, plus persistent request counters.
Send limits Five per email and ten per direct IP per 15-minute window.
Check limits Ten per email and thirty per direct IP per window.
Binding Pending ID/email live in the server-side session; the database ties the challenge to its user.

These are tutorial thresholds. Fixed windows allow boundary bursts; distributed abuse needs further controls. Generic send messages reduce direct account disclosure, but timing and pending-state differences remain. This is not complete enumeration resistance.

OWASP’s authentication guidance discusses generic responses and throttling. Email OTP login alone is not automatically multifactor authentication, and email codes are not phishing-resistant. Choose authentication appropriate to your application.

Create and protect the login session

After successful consumption, rotate the session ID and record the authenticated account. The starter uses HTTP-only, SameSite cookies and CSRF checks on POST actions. Its dashboard checks active-account status and a 30-minute authenticated-session limit.

session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['authenticated_at'] = time();
$_SESSION['csrf'] = bin2hex(random_bytes(32));

Call requireLogin() on every protected route you add. Logout uses POST with CSRF validation, clears state and expires the cookie. Recovery, revocation and device policies are outside this starter.

Download and configure the project

  1. Extract the ZIP and open index.html for offline practice.
  2. Import server/schema.sql and seed an email account you control.
  3. Run composer install inside server.
  4. Set database, secret and SMTP environment variables from the README.
  5. Run this localhost command from the extracted project folder.
php -S 127.0.0.1:8080 -t server/public

Open http://127.0.0.1:8080. Only server/public is the web root; code, dependencies, SQL and credentials stay outside it. No .env loader is included. Deploy with correctly configured HTTPS and proxy cookie settings.

Validation scope: browser and PHP core checks cover local behavior. Real MySQL transactions, concurrency, Composer/SMTP setup and inbox delivery require staging integration tests. This is a tutorial starter, not an audited production authentication service.

Common email OTP problems

Problem Check
No email arrives Check SMTP authentication, sender settings, provider logs and spam handling.
Any account can use matching digits Bind verification to the session, intended user and random challenge ID.
Old code works after resend Invalidate prior challenges and enforce the current pointer.
A code works twice Consume it while holding database transaction locks.
Unlimited guesses Persist attempts and apply email/IP limits.
Secrets appear in the ZIP Load them from private server configuration.

Before production, add failure monitoring, bot/fraud controls, retention for expired rows, tested recovery, transaction-error handling and independent review. Do not log codes, secrets or raw SMTP responses into public errors.

Frequently asked questions

What does OTP stand for?

One-time password: a code intended for one challenge within a short validity window.

Can the public demo send email?

No. Its visible fictional inbox code and client-side state are only for practice. The PHP application is separate.

Should I store OTPs as plaintext?

This starter stores a keyed digest bound to a challenge ID. Protect the key and still enforce expiry and attempts.

Why does the ZIP need Composer?

Composer installs PHPMailer for SMTP. The offline browser practice page needs no dependencies.

Can it verify signup email addresses?

This code signs in existing active users. Signup and email changes need separate account-lifecycle policies.

Is email OTP automatically two-factor authentication?

No. Here email access is the login mechanism. Multiple factors require a separately designed flow.

Practice the flow and inspect the source

Test wrong-code, lockout, expiry and single-use behavior. Review the README and server source before connecting a staging database and SMTP account.