PHP ActiveX Requires Chilkat v11.0.0+
PHP ActiveX
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.
Chilkat PHP ActiveX Downloads
<?php
$success = 0;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Load an API key for the Twilio account from private application configuration.
$http = new COM("Chilkat.Http");
$http->RequireSslCertVerify = 1;
$http->BasicAuth = 1;
$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 COM("Chilkat.StringBuilder");
$number->Append('020 7946 0018');
$encoded = $number->Encode('url_rfc3986','utf-8');
if ($encoded != 1) {
print 'Could not encode the phone number.' . "\n";
exit;
}
$url = new COM("Chilkat.StringBuilder");
$url->Append('https://lookups.twilio.com/v2/PhoneNumbers/');
$url->Append($number->getAsString());
$url->Append('?CountryCode=GB');
$resp = new COM("Chilkat.HttpResponse");
$reply = new COM("Chilkat.JsonObject");
$success = $http->HttpNoBody('GET',$url->getAsString(),$resp);
if ($resp->StatusCode == 0) {
print 'No HTTP response from Twilio.' . "\n";
exit;
}
$parsed = $reply->Load($resp->BodyStr);
if (($success != 1) or ($resp->StatusCode != 200)) {
print 'Twilio returned HTTP ' . $resp->StatusCode . "\n";
if (($parsed == 1) and ($reply->JsonTypeOf('code') == 2)) {
print 'Twilio error: ' . $reply->IntOf('code') . ' ' . $reply->stringOf('message') . "\n";
}
exit;
}
if ($parsed != 1) {
print 'Expected a JSON response from Twilio.' . "\n";
exit;
}
if ($reply->JsonTypeOf('valid') != 5) {
print 'The lookup response is missing the validity flag.' . "\n";
exit;
}
if ($reply->BoolOf('valid') != 1) {
print 'The number is invalid for the specified country.' . "\n";
$i = 0;
while (($i < $reply->SizeOfArray('validation_errors'))) {
$reply->I = $i;
print $reply->stringOf('validation_errors[i]') . "\n";
$i = $i + 1;
}
exit;
}
if ($reply->JsonTypeOf('phone_number') != 1) {
print 'The lookup response is missing the E.164 number.' . "\n";
exit;
}
print 'E.164: ' . $reply->stringOf('phone_number') . "\n";
print 'National format: ' . $reply->stringOf('national_format') . "\n";
?>