phpguzzle.org
enrudees
Twilio – Docs

Send SMS with Twilio in PHP: SDK, Delivery Status and Segments

How do you send an SMS from PHP with Twilio? Install the official twilio/sdk package, create a client with your Account SID and Auth Token, and call $client->messages->create() with the recipient, the sender and the text. Two calls get the first message out: create the client, then send.

The trouble starts after that. The message is gone but status says queued, an unregistered US number gets every message blocked with 30034, one curly apostrophe doubles the bill, and a bulk loop dies on the first exception.

Installing the SDK, getting credentials and checking the environment are covered in the Twilio PHP SDK setup guide. From here on, composer require twilio/sdk has already run and TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN are in the environment. composer show twilio/sdk prints the installed version, and the source and release notes live in the twilio/twilio-php repository.

Sending the first message

require __DIR__ . '/vendor/autoload.php';

use Twilio\Rest\Client;

$client = new Client(getenv('TWILIO_ACCOUNT_SID'), getenv('TWILIO_AUTH_TOKEN'));

$message = $client->messages->create(
    '+12125550148',                  // recipient, the first positional argument
    [
        'from' => '+14155550123',    // your Twilio number
        'body' => 'Your verification code is 4815',
    ]
);

echo $message->sid;      // SMxxxxxxxxxxxxxxxx: the webhook reports status against this SID
echo $message->status;   // queued: accepted into the queue, NOT delivered

The recipient goes first and is positional. Everything else goes into the array in the second argument. People mix this up all the time: they write create(['to' => ..., 'from' => ...]) with a single array and get a TypeError, because the first argument is declared as string.

Both numbers use E.164: a plus, the country code, then the number with no spaces or brackets. +12125550148, not (212) 555-0148 and not 212-555-0148. A US number copied from a signup form usually lacks the leading +1, and Twilio will not guess it.

At this point status is not delivery, only confirmation that Twilio took the message. With a plain from it is queued, and through a Messaging Service the first value is accepted. The final status (delivered, undelivered, failed) arrives later through statusCallback, covered below.

$message carries the other fields of the API response too, handy to store next to the order:

echo $message->to;          // +12125550148
echo $message->from;        // +14155550123
echo $message->price;       // null right after create(); later, for example, "-0.00750"
echo $message->errorCode;   // null while there is no error

price is not known when create() returns: Twilio fills it in after the message is sent, and not instantly. Read it later by fetching the resource again with $client->messages($sid)->fetch(). The status callback does not carry a price. This also answers the common question of how to get message data out of the SDK: it is all in the properties of $message, and there is no JSON to parse.

MMS and attachments

The same create() with mediaUrl sends the message as MMS:

$client->messages->create($to, [
    'from' => $from,
    'body' => 'Receipt for order #1024',
    'mediaUrl' => ['https://example.com/receipts/1024.png'],   // an array: up to ten files
]);

Twilio downloads the file from that URL itself, so the URL has to be public: a local path or a link behind a login will not work. The sending number needs MMS capability, which is shown next to each number in the console. Twilio delivers MMS only to the US, Canada and Australia. Everywhere else, according to its country guidelines, the message goes out as a plain SMS with a link to the file.

US numbers need a registered sender

This is the part that code alone does not solve. A message to a US mobile number from an ordinary ten-digit Twilio number (a 10DLC number) is blocked until the number belongs to an approved A2P 10DLC campaign. The error is 30034, and it applies to everyone who sends from an application, whatever the volume.

Registration has two steps in the console: a Brand (who you are) and a Campaign (what you send). A business registers with its tax ID. A developer without one can use the Sole Proprietor brand, which allows a single campaign and a single number. The number then has to sit in the Messaging Service linked to the campaign, otherwise it still counts as unregistered.

The other sender types have their own gates:

  • A toll-free number needs toll-free verification. Until it is approved, messages to the US and Canada fail with 30032.
  • A short code takes 6 to 10 weeks to provision.
  • An alphanumeric sender such as a brand name is not supported for US recipients at all.

Start the registration early: approval is not instant, and without it the code has nothing to send from.

A phone number or a Messaging Service

A single from is fine for development and the first test. In production the sender is almost always a Messaging Service, a named pool of numbers with its own logic:

$message = $client->messages->create(
    '+12125550148',
    [
        'messagingServiceSid' => 'MGxxxxxxxxxxxxxxxx',   // instead of from
        'body' => 'Order #1024 is packed and on its way',
    ]
);

