How to Send 1000 (or more) Text Messages in PHP Without Timing Out

February 24, 2021
Written by
Reviewed by
Diane Phan
Twilion

How to Send 1000 (or more) Text Messages in PHP Without Timing Out

As of October 24, 2022, the Twilio Notify API is no longer for sale. Please refer to our Help Center Article for more information. 

PHP developers of all experiences are painfully aware that your script may not execute if it takes longer than 30 seconds to process. There’s nothing worse than failing to do proper testing and finding that your code doesn’t scale in production.

In a previous tutorial, I shared how you can calculate the script execution time of sending SMS messages. At the conclusion we discovered that each message takes about .33 seconds to send, meaning that PHP’s 30 second timeout will allow you to send 90 messages before failure.

So what do you do when you want to send more than 90 messages? What about 1000?

Unfortunately, if you want to send bulk SMS (or WhatsApp) messages using the standard Programmable Messaging API, it’s not going to scale in PHP. Great engineering practices would suggest that you break apart your requests and run batches asynchronously. However, Twilio engineering has provided another service specifically for bulk sending called Twilio Notify.

In this quick tutorial, we will learn how to send bulk SMS in PHP using Twilio Notify.

Set Up a New Project Folder

Even though this tutorial only requires one script to execute, we will need a folder to store the dependencies required to securely connect to the Twilio Notify API. We will be using Composer to include the Twilio SDK along with .env files to securely store the Twilio credentials.

In your command line create a new project folder where you normally keep your development files.

$ mkdir sms-bulk-send

Now that the project folder is created, a composer.json file will need to be created in order to store our dependencies.

$ composer init

When prompted to “define your dev dependencies (require-dev) interactively” type n for “No.”

Add the Twilio SDK

Now that Composer is installed, we’re ready to install the Twilio PHP SDK. Run the following in your command line:

$ composer require twilio/sdk

To send the SMS, we will need a PHP script to contain the code that communicates with the Twilio Notify service. In the sms-bulk-send folder, create a new file called send-bulk-sms.php.

Once the file has been created, require the vendor library and include the Twilio Rest Client to access the Twilio API.

<?php

require_once 'vendor/autoload.php';

use Twilio\Rest\Client;

The Twilio API requires that all requests are authenticated using your Account SID and Auth Token. Both of these credentials are available within your console. Copy and paste those credentials to a safe place on your computer.

In order to use them within the code, we will install the dotenv package so that the credentials aren’t actually visible within the code or accidentally committed to a public repository.

Run the following command to install the package:

$ composer require vlucas/phpdotenv

Now that the PHP dotenv package is installed, we can create two new variables ($account_sid and $auth_token) to include your Twilio credentials.

Create a new .env file in the project folder and define the following credentials with your values from the console:

TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=your_auth_token

Add the following code below the Twilio Rest Client requirement in the previous step:

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Your Account SID and Auth Token from https://www.twilio.com/console
$account_sid = $_ENV['TWILIO_ACCOUNT_SID'];
$auth_token = $_ENV['TWILIO_AUTH_TOKEN'];

This code loads the .env variables into the file and assigns your Twilio credentials to the $account_sid and $auth_token variables.

Create a New Notify Service

If you’ve sent an SMS with Twilio before, then you know that you normally include the Twilio phone number as the sender directly in the API request. Using Twilio Notify differs by attaching a Twilio phone number to a Messaging Service, which Notify uses to automatically select based on the notification channel.

We’ll walk through how to set that up.

Purchase a phone number

You will need a Twilio phone number to deliver the message. If you haven’t purchased one, log into your console and navigate to Phone Numbers > Manage > Buy a number.

Attach the phone number to Messaging Service

After your number has been purchased, it will need to be connected to a Messaging Service. Messaging Services are a way to bundle senders (phone numbers) with a predefined set of features and responses.

They are perfect if you have one endpoint that needs to provide the same response, but maybe different regions. With a message service, one API response could respond to all of your subscribers in different countries, with different numbers.

