Skip to navigation Skip to main content
  • English
  • Country
  • Deutsch
  • French
  • Requires WPML plugin
  • United States (USD)
  • Deutschland (EUR)
  • Japan (JPY)
  • Newsletter
  • Contact Us
  • FAQs
  • Html
  • Css
  • Developer Tools
    • JSON Formatter
    • Base64 Encoder / Decoder
    • URL Encoder / Decoder
    • UUID Generator
    • Regex Tester
    • Unix Timestamp Converter
    • CSS Gradient Generator
    • Box Shadow Generator
    • Border Radius Generator
    • PX / REM Converter
    • CSS Clamp Generator
  • Javascript
  • PHP
  • Jquery
Menu
Browse Categories
  • Instagram profile
  • New Collection
  • Woman Dress
  • Contact Us
  • Latest News
  • Purchase Theme
  • Blog
    • Theme elements
      • Alternative
      • Small images
      • Blog chess
      • Masonry grid
      • Meta on image
      • Infinit scrolling Features
      • Blog flat
      • Default flat
      • Blog mask
    • Theme elements Examples
      • Post example #1
      • Post example #2
      • Post example #3
      • Post example #4
      • Post example #5
      • Post example #6
      • Post example #7
      • Post example #8
    Recent Posts
    • Potted plant isolated on a transparent checkerboard in a photo editing workspace
      Remove a Background in Photoshop with Quick Action
      October 9, 2026 1 Comment
    • Five colorful CSS 3D social media icons with raised angled tiles
      3D Social Media Icons with CSS3
      October 9, 2026 1 Comment
    • Pure CSS tabs with four navigation controls above a content panel
      How to Create Pure CSS Tabs with HTML and CSS
      October 9, 2026 1 Comment
  • Shop Pages
    • Shop layouts
      • Filters area
      • AJAX Shop
      • Hidden sidebar Hot
      • No page heading
      • Small categories menu
      • Products list view
      • With background
      • Category description
      • Header overlap
      • Infinit scrolling
      • Load more button

    Advanced Variable products with swatches

    Products variations colors and images without any additional plugins.

    View More
  • Product Loop
    • Hover design Effects
      • All info on hover
      • Icons & Add to cart
      • Icons on hover
      • Quick shop
      • Full info on image
      • Button on image
      • Summary on hover
      • Standard button
      • Tiled hover
      • Full width button
      • Additional information
    • Products styles
      • Even product grid
      • Products color scheme
      • Bordered grid style outside
      • Bordered grid style inside
      • Products background New
      • Products shadow
      • Show empty star rating
      • Show SKU
      • Stock status position
  • Single Product
    • Page design
      • Default
      • Centered
      • Sticky description
      • With shadow
      • With background
      • Accordion tabs New
      • Accordion in content
      • With sidebar
      • Sidebar full-height
      • Extra content #1
      • Extra content #2 Hot
    • Product image
      • Thumbnails left
      • Thumbnails bottom
      • Without thumbnails
      • Sticky images
      • One column
      • Two columns
      • Combined grid
      • Carousel (2 columns)
      • Images full-width
      • Images full-width (container)
      • Zoom image
    • Product types
      • Simple product
      • Grouped product
  • Features
    • Configuring settings
      • Variations swatches New
      • Catalog mode
      • Login to see prices
      • Cookies law info
      • Shop sidebar widgets collapse
      • Mobile bottom navbar
      • Age verification
      • Variation on shop page #1
      • Variation on shop page #2 New
    • Product features Unlimited
      • All images on shop page
      • Pagination in main gallery
      • Size guides
      • 360° product viewer
      • Full width product page
      • Quantity input on shop page
      • Custom product tabs
      • Show brand on product loop
    • Extra features
      • Sticky add to cart
      • Buy now button
      • Visitor counter
      • Custom product label
  • SPECIAL OFFER
  • PURCHASE THEME

Blog

Blog

Mobile OTP Login in PHP and MySQL with SMS Verification

Posted by author-avatar Sandilyan
November 17, 2026
On March 18, 2019
0
SMS OTP login illustration with a phone, verification message, and MySQL database

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.

View live demo ↓Download source ZIP ↓

How SMS OTP login works

  1. The visitor submits a registered international phone number.
  2. PHP validates the request, applies request limits, and queries an active user in MySQL.
  3. The server requests SMS verification from the provider and binds the pending challenge to the current session.
  4. The visitor submits the code. PHP checks the challenge, attempt count, expiry, and provider response.
  5. 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

  1. Extract the ZIP. Open index.html for the offline browser practice flow.
  2. For the PHP application, import server/schema.sql and add a test account whose phone number you own.
  3. Set DB_DSN, DB_USER, DB_PASSWORD, TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_VERIFY_SERVICE_SID and a long random RATE_LIMIT_SECRET in the PHP process environment.
  4. 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.

View live demo ↓Download source ZIP ↓
mobile otp loginmysqlPHPsms otp login
Newer
Scrolling Text with a Close Button Using CSS and jQuery
Back to list
Older Calculate Total Price from Quantity with JavaScript and jQuery
Close
Categories
  • Blog
Recent Posts
  • Potted plant isolated on a transparent checkerboard in a photo editing workspace
    Remove a Background in Photoshop with Quick Action
    October 9, 2026 1 Comment
  • Five colorful CSS 3D social media icons with raised angled tiles
    3D Social Media Icons with CSS3
    October 9, 2026 1 Comment
  • Pure CSS tabs with four navigation controls above a content panel
    How to Create Pure CSS Tabs with HTML and CSS
    October 9, 2026 1 Comment
Recent Comments
    Facebook X-twitter Youtube Linkedin
    Copyright 2026 © SanWebCorner
    • Menu
    • Categories
    • Instagram profile
    • New Collection
    • Woman Dress
    • Contact Us
    • Latest News
    • Purchase Theme
    • Blog
    • Developer Tools
      • JSON Formatter
      • Base64 Encoder / Decoder
      • URL Encoder / Decoder
      • UUID Generator
      • Regex Tester
      • Unix Timestamp Converter
      • CSS Gradient Generator
      • Box Shadow Generator
      • Border Radius Generator
      • PX / REM Converter
      • CSS Clamp Generator
    • Compare
    Shop
    Sidebar