How to Send Text Messages With Twilio

Recently I had a chance to work with the twilio API, and let me tell you; it’s quite confusing. Twilio is a service that allows you to send an SMS message with PHP, or other popular programming languages. They have a quick-start guide on GitHub that gives you a quick-start code sample. All of their samples work, unless there is an invalid phone number given. If there is, Twilio throws you an error such as: Fatal error: Uncaught exception ‘Services_Twilio_RestException’ with message. As such, you can’t simply parse the result the same as you would if the SMS send was successful. To properly account for this, and send text messages with twilio, you need to wrap your SMS send in the following code:

try {
    $message = $client->account->messages->create(array(
    "From" => $from,
    "To" => $to,
    "Body" => $text_message_content,
// if the sms is sent successfully, you can run code here

} catch (Services_Twilio_RestException $e) {
// if there is an error, you can run code here and also capture the message with the function below
    echo $e->getMessage();

Leave a Reply

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