Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Send an SMS with Twilio

See more Twilio Examples

Submit an SMS with the sender, recipient, and text as form fields. This example starts with Twilio test credentials and its successful test sender. Twilio simulates the submission without sending or billing for a message. Test credentials and test numbers.

For live SMS, use the live Account SID in the URL, authenticate with an API key SID and secret, and use an SMS-capable Twilio sender and a recipient in E.164 format. HTTP 201 creates the message. Save its SID to check delivery status later.

Twilio Messages API reference

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Http;
use Chilkat2\HttpRequest;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;

$success = false;

// Assumes Chilkat is unlocked. See Global Unlock Sample.
$http = new Http();
$http->RequireSslCertVerify = true;
$http->BasicAuth = true;
// Use the test Account SID and test Auth Token from the Twilio Console.
$accountSid = 'YOUR_TEST_ACCOUNT_SID';
$http->Login = $accountSid;
$http->Password = 'YOUR_TEST_AUTH_TOKEN';
$url = new StringBuilder();
$url->Append('https://api.twilio.com/2010-04-01/Accounts/');
$url->Append($accountSid);
$url->Append('/Messages.json');

// Add raw field values. Chilkat form-encodes them, including the + in a phone number.
$req = new HttpRequest();
$req->HttpVerb = 'POST';
$req->ContentType = 'application/x-www-form-urlencoded';
$req->AddParam('From', '+15005550006');
$req->AddParam('To', '+12025550123');
$req->AddParam('Body', 'Hello from Twilio!');

$resp = new HttpResponse();
$reply = new JsonObject();
try {
    $http->HttpReq($url->GetAsString(), $req, $resp);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
if ($resp->StatusCode == 0) {
    echo $http->LastErrorText, "\n";
    exit;
}

try {
    $reply->Load($resp->BodyStr);
    $parsed = true;
} catch (\Chilkat2\Exception $e) {
    $parsed = false;
}
if ((!$success) || ($resp->StatusCode != 201)) {
    echo 'HTTP ', $resp->StatusCode, "\n";
    if (($parsed) && ($reply->HasMember('code'))) {
        echo 'Twilio error ', $reply->IntOf('code'), ': ', $reply->StringOf('message'), "\n";
    }

    exit;
}

if (!$parsed) {
    echo "Expected a JSON response.\n";
    exit;
}

if (($reply->JsonTypeOf('sid') != 1) || ($reply->JsonTypeOf('status') != 1)) {
    echo "The create response is missing the message SID or status.\n";
    exit;
}

echo 'Message SID: ', $reply->StringOf('sid'), "\n";
echo 'Initial status: ', $reply->StringOf('status'), "\n";