SMS Integration with Twilio in PHP

What is Twilio?

Twilio is a cloud company that allows developers to integrate voice calls and text messaging into their applications.  You can make and receive phone calls, send and receive text messages by using their API platform.   Their services are used by the likes of Wal-Mart, Uber, eBay, and Airbnb.

Creating an Account

When you're ready to test drive the service, sign up at Try Twilio.  You can start with a free trial account and upgrade your account later.

You'll receive an account ID and an authentication token which are required to make API calls.

Installation

You can install the Twilio SDK using Composer:

composer require twilio/sdk
Using version ^4.10 for twilio/sdk
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing twilio/sdk (4.10.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Sending a Text Message

The following code creates a class that implements SMS message delivery using the Services_Twilio class.  

For trial accounts, the From number is provided by Twilio and the To number must be verified for your account.

require 'vendor/autoload.php';

class SMS
{
    private $client;
    
    public function __construct()
    {
        $account_sid = 'Twilio Account SID';
        $auth_token = 'Twilio Account Authentication Token';
        $this->client = new Services_Twilio($account_sid, $auth_token);
    }

    public function send($from,$to,$message)
    {
        $response = false;

        try
        {
            $message = $this->client->account->messages->create(array(
            "From" => $from,
            "To" => $to,
            "Body" => $message
        ));

            $response = true;
        }
        catch (Services_Twilio_RestException $e)
        {
            echo $e->getMessage();
        }
        
        return $response;
    }
}

$sms = new SMS;

$from = 'XXX-XXX-XXXX';
$to = 'XXX-XXX-XXXX';
$message = 'Test SMS';

if ($sms->send($from, $to, $message))
{
    // Success actions 
}
else
{
    // Error actions
}


Receiving a Text Message

Twilio uses a webhook to notify you of incoming SMS messages.  This is an HTTP request Twilio makes to the Request URL you define in your account settings.  This URL would typically be the part of your web app that handles messaging actions. 

 

When one of your Twilio numbers receives a text message, the service will make an HTTP request to your configured URL and expects to receive a TwiML response back.   TwiML (Twilio Markup Language) is a set of instructions issued to the service on what actions to perform.

You can construct a TwiML response by using the Services_Twilio_Twiml class.   Here's an example that sends back a thank you message.

require 'vendor/autoload.php';

$response = new Services_Twilio_Twiml();
$response->sms("Thank you for signing up!");

echo $response;