Avoid Sending SMS to Landlines in PHP with Twilio's Lookup v2 API
Time to read:
Avoid Sending SMS to Landlines in PHP with Twilio's Lookup v2 API
SMS is one of the most effective ways of staying in touch with your customers. This is because (among other reasons) it's notreliant on an internet connection, works on every mobile phone, and has an open rate of 98%.
But, when sending notifications via SMS in your PHP applications, how do you filter out landlines so that you don't pay for failed SMS? The phone number alone doesn't provide that information.
So, in this tutorial you'll learn how to filter out landlines in PHP using the power of Twilio's Lookup v2 API.
How will the code work?
In essence, there's very little to it. The application will take an array of phone numbers and iterate over them. While iterating, each phone number's details will be retrieved using Twilio's Lookup v2 API. If it's a landline it will be skipped. Otherwise, it will be sent a short, fun, SMS. In addition, the application will log details of each phone number and if it was filtered or not, using Monolog.
Prerequisites
To follow along with this tutorial, you'll need the following:
- A Twilio account (whether free or paid). Create one now if you don't have one already.
- A Twilio phone number that can send SMS
- PHP 8.4 or above
- A phone number that can receive SMS and a landline number (preferrably, one that belongs to you or a friend)
- Your preferred text editor or IDE for writing PHP. I recommend Neovim and Visual Studio Code
Create the basic project structure
You need to create the basic project file and directory structure, wherever you store your PHP projects. To do that, and change into the new project directory, run the following commands.
Add the required libraries
Next, the project will need a few dependencies, these are:
- Monolog: Twilio's de facto logging library
- Twilio's PHP Helper Library: This simplifies interacting with Twilio's APIs
- PHP Dotenv: This loads environment variables from .env files to PHP's
$_ENVand$_SERVERsuperglobals. Note: it's ideal for development environments, but shouldn't be used in production.
To install them, run the following command.
Add an autoloader namespace
With a composer.json file created by the previous command, you next need to add a PSR-4 autoload mapping. This is required to store the code that filters landlines (and any other number that isn't a mobile/cell number) in a reusable class. It could be included directly in the main code, but that would make that code a little hard to read.
Add a mapping named App which maps to the src directory, by adding the following at the end of the existing configuration in composer.json.
Then, run the following command to update Composer's auto-generated autoloader.
Set the required environment variables
Next, set two environment variables (your Twilio credentials), which are required to make authenticated requests to Twilio. To do that, in the project's top-level directory, create a new file named .env and paste the configuration below into the new file.
Then, open the Twilio Console in your browser of choice, and copy the Account SID, Auth Token from the Workbench at the bottom of the page.
Now, set the copied values as the values of TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively, in .env.
Then, under Quick actions click Phone numbers, and copy an E.164-formatted phone number from the Phone Number column. Paste the phone number as the value of , and TWILIO_PHONE_NUMBER in .env.
Write the PHP code
Now, it's time to write the PHP code. The code will be split across two files: index.php and src/Iterator/MobilePhoneNumberFilterIterator.php. Starting with the latter, create a new file in src/Iterators named MobilePhoneNumberFilterIterator.php, and paste the code below into the file.
The class extends FilterIterator from the Standard PHP Library (SPL). Iterators simplify traversing over objects using PHP's standard looping constructs, e.g., for, foreach, and while. FilterIterator, as the name implies, filters out unwanted values from an iterator, as they're iterated over through the logic in the class' accept() function.
The version above fetches details of each phone number, including Line Type Intelligence data as it provides the line's type, e.g., landline, mobile, and fixed VoIP. If the number's line type is set to "mobile" the function returns true, keeping the number. Otherwise, false is returned, filtering out the number.
Next, create the application's entrypoint, index.php, in the project's top-level directory, and paste the code below into the file.
Then, replace <A MOBILE PHONE NUMBER> with a valid mobile/cell phone number, and <A LAND LINE NUMBER> with a landline number.
The code loads Composer's autoload file ( vendor/autoload.php) and registers several variables:
- An array of phone numbers. This is the list of phone numbers to filter and send SMS to.
- Your Twilio phone number. This tells Twilio which number to send the SMS from
- A Twilio (Rest) Client object. This is the central object in Twilio's PHP helper library.
- A Monolog object. This simplifies instrumenting the application, letting us know which numbers were able to receive SMS and which weren't. It will log information to app.log in the project's top-level directory. However, feel free to change this location.
- A MobilePhoneNumberFilterIterator object. As previously discussed, this will filter landlines (and any phone number type other than mobiles) from a list of phone numbers. It's initialised with an ArrayIterator, itself initialised with an array of phone numbers to filter, and the Twilio
Clientobject.
Then, MobilePhoneNumberFilterIterator is iterated over, and an SMS is sent to any non-landline number returned.
Test that the code works as expected
With the code written and ready to run, it's time to see it in action. To do that, run the command below in a new terminal tab or session.
If successful, you should see output similar to the following written to the terminal's output.
That's how to avoid sending SMS to landlines in PHP with Twilio's Lookup v2 API
Thanks to Twilio's Lookup v2 API and PHP's standard library, it's almost trivial to filter landlines (and other phone number types) from a list of phone numbers. Make sure you use this functionality to avoid being charged for failed SMS when integrating with Twilio.
Where to from here?
If you'd like to know more about how you can use PHP with Twilio, check out the following tutorials:
- Make Phone Calls Using PHP and Twilio Programmable Voice
- Send an SMS With PHP in 30 Seconds
- Build An Interactive Voice Response System With PHP
Matthew Setter is the PHP, Go, and Rust editor on the Twilio Voices team, and a developer in each of these languages. He’s also the author of Mezzio Essentials and Deploy with Docker Compose. You can find him at msetter[at]twilio.com, and on LinkedIn and GitHub.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.