Twilio SMS PHP Quickstart

In a few lines of code, your PHP application can send, receive, and reply text messages with Twilio Programmable SMS.

This PHP SMS Quickstart shows you how to use our Communications REST API, the Twilio PHP helper library, and ngrok to expose your local development server to Twilio.

In this Quickstart, you'll learn how to:

  1. Sign up for Twilio and purchase an SMS-enabled phone number
  2. Check and install any prerequisites
  3. Send your first SMS
  4. Set up your development environment to send and receive messages
  5. Receive inbound text messages
  6. Reply to incoming messages with a return SMS

Prefer to get started by watching a video? Check out our PHP SMS Quickstart video on Youtube.

Already have a Twilio account and SMS-capable number? Go ahead and skip this section.

Before you can send an SMS from PHP, sign up for a Twilio account or sign into your account and purchase an SMS-capable phone number.

If you don't currently own a Twilio phone number with SMS functionality, let's look at how to purchase one. 

  1. Navigate to the Buy a Number page
  2. Check the "SMS" box
  3. Click the red "Search" button

Buy a SMS-Capable Twilio Phone Number

You’ll then see available phone numbers with their capabilities listed. Find a number that suits your fancy, then click "Buy" and add it to your account.

Select an SMS-enabled phone number

Now that you have a Twilio account and a programmable phone number, it's time to write some code! To make things simpler, we'll install Twilio's official PHP helper library before we begin in earnest.

If you already have PHP and the Twilio PHP Helper Library installed in your working directory, feel free to skip this step and move on to sending your first text message.

To send your first SMS, let's make sure you're set up with PHP and able to install Twilio's PHP Helper library. When doing web development in PHP, we strongly suggest using Composer for package management. This quickstart relies on Composer to install the PHP Helper library. You can find manual Twilio PHP installation instructions on the PHP Helper Library page.

Install PHP

If you’re using a Mac or *nix machine, you may have PHP already installed. In your favorite terminal, run:

php --version

If it is not installed, follow the PHP installation instructions.

If you're using a Windows machine, please follow the official PHP tutorial to install PHP.

While many versions of PHP 5.x and PHP 7.x will work for this quickstart, please pay attention to supported PHP releases. Always update un-supported versions when doing web development, as older versions will not receive security updates.

Install Composer

Composer is the de facto standard package manager for PHP web development. We strongly suggest installing Composer for this tutorial (and your other web development as well).

Install the Twilio PHP Helper Library

We need to install the Twilio PHP Helper Library in the directory where you will complete the quickstart. If you are using Composer, there are two ways to do this.

First, from a terminal, you can run the following command:

composer require twilio/sdk

Alternatively, you can create a file named composer.json. In that file, add:

{
    "require": {
        "twilio/sdk": "^5.0"
    }
}

Then run

composer install

And composer will grab the latest 5.x version of the Twilio PHP Helper Library.

Finally, for a non-composer installation follow the instructions here. You'll also need to change the code samples as they appear below as instructed on that page.

Send an outbound SMS with PHP

Now that we have PHP, Composer, and twilio-php installed, we can make a single API request and send an outbound text message from our Twilio phone number. Create and open a new file called send_sms.php and type or paste in this code sample.

Loading Code Samples...
Language
SDK Version:
  • 5.x
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$auth_token = 'your_auth_token';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]

// A Twilio number you own with SMS capabilities
$twilio_number = "+15017122661";

$client = new Client($account_sid, $auth_token);
$client->messages->create(
    // Where to send a text message (your cell phone?)
    '+15558675310',
    array(
        'from' => $twilio_number,
        'body' => 'I sent this message in under 10 minutes!'
    )
);
Edit your Account Sid, Auth Token, and change the Twilio Number to a SMS-capable Twilio phone number to send an SMS with PHP.
Send an SMS in PHP

Edit your Account Sid, Auth Token, and change the Twilio Number to a SMS-capable Twilio phone number to send an SMS with PHP.

Replace the placeholder Twilio credentials

Swap the placeholders in account_sid and auth_token with your personal Twilio credentials. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to substitute.

You can reveal your auth token by clicking on the eyeball icon:

Reveal Your Auth Token

Replace the values for account_sid and auth_token with your unique values.

Note: While it's easier to hardcode your credentials in a file for this quickstart, you should use environment variables to keep them secret in production. Check out how to set environment variables for more information, and see the code comments for an example of how to read them in PHP. This repo is also an excellent resource for dealing with environment variables.

Replace the twilio_number phone number

Earlier, you purchased an SMS-enabled phone number. Paste that number into the twilio_number variable using E.164 formatting:

[+][country code][phone number including area code]

Replace the 'To' number in the create() call

The first value in the call to create() is the outgoing phone number, currently set to +15558675310. This can be any phone number that can receive text messages, but you should use a number you control first to witness the magic! As above, use E.164 formatting for this number.

