This tutorial implements phone number verification using the Twilio Verify API in PHP, covering sending a one-time code to a phone number and validating the code a user submits in your application. It targets PHP developers building registration flows, two-factor authentication, or account recovery features who want Twilio to manage code generation, delivery, expiry, and attempt limits. You will build a two-step PHP flow: send the OTP and check the OTP, with Twilio handling all the complexity behind the scenes.
Prerequisites and Setup
Install the packages with composer require twilio/sdk vlucas/phpdotenv and create a Verify Service in the Twilio Console under Verify, Services. Copy the Verify Service SID, which starts with VA, and add it to your .env file alongside your Account SID and Auth Token. Twilio Verify manages code generation, SMS delivery, a 10-minute expiry window, and a maximum of five verification attempts per code without any additional configuration. The Verify API is accessed through the Twilio client using the verify->v2->services($serviceSid) namespace chain.
composer require twilio/sdk vlucas/phpdotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_VERIFY_SERVICE_SID=VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The Complete Code
The send step calls verifications->create($phone, 'sms') on the Verify service, which triggers Twilio to generate and send the OTP code via SMS. The check step calls verificationChecks->create(['to' => $phone, 'code' => $code]) and reads the status property of the returned object, which is 'approved' on success and 'pending' on a wrong code. Catching a RestException with status code 60200 indicates an invalid or expired code, which should be returned as a user-readable error. Both operations use the same service SID so the verification context is consistent across the send and check steps.
<?php
require_once 'vendor/autoload.php';
use TwilioRestClient;
use TwilioExceptionsRestException;
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
$client = new Client($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
$serviceSid = $_ENV['TWILIO_VERIFY_SERVICE_SID'];
function sendOtp(Client $client, string $serviceSid, string $phone): bool {
try {
$verification = $client->verify->v2->services($serviceSid)
->verifications->create($phone, 'sms');
echo 'OTP status: ' . $verification->status . PHP_EOL;
return true;
} catch (RestException $e) {
echo 'Send error ' . $e->getStatusCode() . ': ' . $e->getMessage() . PHP_EOL;
return false;
}
}
function checkOtp(Client $client, string $serviceSid, string $phone, string $code): bool {
try {
$check = $client->verify->v2->services($serviceSid)
->verificationChecks->create(['to' => $phone, 'code' => $code]);
return $check->status === 'approved';
} catch (RestException $e) {
if ($e->getStatusCode() === 60200) {
echo 'Invalid or expired code.' . PHP_EOL;
} else {
echo 'Check error ' . $e->getStatusCode() . ': ' . $e->getMessage() . PHP_EOL;
}
return false;
}
}
$phone = '+15551234567';
sendOtp($client, $serviceSid, $phone);
$code = readline('Enter the code you received: ');
if (checkOtp($client, $serviceSid, $phone, $code)) {
echo 'Phone verified successfully.' . PHP_EOL;
} else {
echo 'Verification failed.' . PHP_EOL;
}
Testing and Debugging
Run the script and enter the code sent to your phone to confirm the happy path works end to end without errors. Test the failure path by entering a wrong code and verifying the function returns false without throwing an unhandled exception. Status code 60203 means the maximum number of check attempts has been reached and the code is permanently invalid; the user must request a new one by calling sendOtp() again. Use Twilio's magic test phone numbers in the Console to run verify flows in automated tests without consuming SMS credits or sending real messages.
Taking It Further
Set the channel parameter to 'call' instead of 'sms' to deliver the OTP as an automated voice call for users who cannot receive SMS messages. Customize the code length (4 or 8 digits) and expiry window in the Verify Service settings in the Twilio Console without modifying any PHP code. Add a per-phone rate limit in your application layer using a cache like Redis to prevent OTP flooding, restricting requests to three sends per phone number per 15 minutes. For passwordless login, combine the OTP check with PHP session creation so a successful verification automatically authenticates the user and stores a session cookie.
Talk to Telphi Consulting about integrating Twilio Verify into your PHP authentication and registration system.
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.