The ultimate guide to sending SMS using PHP and Twilio

September 16, 2024 • 7 min read

Home / Blog / The ultimate guide to sending SMS using PHP and Twilio
The ultimate guide to sending SMS using PHP and Twilio | Use it in a project, a package, or even a WordPress plugin

Introduction

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! 

 

Requirements

  • PHP 7.4+ installed
  • Composer as a dependency manager
  • A Twilio account
  • Have an approved A2P 10DLC Campaign if you're going to be texting US phone numbers (not required while in dev mode)

 

Getting started

 

1. Set Up the PHP Project

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.

 

2. Install the Twilio PHP SDK

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

 

3. Set Up Environment Variables

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

 

4. Code Sample: Send SMS Using the Twilio SDK

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;

 

5. Run the Script

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.

 

Scheduling SMS with PHP and Twilio

When it comes to scheduling SMS messages, there are two main approaches we can use:

  1. Check in PHP if the message is ready to be sent, and then trigger it – Useful if you want full control over scheduling and prefer to handle the timing within your PHP code.
  2. 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.

     

Option 1: Validating if a Message is Ready to be Sent Using PHP

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

  • This code fetches messages with their scheduled send times from a simulated database array, but you could have any sort of data structure, such as a JSON, a CSV, TXT or even XML file that contains your message list.
  • It compares the current time ($currentTime) with the scheduled time, and sends the SMS if the current time has passed.
  • This script could be set to run periodically via a cron job, say every minute, to check for messages ready to be sent.

 

Option 2: Scheduling Messages Using Twilio's Built-In Scheduling Features

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

  • The 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.
  • Twilio’s 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.

 

Conclusion

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

204
Twilio,  PHP

About the author

Author

Gonzalo Gomez

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.

Subscribe to my newsletter

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

Related posts

Laravel and Twilio: Cloud communications in a nutshell

April 05, 2024
IntroductionIn a previous chapter, I added a small guide with my tips on how to get your 10DLC phone number verified in Twilio, but I... Continue reading

Content rendering: Blade vs Vue and React

June 03, 2024
IntroductionThere are different approaches when it comes to showing data to the end user. Today, I'd like to talk about the 2 alternatives that I... Continue reading

Traits and Laravel: the practical guide

April 18, 2024
IntroductionTraits are a mechanism for code re-use in single inheritance languages such as PHP. They were designed to allow us developers to save logic and... Continue reading

Best practices for storing timestamps in Laravel

August 23, 2024
IntroductionWhen dealing with time-sensitive data in web applications, timestamps are crucial. They help track everything from user activity to system logs. However, the way we... Continue reading