Save the file then run the script:

php send_sms.php

Boom! Assuming all the values are correct, you should already see the SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this guide to sending MMS to see how to do it.

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs.

Receive and reply to inbound SMS messages with PHP

When someone sends an SMS to your Twilio phone number, Twilio makes an HTTP request to your server asking for instructions on what to do next. For this Quickstart, we’ll reply to the sender with a note about how we're sending our SMS reply.

We'll again use the Twilio PHP Library, then use PHP's built-in development webserver in combination with ngrok to instruct Twilio how to handle the message. Create a new file reply_sms.php in the same directory as send_sms.php, open it, then copy and paste or type the following code.

(Note: if you do not use the same directory, please follow the PHP Helper Library install step above)

Loading Code Samples...
Language
SDK Version:
  • 5.x
<?php
require_once "vendor/autoload.php";
use Twilio\Twiml;

// Set the content-type to XML to send back TwiML from the PHP Helper Library
header("content-type: text/xml");

$response = new Twiml();
$response->message(
    "I'm using the Twilio PHP library to respond to this SMS!"
);

echo $response;
Demonstrates using the Twilio PHP Helper Library to receive an SMS and send one in reply from your application.
Receive and Reply to an SMS in PHP

Demonstrates using the Twilio PHP Helper Library to receive an SMS and send one in reply from your application.

Save the file, then start the PHP development server with:

php -S localhost:8000

In your favorite browser, open the URL http://localhost:8000/reply_sms.php.

If all went well, you should see XML in your browser with the message we'd like to reply with to all our inbound texts. And, yes, that's all the code you need - there are just a couple more steps before everything is wired up. Next, let's expose this endpoint to Twilio.

Allow Twilio to talk to your PHP application

Most Twilio services use webhooks to communicate with your application. For example, when Twilio receives an SMS it reaches out to a specific URL in your application and you respond with instructions on how to handle a response. The small piece of code in reply_sms.php is an example of one instruction you can use in response - but this sadly isn't accessible from the outside world, only in your local environment.

While there are many ways to make this code public (for example by deploying it to an external host), we recommend a tool called Ngrok. When you start Ngrok, it provides a unique URL on the ngrok.io domain and then forwards incoming requests to your local development environment.

The architecture simplifies to this:

How ngrok helps Twilio reach your local server

If you don’t already use Ngrok, visit the download page and install it for your platform.

If you're working on a Mac or Linux, you're all set after decompression. If you're on Windows, we have a guide on how to install and configure ngrok on Windows. For more info on ngrok, including some great tips and tricks, check out our this in-depth blog post.

Once downloaded and installed, open a new terminal tab or window (leave your development server running) and start Ngrok with this command:

./ngrok http 8000

You should see output similar to this:

Ngrok server terminal output

Copy your public URL from this output, paste it into your browser, and append reply_sms.php. You should see the same XML file from the previous step, except now you can access this externally.

Pretty cool, right? Now we only have to tell Twilio where to look.

Configure your Webhook URL

Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.

  1. Log into Twilio.com and go to the Console's Numbers page
  2. Click on your SMS-enabled phone number (the same one we sent messages with originally)
  3. Under the Messaging sub-section, make sure the default “CONFIGURE WITH” is set to "Webhooks/TwiML."
  4. In the “A MESSAGE COMES IN” section, select "Webhook" and paste in the ngrok URL followed with /reply_sms.php

Configure your SMS Webhook

Save your changes - you’re ready to go!

Test your application with a text

Now that everything is glued together, it's time to test.

Send a text message from your mobile phone to your Twilio phone number. You'll see a couple of things happen very quickly -

  1. An HTTP request will show up in your Ngrok console.
  2. Your PHP dev server will note a new connection
  3. Twilio will forward your response back as an SMS!

Where to next?

Now that you know the basics of sending and receiving SMS and MMS text messages with PHP, you might want to check out these resources.

We hope you enjoyed the quickstart, and definitely can't wait to see what you build!

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
SDK Version:
  • 5.x
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$auth_token = 'your_auth_token';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]

// A Twilio number you own with SMS capabilities
$twilio_number = "+15017122661";

$client = new Client($account_sid, $auth_token);
$client->messages->create(
    // Where to send a text message (your cell phone?)
    '+15558675310',
    array(
        'from' => $twilio_number,
        'body' => 'I sent this message in under 10 minutes!'
    )
);
SDK Version:
  • 5.x
<?php
require_once "vendor/autoload.php";
use Twilio\Twiml;

// Set the content-type to XML to send back TwiML from the PHP Helper Library
header("content-type: text/xml");

$response = new Twiml();
$response->message(
    "I'm using the Twilio PHP library to respond to this SMS!"
);

echo $response;