In the console, navigate to Messaging > Services. If you don't have a messaging service to use, create one by clicking on the blue Create Messaging Service button. When the prompt loads, input "Send Bulk SMS" as the Messaging Service Name. Click on the blue Create button once you're done.

Create Messaging Service prompt

Once the service is created, you will be redirected to the Sender Pool. This option allows you to add your phone number as a sender. Follow the prompts by clicking on the Add Senders button.

Assign the Messaging Service to a Notify Service

Next, the Messaging service will need to be assigned to a Notify Service.

Twilio Notify is a service that makes it possible to reach one customer or a million on their preferred channel with just one API call. The key for our use case is that because it’s one API call, the likelihood of it completing within 30 seconds is drastically higher.

Notify Services also allow you to segment your data based on use-case. You could essentially segment your Messaging Services based on environment (dev, staging, prod) by assigning them to different Notify Services.

Navigate to Notify > Services from the Twilio Console and click the red and white plus sign to create a new Notify Service. Let's name it "Bulk Notification." Click on the red Create button to move on.

New Service prompt

Once redirected to the configuration page, assign the Messaging Service SID via the dropdown and click Save.

Notify Service configuration

After you have defined the Notify Service an SID will be generated for you. Create a new variable in your .env file called TWILIO_NOTIFY_SID and assign the value provided on the dashboard.

TWILIO_NOTIFY_SID=ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Return to the send-bulk-sms.php file and create a new variable called $notify_sid. We will dynamically assign the variable through dotenv.

$notify_sid = $_ENV['TWILIO_NOTIFY_SID'];

Now that the dotenv variables have been defined, we will initialize a new Twilio Rest Client and define a variable to record the current time. Copy and paste the following code below the Twilio credentials previously defined.

// Initialize the client
$client = new Client($account_sid, $auth_token);

$start_time = microtime(true);

NOTE: We are also tracking the start time as in the previous post to prove the speed of the Notify Service.

Now declare an array containing key-value pairs of toBinding and body.

toBinding accepts a JSON object containing the binding_type which in our case is sms and the addresswhich is the subscriber's phone number in E.164 format. The following code will show you how to assign multiple recipients.

// Define the list of subscribers
$subscribers = [
   json_encode(['binding_type' => "sms", 'address' => "+1651000000000"]),
   json_encode(['binding_type' => "sms", 'address' => "+1651000000000"])
];

$request_data = [
   "toBinding" => $subscribers,
   'body' => "Knok-Knok! This is your first Notify SMS"
];

Lastly, insert the array into the Notify API request to prepare your message to be sent.

// Create a notification
$notification = $client
   ->notify->services($notify_sid)
   ->notifications->create($request_data);

echo $notification->body; // => Knok-Knok! This is your first Notify SMS

At the end of the script we will record the execution time for the Notify request using the following variable:

$end_time = microtime(true);
$execution_time = ($end_time - $start_time);

echo " Execution time: " . $execution_time . " seconds";

Measure the Script Execution Time

It’s time to test your script by running the script in your command line:

$ php send-bulk-sms.php

As with the previous tutorial, I would recommend running this and recording the results at least three times.

It's important to note that even though the request is complete, the delivery time will still run according to the type of sender used. For instance, if you're using a 10-digit or long code phone number, the delivery time is 1 message per second.

Knok-Knok! This is your first Notify SMS
Execution time: 0.96540904045105 seconds

How long did it take to send? For me it was an average of .97 seconds!

In the case of this tutorial, sending 1,000 SMS with a long code number will take 16 minutes, but the request itself has completed in under 1 second! This means that your request will almost be seamless in the user experience.

Conclusion

With this knowledge in hand, you can now make more informed decisions about building your communications-based app. It's even possible to increase the execution time by off loading this script via an AJAX request.

I would recommend taking a look at the docs to see how you can extend this with Facebook Messenger or Push with saved subscribers in a database.

Marcus Battle is a Senior Manager of Developer Voices at Twilio where he prompts and rallies developers to build the future of communications. He can be reached via: