# Receive and Reply to Incoming Messages - PHP

In this guide, we'll walk through how to use [Programmable Messaging](https://www.twilio.com/en-us/messaging/channels/sms) 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](/docs/glossary/what-is-a-webhook)** you create in PHP from which you can send a reply back using **[TwiML](/docs/glossary/what-is-twilio-markup-language-twiml)**. This guide will help you master those basics in no time.

> \[!NOTE]
>
> 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](/docs/usage/webhooks/getting-started-twilio-webhooks). Find other webhook pages, such as a [security guide](/docs/usage/webhooks/webhooks-security) and an [FAQ](/docs/usage/webhooks/webhooks-faq) in the [Webhooks](/docs/usage/webhooks) section of the docs.

The code snippets in this guide are written using [PHP version 7.1](https://php.net/supported-versions.php), assume a [local](https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04) [web server](https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-ubuntu-18-04) [exists](https://php.net/manual/en/features.commandline.webserver.php), and make use of the [Twilio PHP SDK](https://github.com/twilio/twilio-php).

Let's get started!

![PHP elephant, mobile phone with heart, and Twilio logo.](https://docs-resources.prod.twilio.com/ccb7b095f67396501f73c594a546e7f88fb1447fad823e66c55bf428e531ec17.png)

## Creating your webhook

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 SDK, you'll want to [do that now](https://github.com/twilio/twilio-php).

Respond to an incoming text message

```php
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once 'vendor/autoload.php'; // Loads the library
use Twilio\TwiML\MessagingResponse;

$response = new MessagingResponse();
$response->message("The Robots are coming! Head for the hills!");
print $response;
```

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

![Diagram showing SMS flow from phone to app via Twilio with HTTP requests and responses.](https://docs-resources.prod.twilio.com/c15f2bf86138c03fe2b76b46fa25e1dba9bef1bd079c95b3b0cb8bb6ebfb847c.png)

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](https://www.google.com/#q=cloud+web+hosting)), but for learning or testing purposes, it's reasonable to use a tool such as [ngrok](https://ngrok.com/) to create a temporary public URL for our local web server.

![Ngrok forwarding URL http://92832de0.ngrok.io to localhost:80.](https://docs-resources.prod.twilio.com/22fabf6fc087afa9dc021202faf9179c3f9b4ef2efb41f38e64c1f932d89c6bb.png)

### Configure your Twilio number

Now that we have a URL for our code, we want to add that to the configuration of a [Twilio number we own](https://help.twilio.com/hc/en-us/articles/223135247-How-to-Search-for-and-Buy-a-Twilio-Phone-Number-from-Console):

1. Log into Twilio.com and go to the [Console's Numbers page](/console/phone-numbers/incoming)
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:

![Messaging configuration with webhook URL set to https://yourserver.com/sms.](https://docs-resources.prod.twilio.com/f25966b33e960a4214a186c1dbdd0d35aff94f3b3c704f7db85ba8a082ec20d2.png)

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.

#### Backup webhook 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](/docs/usage/security/availability-reliability) for more details on the fallback URL.

> \[!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](/docs/usage/security#http-authentication).

## Respond with media message

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](/docs/messaging/twiml/message) for more info.

> \[!WARNING]
>
> MMS messages can only be sent and received by numbers which have MMS capability. You can [check the capabilities](https://www.twilio.com/console/phone-numbers/search) of numbers in the account portal or query the [Available Phone Numbers](/docs/phone-numbers/api/availablephonenumber-resource) resource to search for Twilio numbers that are MMS enabled.

Generate a TwiML Message with Image

```php
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once 'vendor/autoload.php'; // Loads the library
use Twilio\TwiML\MessagingResponse;

$response = new MessagingResponse;
$message = $response->message("");
$message->body("The Robots are coming! Head for the hills!");
$message->media("https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg");
print $response;
```

## Custom responses to incoming media messages

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

```php
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once 'vendor/autoload.php'; // Loads the library
use Twilio\TwiML\MessagingResponse;

$response = new MessagingResponse;
$body = $_REQUEST['Body'];
$default = "I just wanna tell you how I'm feeling - Gotta make you understand";
$options = [
  "give you up",
  "let you down",
  "run around and desert you",
  "make you cry",
  "say goodbye",
  "tell a lie, and hurt you"
  ];

if (strtolower($body) == 'never gonna') {
    $response->message($options[array_rand($options)]);
} else {
    $response->message($default);
}
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

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

```php
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once 'vendor/autoload.php'; // Loads the library
use Twilio\TwiML\MessagingResponse;

$response = new MessagingResponse();
print $response;
```

## Enhance messages with Twilio Marketplace Add-ons

Need more information about the phone number that sent the message? Need to analyze the message itself for sentiment or other data? Add-ons are available in the [Twilio Marketplace](https://twilio.com/console/add-ons) to accomplish these tasks and more.

To learn how to enable [Add-ons for your incoming SMS messages](https://console.twilio.com/us1/develop/add-ons/catalog?products=programmable_messaging), refer to our [Add-ons tutorial](/docs/marketplace/listings/tutorial).	To learn how to enable [Add-ons for your incoming SMS messages](https://console.twilio.com/us1/develop/add-ons/catalog?products=programmable_messaging), see the [How to Use Twilio Marketplace Add-on Listings guide](/docs/marketplace/listings/usage#add-on-listings).

![Flowchart of SMS to app communication via Twilio with third-party services.](https://docs-resources.prod.twilio.com/2e7432cda6965a10a0fa9c7c5eecddb3b67dc073dde8b9ad03e92d1ac3c8b9fe.png)

## Where to next?

Ready to dig deeper into handling incoming messages? Check out our guide on how to [Create an SMS Conversation](/docs/messaging/tutorials/how-to-create-sms-conversations/php) and our [Automated Survey](https://www.twilio.com/blog/server-notifications-php-laravel) tutorial.
