Blog
Mobile OTP Login in PHP and MySQL with SMS Verification
To build a mobile OTP login system in PHP and MySQL, look up a registered user with a prepared query, start an SMS verification on the server, and create a login session only after the verification provider approves the submitted code. OTP means one-time password. The browser should never decide whether a real user is authenticated.
This tutorial replaces the legacy SMS-gateway example with a PHP/MySQL starter that delegates code delivery and verification to Twilio Verify. The public demo is a separate browser simulation: no phone number, SMS charge, or real login is involved.
How SMS OTP login works
- The visitor submits a registered international phone number.
- PHP validates the request, applies request limits, and queries an active user in MySQL.
- The server requests SMS verification from the provider and binds the pending challenge to the current session.
- The visitor submits the code. PHP checks the challenge, attempt count, expiry, and provider response.
- After approval, PHP rechecks the account, rotates the session ID, and records the authenticated user ID.
A general SMS gateway delivers your message but leaves token generation, storage, expiry, verification and replay protection to your application. A managed verification service handles the provider-side code lifecycle. This example uses the latter approach; the PHP application still owns account authorization, session handling and abuse limits.
Live demo: practice an OTP flow
Generate a practice code, try an incorrect value, verify the correct value, then try reusing it. You can also simulate expiry or test five incorrect attempts. The visible inbox code is deliberately included for learning and must never appear in a real login response.
Practice the OTP login flow
Browser simulation — no SMS and no real login. Use the fictional account below. Do not enter a phone number or a real one-time password.
Demo account: Sample member
Simulated inbox code:
Expires after 60 seconds. Five incorrect attempts lock this challenge.
Copy the code shown above to practice verification.
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.
Browser demo versus PHP starter
| Part | What it does |
|---|---|
| Embedded browser demo | Fictional account, visible practice code, 60-second expiry, five incorrect attempts, no authentication. |
| Downloadable PHP application | Registered-user MySQL lookup, real Verify API calls, session-bound challenge, five-minute application expiry and protected sample dashboard. |
| SMS provider | Sends and checks actual codes after you configure an account and service. |
1. Prepare PHP, MySQL and a verification service
Use a supported PHP 8.x release with PDO MySQL, cURL, JSON and sessions, plus MySQL with InnoDB. Deploy behind HTTPS. Create a Verify service configured for six-digit codes, and keep its credentials in server environment variables. The ZIP does not load a .env file automatically.
The Twilio Verifications reference documents starting a verification. A successful start response does not itself confirm delivery or authenticate the user. Provider account restrictions, destination requirements and billing may apply; check them before sending real messages.
2. Store registered users, not plaintext OTPs
CREATE TABLE users (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
phone VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,
active BOOLEAN NOT NULL DEFAULT TRUE
) ENGINE=InnoDB;
CREATE TABLE otp_limits (
bucket CHAR(64) CHARACTER SET ascii PRIMARY KEY,
window_start BIGINT NOT NULL,
hits INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
-- Add an E.164 number that you own using a prepared statement in a trusted admin tool.
-- No real numbers or credentials are bundled. This tutorial does not provide public registration.
The phone column holds a normalized international number; the unique key prevents duplicate account numbers. This starter intentionally includes no public registration endpoint. Add only numbers you own through a trusted admin process during testing. The second table stores request counters keyed by a server-secret HMAC, not SMS codes.
3. Use a prepared query to find the account
$q = db()->prepare('SELECT id FROM users WHERE phone=? AND active=1');
$q->execute([$phone]);
$id = $q->fetchColumn();
Bind the phone value as a parameter rather than concatenating it into SQL. PHP’s PDO::prepare documentation explains the placeholder mechanism. A basic plus-sign-and-digits format check does not establish ownership or fully validate international numbering rules.
4. Start a server-side SMS verification
$verification = verifyApi('Verifications', [
'To' => $phone,
'Channel' => 'sms'
]);
// Save its SID with the pending session challenge, never in browser-controlled auth state.
The complete adapter in server/bootstrap.php authenticates the request with server-held credentials and leaves TLS certificate verification enabled. The login handler stores the provider verification SID with the account ID, phone number, attempt count and application expiry in the session. Do not put API tokens in HTML, JavaScript, URLs, downloadable configuration or error messages.
The starter returns a generic send message for unknown accounts and provider failures. This reduces obvious account disclosure, but differences in response timing remain. Treat account enumeration and abuse prevention as separate design work.
5. Verify the code before creating a session
$result = verifyApi('VerificationCheck', [
'VerificationSid' => $pending['sid'],
'Code' => $code
]);
if (($result['status'] ?? '') !== 'approved') {
throw new RuntimeException('Not approved');
}
// Recheck that the account is still active, then:
unset($_SESSION['pending']);
session_regenerate_id(true);
$_SESSION['user_id'] = $pending['id'];
$_SESSION['authenticated_at'] = time();
This is an excerpt; the ZIP includes CSRF checks, the pending-challenge guards, the active-account recheck, counters, redirects and logout. The Verification Check reference describes checking a submitted token. A pending or failed result must never establish a login.
PHP’s session security guidance covers cookie settings and session ID management. The sample rotates the session ID after authentication and checks a 30-minute authenticated-session limit on its dashboard. Every additional protected route needs the same authorization and timeout checks.
Expiry, resend and attempt limits
| Control | PHP starter behavior |
|---|---|
| Pending challenge | Bound to the current session, user, phone and provider verification SID. |
| Application expiry | Five minutes; provider validity is separate and may differ. |
| Verification attempts | At most five valid-format checks per challenge; provider errors consume attempts too. |
| Resend delay | 30 seconds per session; persistent phone/IP counters also apply. |
| Persistent request limits | Send: five per phone and ten per direct IP per 15-minute window. Check: ten per phone and thirty per direct IP per window. |
| Successful use | Clears the pending challenge before redirecting. |
These limits are tutorial defaults. Fixed windows can burst at boundaries, and distributed abuse still needs provider fraud controls and monitoring. Resends clear the local challenge, including on failure; a provider may reuse the same SMS token within its validity window, so a resend does not guarantee a new token.
Download and run the project
- Extract the ZIP. Open
index.htmlfor the offline browser practice flow. - For the PHP application, import
server/schema.sqland add a test account whose phone number you own. - Set
DB_DSN,DB_USER,DB_PASSWORD,TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN,TWILIO_VERIFY_SERVICE_SIDand a long randomRATE_LIMIT_SECRETin the PHP process environment. - For localhost development, run the command below from the extracted project folder. The only document root must be
server/public.
php -S 127.0.0.1:8080 -t server/public
Open http://127.0.0.1:8080. The development server is for localhost testing. Keep bootstrap.php and the schema outside the public document root. The README explains HTTPS/proxy settings, provider setup, integration checks and operational limits.
Validation scope: the public browser simulation is tested separately. Real SMS delivery, your provider account, and PHP/MySQL deployment require staging integration tests with your own configuration. The starter is not an audited production authentication service.
Before using SMS login in production
Configure provider fraud controls, spend limits, monitoring and service rate limits; define phone normalization, account recovery and number-change procedures. Review session expiry, revocation and authorization on all routes. Avoid exposing provider errors or sensitive logs. SMS codes can be phished, and phone numbers can be reassigned or taken over through SIM swaps. Consider passkeys when choosing an authentication method for higher-risk accounts.
Frequently asked questions
What is the full form of OTP?
OTP stands for one-time password: a code intended for a single verification within a limited validity period.
Can PHP send an SMS by itself?
PHP can call an SMS or verification provider API. Actual message delivery requires a configured provider or other SMS infrastructure.
Should I store OTPs in MySQL?
This starter delegates code handling to the verification provider and stores no OTP. If you build your own token service, you must separately design secure generation, protected storage, expiry, attempt limits and atomic single-use consumption.
Does a correct code automatically identify any account?
No. Verify the specific challenge associated with the intended user and session, then recheck account eligibility. Never search globally for any matching OTP.
Is the live demo a real login?
No. It demonstrates UI states only. Its visible code and client-side state must not be used to protect an account.
Does the ZIP work without SMS credentials?
The offline practice page does. The separate PHP login application requires MySQL, a registered test account and valid provider configuration; there is no authentication bypass.
Try the flow and inspect the source
Use the practice demo to understand wrong-code, expiry, lockout and single-use behavior, then review the PHP source and README before connecting a staging SMS account.