Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Receive and Reply to Incoming Messages - PHP


In this guide, we'll walk through how to use Programmable Messaging(link takes you to an external page) to respond to incoming messages in a PHP web application.

When someone sends a text message to a Twilio number, Twilio can call a webhook you create in PHP from which you can send a reply back using TwiML. This guide will help you master those basics in no time.

(information)

Info

Twilio can send your web application an HTTP request when certain events happen, such as an incoming text message to one of your Twilio phone numbers. These requests are called webhooks, or status callbacks. For more, check out our guide to Getting Started with Twilio Webhooks. Find other webhook pages, such as a security guide and an FAQ in the Webhooks section of the docs.

The code snippets in this guide are written using PHP version 7.1(link takes you to an external page), assume a local(link takes you to an external page) webserver(link takes you to an external page) exists(link takes you to an external page), and make use of the Twilio PHP SDK(link takes you to an external page).

Let's get started!

PHP Twilio Banner.

Creating your webhook

creating-your-webhook page anchor

Later we will configure a Twilio phone number to send an HTTP request to a URL that we specify every time someone sends that number a message. Before we set that up, let's create the PHP code that will handle receiving and replying to those messages.

We'll create a new PHP file replyToMessage.php to hold our code. If you haven't already installed the Twilio helper library, you'll want to do that now(link takes you to an external page).

Respond to an incoming text message

respond-to-an-incoming-text-message page anchor

When your Twilio phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server can reply with a text message using the Twilio helper library.

PHP

_10
<?php
_10
// Get the PHP helper library from https://twilio.com/docs/libraries/php
_10
_10
require_once 'vendor/autoload.php'; // Loads the library
_10
use Twilio\TwiML\MessagingResponse;
_10
_10
$response = new MessagingResponse();
_10
$response->message("The Robots are coming! Head for the hills!");
_10
print $response;

Here we're using the helper library to generate and send TwiML back to the Twilio API which will reply to incoming messages using those instructions.

Request/response flow of Twilio SMS.

Now we need a public URL where the Twilio API can send incoming requests.

For a real project we'll want to deploy our code on a web or cloud hosting provider (of which there are many(link takes you to an external page)), but for learning or testing purposes, it's reasonable to use a tool such as ngrok(link takes you to an external page) to create a temporary public URL for our local web server.

Ngrok URL.

Configure your Twilio number

configure-your-twilio-number page anchor

Now that we have a URL for our code, we want to add that to the configuration of a Twilio number we own(link takes you to an external page):

  1. Log into Twilio.com and go to the Console's Numbers page
  2. Click on the phone number we want to use for this project
  3. Find the Messaging section and the "A MESSAGE COMES IN" option
  4. Select "Webhook" and paste in the URL we want to use, being sure to include the relevant file name:
Configure SMS Webhook.

If we wanted our webhook to receive another type of request, like GET or PUT, we could specify that using the drop down to the right of our URL.

You'll notice in the console that there is also a spot to provide a Webhook URL for when the "PRIMARY HANDLER FAILS." Twilio will call this URL if your primary handler returns an error or does not return a response within 15 seconds. Refer to our Availability and Reliability guide for more details on the fallback URL.

(warning)

Warning

Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them.

Learn more about HTTP authentication and validating incoming requests here.


Respond with media message

respond-with-media-message page anchor

We can send a message with embedded media (e.g. an image) by using the media method to add an image URL to our message. We can send multiple images by adding more media calls with additional image URLs.

After updating the code, you may need to restart your local server. When you text the Twilio number you just set up with your webhook, you should get a reply back with the added image! Check out the API Reference for more info.

(warning)

Warning

MMS messages can only be sent and received by numbers which have MMS capability. You can check the capabilities(link takes you to an external page) of numbers in the account portal or query the Available Phone Numbers resource to search for Twilio numbers that are MMS enabled.

Generate a TwiML Message with Image

generate-a-twiml-message-with-image page anchor
PHP

_11
<?php
_11
// Get the PHP helper library from https://twilio.com/docs/libraries/php
_11
_11
require_once 'vendor/autoload.php'; // Loads the library
_11
use Twilio\TwiML\MessagingResponse;
_11
_11
$response = new MessagingResponse;
_11
$message = $response->message("");
_11
$message->body("The Robots are coming! Head for the hills!");
_11
$message->media("https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg");
_11
print $response;


Custom responses to incoming media messages

custom-responses-to-incoming-media-messages page anchor

We've sent text and image replies, but what if we want to choose our reply based on the message we received? No problem!

The content of the incoming message will be in the Body parameter of the incoming API request. Let's take a look at how we might use that to customize our response.

Generate a dynamic TwiML Message

generate-a-dynamic-twiml-message page anchor
PHP

_24
<?php
_24
// Get the PHP helper library from https://twilio.com/docs/libraries/php
_24
_24
require_once 'vendor/autoload.php'; // Loads the library
_24
use Twilio\TwiML\MessagingResponse;
_24
_24
$response = new MessagingResponse;
_24
$body = $_REQUEST['Body'];
_24
$default = "I just wanna tell you how I'm feeling - Gotta make you understand";
_24
$options = [
_24
"give you up",
_24
"let you down",
_24
"run around and desert you",
_24
"make you cry",
_24
"say goodbye",
_24
"tell a lie, and hurt you"
_24
];
_24
_24
if (strtolower($body) == 'never gonna') {
_24
$response->message($options[array_rand($options)]);
_24
} else {
_24
$response->message($default);
_24
}
_24
print $response;

Here we've created a default message and an array of options for replying to the specific incoming message "never gonna." If any messages come in other than "never gonna" then we send out our default message. When the incoming message is "never gonna" we'll pick one of our array of options at random. Once we've updated our code, we can try sending our Twilio number an SMS that says "never gonna" or anything else and should get the corresponding response.


Receive incoming messages without sending a reply

receive-incoming-messages-without-sending-a-reply page anchor

If you would like to receive incoming messages but not send an outgoing reply message, you can return an empty TwiML response. Twilio still expects to receive TwiML in response to its request to your server, but if the TwiML does not contain any directions, Twilio will accept the empty TwiML without taking any actions.

Receive an incoming message without sending a response

receive-an-incoming-message-without-sending-a-response page anchor
PHP

_10
<?php
_10
// Get the PHP helper library from https://twilio.com/docs/libraries/php
_10
_10
require_once 'vendor/autoload.php'; // Loads the library
_10
use Twilio\TwiML\MessagingResponse;
_10
_10
$response = new MessagingResponse();
_10
print $response;


Enhance messages with add-ons

enhance-messages-with-add-ons page anchor

Need more information about the phone number that sent the message? Need to analyze the SMS itself for sentiment or other data? Add-ons are available in the Add-ons Marketplace(link takes you to an external page) to accomplish these tasks and more.

To learn how to enable Add-ons for your incoming SMS messages, refer to our Add-ons quickstart.

Add-ons Diagram.

Ready to dig deeper into handling incoming messages? Check out our guide on how to Create an SMS Conversation and our Automated Survey(link takes you to an external page) tutorial.


Rate this page: