How To Use the Twilio API To Send an SMS Message

Judah Frangipane
Nov. 08 2013, 09:00AM EST

Businesses are taking advantage of the ubiquity of mobile devices and SMS. This tutorial describes how to send an SMS message to a phone with PHP. We will be using the Twilio API, which provides numerous communications services. For example, with Twilio you can make and receive phone calls through the browser, mobile or desktop, send and receive SMS and MMS messages, or handle short codes.

The first thing you need to do is setup a free trial account, including a phone number for use with this tutorial. You can do that here.

Next, you need to get your account ID and your authorization token. You can find them on the user account page.

Twilio provides a PHP library that makes it simple to work with SMS and MMS messages. You can download the library here.

The next step is to create the page that will send the SMS message. Create a file called SendSMS.php, and place the following code into it.

< ?php
/* Send an SMS using Twilio. */

$testing = $_REQUEST["testing"];

if ($testing) {
    echo "Testing<br>";
}

// Include the Twilio-PHP library from http://twilio.com/docs/libraries
// Once downloaded move it into the folder containing this file.
require "Services/Twilio.php";

// Set your AccountSid and AuthToken here.
// Each can be found at http://www.twilio.com/user/account
$AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";

// Your valid Twilio phone number
$fromNumber = "+14325551212";

// Create a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);

// Get the number and message we submitted
$toNumber = "+1" . $_REQUEST["number"];
$message = $_REQUEST["message"];

// If testing we only need to load the PHP page in the browser
if ($testing) {
    $fromNumber = "+14325551212";
    $toNumber = "+14325551212";
    $message = "This is a test. Time is " . date('h:i.s');
}

// Send SMS
// - $fromNumber is your Twilio number
// - $toNumber is any phone number
// - $message is the sms body
try {
    $sms = $client->account->messages->sendMessage($fromNumber, $toNumber, $message);

    // Display a confirmation message on the screen
    echo "An SMS message was sent to $toNumber";
}
catch (Exception $e) {
    echo "The message was not sent!<br><br>";
    // If you don't see the previous message
    // Check to see if your Twilio phone number is correct in the $fromNumber
    // Check to see if the number you are texting is verified (the $toNumber)
    // The $toNumber must be verified if you are using a trial Twilio account

    echo "From Number: " . $fromNumber." (must be your Twilio phone number)<br>";
    echo "To Number: " . $toNumber." (this must be a verified phone number if you are using a trial account)<br>";
    echo "Message: " . $message."<br>";
    echo "<br>";
}

Fill in your AccountSid, AccountToken, fromNumber (Twilio number) and toNumber (this is a verified number you must manually add to your Twilio account while using trial mode). Save this page to your local or remote server and view it in the browser. It should not work yet because you have not submitted a phone number or a message.

You can append “?testing=true” to the URL to test it with the values you entered earlier. Visit “SendSMS.php?testing=true” in your browser. If it is set up correctly, you should receive the test SMS message on your phone and a confirmation message in the browser. If not, check the error messages.

Next, we will create a form on the client side for users to enter a test message. Create an HTML page in the same directory and add the following code:

<FORM action="SendSMS.php" method="post" style="width: 250px; padding-left: 10px">
  <P>
     Phone Number (123-345-7890):<br> <INPUT type="text" name="phone" style="width: 100%"><BR>
     Message: <br><TextArea type="text" name="message" style="width: 100%"></TextArea><br><br>
     <BUTTON name="reset" type="reset">Reset</BUTTON>
     <BUTTON name="submit" value="submit" type="submit">Send</BUTTON>
  </P>
</FORM>

This adds a form with the phone number, message, reset and submit button elements.

With our HTML form we can submit the message to the SendSMS.php page. Open the HTML page in the browser and type in a phone number and a message and click Submit. In this case, type in a phone number you have validated with your Twilio account.

There are three required parameters when sending an SMS message: the to number, the from number and the body message.

In the from variable we place our phone number. Phone numbers must be preceded by the country code. Only phone numbers or short codes purchased from Twilio work here; you cannot (for example) spoof SMS messages from your own cell phone number.

In the to variable we place the phone we want to send a message to. If you are using a trial account it can only be sent to a number you’ve registered with your account. The destination phone number must be formatted with a ‘+’ and country code, such as +16175551212 (E.164 format). For ‘To’ numbers without a ‘+’, Twilio will use the same country code as the ‘From’ number. Twilio will also attempt to handle locally formatted numbers for that country code (for example, (415) 555-1212 for the United States and 07400123456 for Great Britain). If you are sending to a different country than the ‘From’ number, you must include a ‘+’ and the country code to ensure proper delivery.

In the body variable, set the text of the message you want to send, limited to 160 characters.

When sending the SMS, it’s a good idea to add a "try and catch" block to indicate the success of the call.


// Send SMS
// - $fromNumber is your Twilio number
// - $toNumber is any phone number
// - $message is the sms body
try {
    $sms = $client->account->messages->sendMessage($fromNumber, $toNumber, $message);

    // Display a confirmation message on the screen
    echo "An SMS message was sent to $toNumber";
}
catch (Exception $e) {
    echo "The message was not sent!<br><br>";

    // If you don't see the previous message
    // Check to see if your Twilio phone number is correct in the $fromNumber
    // Check to see if the number you are texting is verified (the $toNumber)
    // The $toNumber must be verified if you are using a trial Twilio account
    echo "From Number: " . $fromNumber." (must be your Twilio phone number)<br>";
    echo "To Number: " . $toNumber." (this must be a verified phone number if you are using a trial account)<br>";
    echo "Message: " . $message."<br>";
    echo "<br>";
}

If the call was successful, we can access the $sms object. It will contain the following information (formatted here as XML):


<TwilioResponse>
  <SMSMessage>
    <Sid>SMd6db4f277379325b1ef87fa5689987c3</Sid>
    <DateCreated>Mon, 02 Sep 2013 19:32:47 +0000</DateCreated>
    <DateUpdated>Mon, 02 Sep 2013 19:32:47 +0000</DateUpdated>
    <DateSent/>
    <AccountSid>AC15131765526083681147017778220886</AccountSid>
    <To>+14325553539</To>
    <From>+14325554655</From>
    <Body>test from example</Body>
    <Status>queued</Status>
    <Direction>outbound-api</Direction>
    <ApiVersion>2010-04-01</ApiVersion>
    <Price/>
    <PriceUnit>USD</PriceUnit>
    <Uri>/2010-04-01/Accounts/AC15131765526083681147017778220886/SMS/Messages/SMd6db4f277379325b1ef87fa5689987c3</Uri>
  </SMSMessage>
</TwilioResponse>

View the HTML page in the browser and send a test message. If everything worked correctly, you should receive a text message and see the message, “An SMS message was sent successfully” in your browser.

Twilio has many other functions, including the ability to make calls and receive calls from within the browser.

For more information, check out the many resources and libraries available on the main Twilio website.

More resources:
Documentation
Quickstart

Judah Frangipane

Comments

User HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.