How to Validate Phone Numbers in PHP with the Twilio Lookup API - Twilio
Power modern communications. Build the next generation of voice and SMS applications.
Start building for free

How to Validate Phone Numbers in PHP with the Twilio Lookup API

Screen Shot 2016-03-21 at 3.00.30 PM

Twilio Lookup is a phonebook REST API that you can use to check whether a number exists, format international numbers to local standards, determine whether a phone can receive text messages, and even discover information about the carrier associated with that phone number.

In this post, we’re going to learn how to deal with valid and invalid numbers using the Twilio PHP library. Whether you need to look up customer numbers in your production Laravel app or just have a basic script you want to run to check numbers in a local database, this code should get you started with validating phone numbers.

Getting started

We’ll need a few things before we start building:

  • PHP – I am using version 5.5 for this post
  • Composer – This will help us manage our dependencies
  • The Twilio PHP Library – Open your terminal, navigate to the folder you want your code to live in and enter the following to install it with Composer:
composer require twilio/sdk:4.*

iDAQcmxBYn7TF204ZeIOPwciQV2Zn-HWiflo7X8xgRgTZ9hMq8Oqq2iUQ9y6ANSMbQ0BD8WsrgyCxbBRX779U0ObFGckOoJ6888N5jBDat2jZKcm4TzJqVsqAwbI4-MfyDY6Kuc9.png

Looking up valid phone numbers

Check out the Lookup page if you want to play around with the API and see what type of data a request will return. Try entering a phone number and take a look at the JSON response object.

lookup-number.gif

Here’s a quick code sample to do a basic phone number lookup. Create a file named lookup.php and add this code to it:

<?php
// Get the PHP helper library from twilio.com/docs/php/install
// Loads the library
require "vendor/autoload.php";

// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "{{account_sid}}";
$token = "{{ auth_token }}";
$client = new Lookups_Services_Twilio($sid, $token);

// Make a call to the Lookup API
$number = $client->phone_numbers->get("15108675309");

// Print the nationally formatted phone number
echo $number->national_format . "\r\n"; // => (510) 867-5309

Open up your terminal and navigate to the directory containing lookup.php and run this command:

php lookup.php

This basic functionality is free, but you can get more information by doing a carrier lookup. Carrier lookups are commonly used to determine if a number is capable of receiving SMS/MMS messages. These cost $0.005 but a free trial account has $20 in credit to play with.

Carrier lookups require an extra parameter.

<?php
// Get the PHP helper library from twilio.com/docs/php/install
// Loads the library
require "vendor/autoload.php";

// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "{{account_sid}}";
$token = "{{ auth_token }}";
$client = new Lookups_Services_Twilio($sid, $token);

// Perform a carrier Lookup using a US country code
$number = $client->phone_numbers->get("(510) 867-5309", array("CountryCode" => "US", "Type" => "carrier"));

// Log the carrier type and name
echo $number->carrier->type . "\r\n"; // => mobile
echo $number->carrier->name; // => Sprint Spectrum, L.P.

Looking up invalid phone numbers

In this “online phonebook” the phone numbers serve as a unique ID. When you try to look up a phone number that does not exist you will get a 404 response.

Head over to the Lookup homepage again to see this in action when you check a number that doesn’t exist:

ZixwNsMm7CVar6mxoRfvpPlv-XSUticVG5Pc3Lfv9Fk-JziTt0iJdzg6zG-pX_TZP3CqU_N2O64UdsFQNkBtsB4r84EDd98q2KVkWBCD14eIrNtoK2lRAOx8j7U3SN6EkEMBxK9s.png

Let’s create a function that takes a phone number, returns true if the number exists and false if it doesn’t. We’ll do this by trying to do a carrier lookup and checking to see if an exception was raised with a 404 error code.

Replace the code in lookup.php with the following:

<?php // Get the PHP helper library from twilio.com/docs/php/install // Loads the library require "vendor/autoload.php"; // A function that takes a phone number and // returns true if the number is valid and false otherwise. function isValidNumber($number) { // Your Account Sid and Auth Token from twilio.com/user/account $sid = "{{account_sid}}"; $token = "{{ auth_token }}"; $client = new Lookups_Services_Twilio($sid, $token); // Try performing a carrier lookup and return true if successful. try { $number = $client->phone_numbers->get($number, array("CountryCode" => "US", "Type" => "carrier"));
        $number->carrier->type; // Should throw an exception if the number doesn't exist.
        return true;
    } catch (Exception $e) {
        // If a 404 exception was encountered return false.
        if($e->getStatus() == 404) {
            return false;
        } else {
            throw $e;
        }
    }
}

if (isValidNumber("19999999999")) {
    echo "Phone number is valid";
} else {
    echo "Phone number is not valid";
}

Try running this code by using the following command in your terminal, and don’t forget to insert your Account SID and Auth Token:

php lookup.php

You now have a function you could use anywhere in your code for checking phone numbers.

Looking Ahead

So now you know how to use the REST API phone book that is Twilio Lookup. You can also check out other resources to learn how to use Lookup in other languages:

Feel free to reach out if you have any questions or comments or just want to show off the cool stuff you’ve built.

Sign up and start building
Not ready yet? Talk to an expert.