Twilio is a great service. It allows you to send and receive automated calls and text messages for very reasonable prices. They also have a wonderful API that makes integration into your site or plugin a breeze.

Background

You are given a unique Account SID and Account Token for each phone number you use; you use this data to authenticate with the server. To send a request, you just put To, From, and Body URL attributes into a HTTP post. The easiest way to do this is probably using cURL (or create stream). The function below is all you need to send an SMS.

Code

Note that this function doesn’t do any error checking to make sure things are formatted correctly. I recommend using preg_replace() to strip [^0-9], and trimming then adding a +1 to the numbers.

function send_sms( $sid, $token, $to, $from, $body ) {
    // resource url & authentication
    $uri = 'https://api.twilio.com/2010-04-01/Accounts/' . $sid . '/SMS/Messages';
    $auth = $sid . ':' . $token;

    // post string (phone number format= +15554443333 ), case matters
    $fields = 
        '&To=' .  urlencode( $to ) . 
        '&From=' . urlencode( $from ) . 
        '&Body=' . urlencode( $body );

    // start cURL
    $res = curl_init();
    
    // set cURL options
    curl_setopt( $res, CURLOPT_URL, $uri );
    curl_setopt( $res, CURLOPT_POST, 3 ); // number of fields
    curl_setopt( $res, CURLOPT_POSTFIELDS, $fields );
    curl_setopt( $res, CURLOPT_USERPWD, $auth ); // authenticate
    curl_setopt( $res, CURLOPT_RETURNTRANSFER, true ); // don't echo
    
    // send cURL
    $result = curl_exec( $res );
    return $result;
}

This will return the whole XML response, which is helpful for debugging, but a bit clunky otherwise. If you’re looking for a cleaner, less informative check, just use curl_getinfo() to get the header code. Check if it’s a 200, and return false if it isn’t.

5 Thoughts on “Send a Twilio Text Message with PHP using cURL

  1. Thx for the tips… i was searching for free sms service … this gonna help me … thx again\

  2. You reference $userpwd but that isn’t defined. Did you mean $auth?

  3. Nice script! You might want to add curl_close( $res ); before the return, so the connection doesn’t hang after your done with it.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation