Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Validate and format a phone number with Twilio Lookup

See more Twilio Examples

Use Basic Lookup v2 to check a national-format number and obtain its E.164 and national display formats. Supply the two-letter country code for a national number. The example requests only the basic fields.

Read the boolean valid field even when the HTTP request succeeds. When it is false, display any validation_errors that Twilio supplies. Numbering-plan validation does not establish reachability or control of a phone. To confirm control, send an SMS verification code.

Twilio documentation

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;

$success = false;

// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Load an API key for the Twilio account from private application configuration.
$http = new Http();
$http->RequireSslCertVerify = true;
$http->BasicAuth = true;
$http->Login = 'YOUR_API_KEY_SID';
$http->Password = 'YOUR_API_KEY_SECRET';

// The phone number is one URL path segment. Percent-encode spaces and any leading +.
$number = new StringBuilder();
$number->Append('020 7946 0018');
try {
    $number->Encode('url_rfc3986', 'utf-8');
} catch (\Chilkat2\Exception $e) {
    echo "Could not encode the phone number.\n";
    exit;
}

$url = new StringBuilder();
$url->Append('https://lookups.twilio.com/v2/PhoneNumbers/');
$url->Append($number->GetAsString());
$url->Append('?CountryCode=GB');
$resp = new HttpResponse();
$reply = new JsonObject();

try {
    $http->HttpNoBody('GET', $url->GetAsString(), $resp);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
if ($resp->StatusCode == 0) {
    echo "No HTTP response from Twilio.\n";
    exit;
}

try {
    $reply->Load($resp->BodyStr);
    $parsed = true;
} catch (\Chilkat2\Exception $e) {
    $parsed = false;
}
if ((!$success) || ($resp->StatusCode != 200)) {
    echo 'Twilio returned HTTP ', $resp->StatusCode, "\n";
    if (($parsed) && ($reply->JsonTypeOf('code') == 2)) {
        echo 'Twilio error: ', $reply->IntOf('code'), '  ', $reply->StringOf('message'), "\n";
    }

    exit;
}

if (!$parsed) {
    echo "Expected a JSON response from Twilio.\n";
    exit;
}

if ($reply->JsonTypeOf('valid') != 5) {
    echo "The lookup response is missing the validity flag.\n";
    exit;
}

if (!$reply->BoolOf('valid')) {
    echo "The number is invalid for the specified country.\n";
    $i = 0;
    while ($i < $reply->SizeOfArray('validation_errors')) {
        $reply->I = $i;
        echo $reply->StringOf('validation_errors[i]'), "\n";
        $i = $i + 1;
    }

    exit;
}

if ($reply->JsonTypeOf('phone_number') != 1) {
    echo "The lookup response is missing the E.164 number.\n";
    exit;
}

echo 'E.164: ', $reply->StringOf('phone_number'), "\n";
echo 'National format: ', $reply->StringOf('national_format'), "\n";