One of the two parameters is enough: from or messagingServiceSid. You can pass both, in which case from has to be a number from that service’s pool, and the first status is queued instead of accepted. What the service adds over a single number: it spreads traffic across the pool, keeps the same number for the same recipient (Sticky Sender), handles opt-outs and picks a local number for the recipient’s country. For US traffic it is also where the A2P campaign is attached, so a 10DLC number ends up in a service anyway. The service is created once, in the console (Messaging > Services) or through the API, and the code only keeps its MGxxxx identifier.

Trial accounts: the usual reason nothing arrives

Most beginners trip here before any code is wrong. A Twilio trial account comes with tight restrictions:

  • You can send only to verified numbers, at most five per account. The number you signed up with is verified from the start.
  • Sending is limited to the country you signed up from, and for SMS the docs name verified US numbers only.
  • Sender: a shared Twilio trial number. You do not pass from on a trial, and you buy your own number after upgrading.
  • You cannot send your own text. body takes the name of one of Twilio’s templates, for example sms_order_confirmation.
  • The trial stops working after 30 days.
// On a trial the recipient is one of your verified US numbers, from is omitted,
// and body is the name of a Twilio template, not your own text.
$message = $client->messages->create('+12125550148', ['body' => 'sms_order_confirmation']);

A message to an unverified number is rejected with code 21608. A paid account whose primary compliance profile is not approved yet gets the same code. Catch the error and read it:

use Twilio\Exceptions\RestException;

try {
    $message = $client->messages->create($to, ['from' => $from, 'body' => $text]);
} catch (RestException $e) {
    // getCode() is the Twilio error code, not the HTTP status (that is getStatusCode())
    // 21608: the recipient is not verified (trial, or no approved compliance profile)
    // 21606: from cannot send SMS on this account
    error_log("Twilio {$e->getCode()} (HTTP {$e->getStatusCode()}): {$e->getMessage()}");
    throw $e;
}

getCode() returns the five-digit Twilio code and getStatusCode() the HTTP status. The Twilio code is what tells you what to fix. Catch a bare \Exception and print only getMessage(), and the most useful part is gone. Twilio lists every code in its error dictionary.

Length, segments and hidden characters

An SMS is not a string of any length. Plain English text is encoded as GSM-7, and 160 characters fit into one segment. A single character outside the GSM-7 alphabet switches the whole message to UCS-2, where a segment holds 70. Every segment is billed separately.

English text rarely needs such characters. They get in by accident: a curly apostrophe from a word processor, an em dash from a CMS, an ellipsis typed as one character, an emoji in a template.

$message = $client->messages->create($to, [
    'from' => $from,
    // \u{2019} is a curly apostrophe: one character moves the text to UCS-2
    'body' => "We\u{2019}re ready when you are. Your table for four is booked for 7:30 pm on Friday.",
]);

echo $message->numSegments;   // the string "2": 78 characters, over the 70 limit

With a straight apostrophe the same text is one segment. Through a Messaging Service the value in the create() response is "0": no sender is assigned yet, and the segment count appears later. What to do about it:

  • Turn on Smart Encoding in the Messaging Service (Content Settings). It replaces curly quotes, long dashes and similar characters with their GSM-7 twins. It does not touch emoji.
  • Keep emoji out of transactional messages.
  • Remember that a long message leaves 153 characters per segment in GSM-7 and 67 in UCS-2, because part of each segment carries the header that glues the parts together.
  • Characters such as {, }, [, ] and ~ are in GSM-7 but count as two.
// Without a Messaging Service, Smart Encoding can be turned on per message
$client->messages->create($to, ['from' => $from, 'body' => $text, 'smartEncoded' => true]);

Prices depend on the country and change, so see Twilio’s SMS pricing page. The logic is what matters: count segments, not messages.

Delivery status only comes through a webhook

messages->create() returns queued (or accepted with a Messaging Service), the state at the moment the request was taken. After that the message moves through sending and sent to delivered, or ends as undelivered or failed. The response to create() cannot contain the final status, because the carrier confirms delivery later.

To learn what happened, pass statusCallback, a URL Twilio sends a POST to on every status change:

$client->messages->create($to, [
    'from' => $from,
    'body' => $text,
    'statusCallback' => 'https://example.com/twilio/status',
]);

The handler behind that URL reads the status from the POST fields:

