Back to Blog
Language How-Tos

How to Build an SMS Auto-Reply Bot in Twilio Using PHP

Build a PHP SMS bot that reads inbound message keywords and returns contextual TwiML responses using the Twilio PHP SDK.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
PHP
How-To
Code
How to Build an SMS Auto-Reply Bot in Twilio Using PHP

This tutorial builds a keyword-driven SMS auto-reply bot in PHP using Twilio's TwiML MessagingResponse that responds to inbound messages based on the words they contain. It targets PHP developers who need to automate responses to common customer questions such as store hours, pricing, or support contacts without a human agent. You will build a single PHP webhook with a configurable keyword-to-response array and a sensible fallback for messages that match no known keyword.

Prerequisites and Setup

Install the Twilio SDK with composer require twilio/sdk and configure your Twilio number's SMS webhook to POST to your bot PHP script. The bot uses a plain PHP associative array to map lowercase keyword strings to response text, keeping routing logic separate from message content so responses can be updated without changing the matching algorithm. Expose your server with ngrok during development and replace the URL in the Twilio Console once you deploy to a stable host. The keyword matching uses PHP's str_contains() function (PHP 8.0+) or strpos() for earlier versions to check whether a keyword appears anywhere in the normalised body.

composer require twilio/sdk

# Twilio Console: SMS webhook
# https://xxxx.ngrok.io/bot.php (POST)

The Complete Code

The script normalises the incoming body to lowercase and strips whitespace with strtolower(trim()) before iterating the responses array with foreach and breaking on the first match. Using str_contains() for keyword matching means the keyword can appear anywhere in a longer message rather than requiring an exact match. A $matched boolean flag controls whether the fallback message is sent at the end of the loop. The MessagingResponse helper builds valid TwiML XML so there is no risk of malformed XML from manual string construction.

<?php
require_once 'vendor/autoload.php';

use TwilioTwiMLMessagingResponse;

$responses = [
    'hours'    => 'We are open Mon-Fri 9am-6pm ET and Saturday 10am-4pm ET.',
    'price'    => 'Our plans start at $29/month. Reply PLANS for a full breakdown.',
    'plans'    => 'Starter $29/mo, Professional $79/mo, Enterprise custom. Reply TALK for a demo.',
    'support'  => 'For support email support@telphi.com or reply TALK to speak with us.',
    'talk'     => 'A sales rep will call you within 1 business hour. Reply with your name.',
    'location' => 'We serve clients nationwide. Our HQ is in New York, NY.',
];

$fallback = 'Thanks for your message! Reply HOURS, PRICE, PLANS, SUPPORT, or TALK ' .
            'for instant answers, or a team member will follow up shortly.';

$body    = strtolower(trim($_POST['Body'] ?? ''));
$twiml   = new MessagingResponse();
$matched = false;

foreach ($responses as $keyword => $reply) {
    if (str_contains($body, $keyword)) {
        $twiml->message($reply);
        $matched = true;
        break;
    }
}

if (!$matched) {
    $twiml->message($fallback);
}

header('Content-Type: text/xml');
echo $twiml;

Testing and Debugging

Send each keyword from a test phone and confirm the bot returns the matching response for each one. Test the fallback by sending a message with no matching keywords such as "hello" and verify the fallback text is returned. Check the PHP error log via tail -f /var/log/php_errors.log for any exceptions that are preventing the TwiML response from being sent. If the bot responds with a PHP error page instead of TwiML, add ini_set('display_errors', 0) at the top of the script so PHP errors go to the log rather than contaminating the TwiML response body.

Taking It Further

Load keyword-response pairs from a database table so non-technical staff can update bot responses through a simple admin UI without modifying PHP code. Add a conversation state table that stores the last keyword matched per phone number so the bot can ask a follow-up question on the next message. Implement a catch-all LLM integration using the Anthropic or OpenAI API as a fallback for messages that match no keyword, so the bot can answer arbitrary questions using your product documentation as context. Log every inbound message and matched keyword to a database for analytics on which topics receive the most questions from customers.

Contact Telphi Consulting to build a production PHP SMS bot with NLP integration, conversation tracking, and CRM synchronisation.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.