This tutorial builds a custom one-time password system in PHP using Twilio SMS that gives you full control over code generation, storage, expiry, and verification without delegating those concerns entirely to the Twilio Verify API. It targets PHP developers who need custom OTP behaviour such as a non-standard code format, a specific expiry window, or tight integration with an existing session or database layer. You will generate a cryptographically secure six-digit code using PHP's random_int() function, store it with an expiry timestamp in the session, send it via Twilio, and verify it in a separate POST endpoint.
Prerequisites and Setup
Install the packages with composer require twilio/sdk vlucas/phpdotenv and configure your Twilio credentials in a .env file. The OTP store in this tutorial uses PHP sessions keyed by phone number; replace the session store with a database table or a Redis hash in production for persistence across server restarts and multi-instance deployments. Set the expiry window to 5 minutes and the maximum attempt count to 3 to balance usability with brute-force protection. Call session_start() at the top of every PHP file that reads or writes OTP session data.
composer require twilio/sdk vlucas/phpdotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
The Complete Code
PHP's random_int(0, 999999) generates a cryptographically secure integer that is zero-padded to six digits with str_pad() to prevent codes starting with zero from being shortened. The OTP session entry stores the code, a creation timestamp from time(), and a failed-attempt counter. The verify endpoint rejects codes older than 300 seconds by comparing time() against the stored timestamp, and locks the entry after three wrong guesses by checking the attempts counter before each verification attempt. Deleting the session key on successful verification ensures each code can only be used once.
<?php
// send-otp.php
session_start();
require_once 'vendor/autoload.php';
use TwilioRestClient;
use TwilioExceptionsRestException;
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
$phone = $_POST['phone'] ?? '';
if (!$phone) { http_response_code(400); echo json_encode(['error' => 'phone required']); exit; }
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$_SESSION['otp_' . $phone] = ['code' => $code, 'created' => time(), 'attempts' => 0];
$client = new Client($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
try {
$client->messages->create($phone, [
'from' => $_ENV['TWILIO_PHONE_NUMBER'],
'body' => 'Your Telphi code is ' . $code . '. Valid for 5 minutes.',
]);
echo json_encode(['message' => 'OTP sent']);
} catch (RestException $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
<?php
// verify-otp.php
session_start();
$phone = $_POST['phone'] ?? '';
$code = $_POST['code'] ?? '';
$key = 'otp_' . $phone;
$entry = $_SESSION[$key] ?? null;
if (!$entry) { http_response_code(404); echo json_encode(['error' => 'No OTP for this number']); exit; }
if ($entry['attempts'] >= 3) { http_response_code(429); echo json_encode(['error' => 'Too many attempts. Request a new code.']); exit; }
if (time() - $entry['created'] > 300) { unset($_SESSION[$key]); http_response_code(410); echo json_encode(['error' => 'Code expired.']); exit; }
if ($code !== $entry['code']) {
$_SESSION[$key]['attempts']++;
$remaining = 3 - $_SESSION[$key]['attempts'];
http_response_code(401);
echo json_encode(['error' => $remaining . ' attempt(s) remaining.']);
exit;
}
unset($_SESSION[$key]);
echo json_encode(['verified' => true]);
Testing and Debugging
POST to send-otp.php with a phone field in E.164 format and verify the SMS arrives within a few seconds with the six-digit code. POST to verify-otp.php with the correct phone and code to confirm the verified response. Test the wrong-code path three times to trigger the 429 lockout response and verify the session entry blocks further attempts. Wait 6 minutes after sending a code and confirm the 410 expired response fires when trying to use the old code, confirming the expiry logic works correctly.
Taking It Further
Replace the PHP session store with a PDO database table that has columns for phone, code hash, created timestamp, and attempts count, with a unique index on phone so each number can have only one active OTP at a time. Hash the OTP before storing with password_hash($code, PASSWORD_BCRYPT) and verify with password_verify() so the plaintext code is never stored in the database. Add a per-phone rate limit that blocks new OTP requests if the same number has requested more than three codes in the past 15 minutes, using a separate rate_limits table. Consider switching to the Twilio Verify API for built-in fraud monitoring and adaptive verification for high-traffic or high-risk applications.
Contact Telphi Consulting to design a secure PHP multi-factor authentication system using Twilio for your web application.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.