// POST from Twilio to statusCallback
$sid    = $_POST['MessageSid']    ?? '';
$status = $_POST['MessageStatus'] ?? '';   // sent, delivered, undelivered, failed
$error  = $_POST['ErrorCode']     ?? null; // error code when delivery did not happen

if ('delivered' === $status) {
    markDelivered($sid);
} elseif ('undelivered' === $status || 'failed' === $status) {
    markFailed($sid, $error);
}

http_response_code(204);   // Twilio does not need a response body

Two things about this endpoint. First, it is public and anyone can post fake statuses to it, so check the X-Twilio-Signature header before trusting MessageStatus. Twilio describes the check in its webhook security guide. Second, Twilio waits about 15 seconds for the response, so push anything slow (a sluggish database, notifications) to a queue instead of doing it in the handler.

Bulk sending without a naive loop

A classic Stack Overflow question: how to text many recipients without a foreach. The Messages API has no “send to all” call, every message is a separate create(). A plain loop is still a bad idea:

// Don't: the process is busy until the whole list is done,
// and the first exception stops the campaign halfway.
foreach ($recipients as $to) {
    $client->messages->create($to, ['messagingServiceSid' => $mg, 'body' => $text]);
}

Put each send on a queue and let the Messaging Service pool spread the load:

// Each send is its own background job. The Messaging Service pool smooths the flow,
// and the web process does not sit waiting on the network.
foreach ($recipients as $to) {
    dispatch(new SendSmsJob($to, $text));   // your framework's queue
}

Twilio does not reject the excess, it queues it. For US recipients the rate is set by your A2P 10DLC campaign. A message that waits in the queue for more than 10 hours fails with code 30001. A 429 Too Many Requests response means something else: too many concurrent API requests. Such a request was not processed, so retry it with a growing pause.

messages->create() has no idempotency key, so duplicates are yours to prevent. If a job crashes after the send but before it is marked as done, the retry sends the message again: the customer gets it twice and you pay twice. Build a deduplication key from your own domain (recipient plus template plus event) and check it before create(), not after.

To send at a set time, do not hold the job in memory until then. Twilio can schedule the message itself, through a Messaging Service:

$message = $client->messages->create($to, [
    'messagingServiceSid' => 'MGxxxxxxxxxxxxxxxx',
    'body' => $text,
    'scheduleType' => 'fixed',
    'sendAt' => new \DateTime('+1 hour'),  // no sooner than 15 minutes, no later than 35 days
]);

echo $message->status;   // scheduled

Twilio handles opt-outs on its side. When a recipient replies STOP or another standard keyword (STOPALL, UNSUBSCRIBE, CANCEL, END, QUIT, REVOKE, OPTOUT), Twilio marks that sender and recipient pair as unsubscribed and blocks further sends with code 21610 until START arrives. Carriers require this, and code cannot get around it. A Messaging Service adds Advanced Opt-Out: keywords, confirmation texts and languages are set in the console, and you do not need your own table of keywords.

So 21610 is not a send failure but a normal signal that the recipient left. Catch it separately from other errors and drop the number on your side, or every attempt will hit the same block.

Common pitfalls

The number is not in E.164. Code 21211, Invalid ‘To’. Usually the +1 is missing or the number still has brackets and dashes. Normalize numbers before sending. Lookup helps weed out the ones that cannot be valid.

The sender is not registered. Code 30034 for a 10DLC number outside an approved campaign, 30032 for an unverified toll-free number. Nothing in the request fixes either.

from is not usable. Code 21606: the sender cannot send SMS from this account. Among the causes: the number belongs to another account or subaccount, or test credentials are used with a live number.

The recipient opted out. Code 21610: STOP came in, and nothing goes out until START.

The region is off. Code 21408: sending to the recipient’s country is not allowed in the account settings. A new account can send only to its home country, the rest is enabled in the console under Messaging > Settings > Geo Permissions.

Waiting for delivered in the create() response. It is not there. The response has queued or accepted, and the final status comes through statusCallback.

Next steps

If you are sending verification codes, do not build your own OTP on top of plain SMS. The Verify API generates the code, limits attempts and expires it for you. To stop paying for messages to numbers that do not exist, validate them first with Lookup.

In development it helps to see exactly what went to Twilio and what came back. The quickest way is to log the caught RestException whole: the code, the HTTP status and the message give an exact picture faster than guessing from getMessage() alone.

Spotted something inaccurate on this page?

Report an error