September 16, 2024 • 7 min read
Going with PHP and Twilio to send SMS is a powerful combination. Whether you're looking to build a webapp, a webservice, or even a script that triggers when some action has happened in an external system, you save lots of overheads and delegate the heavylifting to an external SMS services provider, such as Twilio.
When building a platform with SMS capabilities, one of the biggest concerns are message scheduling. Requirements may be that the messages get sent instantly when the script is triggered, or perhaps you need to send a reminder SMS every morning at 9 AM, for example. We'll cover both scenarios in the examples below. Let's get started!
If you don’t have an existing PHP project, let's start by creating one. First, make sure you have PHP 7.4+ and Composer installed.
Open your terminal and follow these steps:
# Step 1: Create a project directory
mkdir php-twilio-sms
cd php-twilio-sms
# Step 2: Initialize a Composer project
composer init
You will be prompted to set up basic project details such as the package name and version. You can fill these out or leave the default values for now.
Next, we need to install the Twilio SDK via Composer. This SDK will help us interact with Twilio's API easily.
Add the Twilio's PHP SDK to your project and update your composer.json
file:
composer require twilio/sdk
Twilio requires authentication using your Account SID and Auth Token, which are provided when you create an account on Twilio. To keep things secure, let’s store these sensitive details in an .env
file.
Create a .env
file in your project directory:
touch .env
Then add your Twilio credentials to that file. Make sure to replace the placeholder values with your actual Twilio credentials.
TWILIO_ACCOUNT_SID=your_account_sid_here
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=your_twilio_phone_number_here
Now that we’ve set up the project, let’s write a simple PHP script to send an SMS. Create a new file called send-sms.php
:
<?php
// Load Composer's autoload file
require __DIR__ . '/vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
use Twilio\Rest\Client;
// Your Twilio credentials
$sid = $_ENV['TWILIO_ACCOUNT_SID'];
$token = $_ENV['TWILIO_AUTH_TOKEN'];
// Create a Twilio client
$client = new Client($sid, $token);
// Phone numbers
$from = $_ENV['TWILIO_PHONE_NUMBER']; // Your Twilio number
$to = '+1234567890'; // The recipient's phone number
// Send the SMS
$message = $client->messages->create(
$to,
[
'from' => $from,
'body' => 'Hello! This is a test message from Twilio using PHP.'
]
);
// Display the message SID to confirm it was sent
echo "Message SID: " . $message->sid;
To send the SMS, simply run the script in your terminal:
php send-sms.php
If everything is set up correctly, you should receive a success message in your terminal, along with the Message SID to confirm the SMS has been sent. The recipient will receive the text message shortly.
Now let's go through the different scheduling options that we can have.
When it comes to scheduling SMS messages, there are two main approaches we can use:
Use Twilio's built-in scheduling features – Let Twilio handle the scheduling by specifying the exact time the message should be sent, reducing overhead on your end.
This approach involves storing messages (and their send times) in your database, and periodically running a PHP script to check if the current time matches or exceeds the scheduled time. Let's check the following code:
<?php
// Database check (replace this with your database logic)
$scheduledMessages = [
[
'phone_number' => '+1234567890',
'message' => 'Reminder: Your appointment is tomorrow at 9AM.',
'scheduled_time' => '2024-09-18 09:00:00'
],
[
'phone_number' => '+0987654321',
'message' => 'Don’t forget to pick up your package!',
'scheduled_time' => '2024-09-18 15:30:00'
]
];
$currentTime = date('Y-m-d H:i:s');
foreach ($scheduledMessages as $sms) {
if ($currentTime >= $sms['scheduled_time']) {
// Send SMS if the current time has passed the scheduled time
sendSms($sms['phone_number'], $sms['message']);
}
}
// SMS sending function
function sendSms($to, $message)
{
// Include Twilio's PHP SDK
require_once 'vendor/autoload.php';
use Twilio\Rest\Client;
$sid = 'your_twilio_sid';
$token = 'your_twilio_auth_token';
$client = new Client($sid, $token);
$client->messages->create(
$to,
[
'from' => 'your_twilio_number',
'body' => $message
]
);
echo "SMS sent to $to\n";
}
What we're doing here
$currentTime
) with the scheduled time, and sends the SMS if the current time has passed.Twilio offers a feature that allows you to schedule messages on their end. This way, you just send the SMS request to Twilio with the desired send time, and they handle the rest.
Here’s how you can schedule a message using Twilio:
<?php
// Include Twilio's PHP SDK
require_once 'vendor/autoload.php';
use Twilio\Rest\Client;
// Twilio credentials
$sid = 'your_twilio_sid';
$token = 'your_twilio_auth_token';
$client = new Client($sid, $token);
// Schedule message details
$to = '+1234567890';
$message = 'Reminder: Your appointment is tomorrow at 9AM.';
$scheduleTime = (new DateTime('2024-09-18 09:00:00'))->format(DateTime::RFC3339);
// Send the scheduled SMS
$message = $client->messages->create(
$to,
[
'from' => 'your_twilio_number',
'body' => $message,
'scheduleType' => 'fixed', // Fixed scheduling
'sendAt' => $scheduleTime, // Time to send
'messagingServiceSid' => 'your_messaging_service_sid' // Messaging Service SID - can be found at Twilio´s console
]
);
echo "SMS scheduled to be sent at $scheduleTime to $to\n"; // you can return a specific value or store the $message data in your database
Let's walk through that code
scheduleType
is set to 'fixed'
, indicating that the message should be sent at a specific time.sendAt
is used to specify the exact time in RFC3339 format when Twilio should send the message.messagingServiceSid
can be used to define the service responsible for sending the message.This approach ensures the SMS will be sent at the exact time you schedule, without needing to run any periodic PHP scripts.
There are different ways to send SMS using PHP. Using a 3rd party service such as Twilio or Vonage can save us hours worth of work as they have internal mechanisms to help us achieve the desired results. Moving forward, you can also implement webhooks to have two-way communications in your platform in short time, thanks to all this heavy lifting that Twilio does for us. Then again, everything depends on the requirements of your project.
Liked the post? Feel free to share!
-Gonza
Sr. Software Engineer
I have over 6 years of experience building highly scalable web applications using a wide variety of technologies. Currently focusing on Laravel, Livewire, Vue.js and AWS as my go-to stack.
If you enjoy the content that I make, you can subscribe and receive insightful information through email. No spam is going to be sent, just updates about interesting posts or specialized content that I talk about.
Ready to take your project to the next level?
Contact me