This tutorial builds a PHP webhook that detects STOP, UNSTOP, and HELP keyword replies in inbound Twilio SMS messages and responds with carrier-compliant TwiML while updating an opt-out store in your application's database. It targets PHP developers who need to track and respect opt-outs for TCPA and CTIA compliance without relying solely on Twilio's automatic handling. You will detect the keyword, update an opt-out table via PDO, and return the appropriate TwiML response for each keyword category.
Prerequisites and Setup
Install the Twilio SDK with composer require twilio/sdk and configure your Twilio number's inbound SMS webhook in the Console to POST to your PHP opt-out handler. Twilio handles STOP and UNSTOP automatically at the platform level before your webhook fires, but building your own handler gives you real-time visibility and lets you synchronise opt-outs to your own database for cross-channel suppression. The keyword matching must be case-insensitive and trim whitespace because users type these words with varying capitalisation and accidental trailing spaces. Your PHP script must return a valid TwiML response for every inbound message, even opt-out keywords, or Twilio will log a webhook delivery warning.
composer require twilio/sdk
# Twilio Console: set SMS webhook
# https://yourdomain.com/opt-out.php (POST)
The Complete Code
Normalising the body to uppercase with strtoupper(trim($_POST['Body'] ?? '')) before comparing against keyword arrays catches all user input variations without a regex. PHP's in_array() function provides a clean membership check against each keyword list. An in-memory array of opt-outs is used here for simplicity; replace the $optOutList operations with PDO INSERT and DELETE statements against a sms_opt_outs database table for persistent storage across requests. The helper function isOptedOut() at the bottom is what your outbound send logic should call before every messages->create() call.
<?php
require_once 'vendor/autoload.php';
use TwilioTwiMLMessagingResponse;
$stopKeywords = ['STOP', 'STOPALL', 'UNSUBSCRIBE', 'CANCEL', 'END', 'QUIT'];
$unstopKeywords = ['START', 'UNSTOP', 'YES'];
$helpKeywords = ['HELP', 'INFO'];
$from = $_POST['From'] ?? '';
$body = strtoupper(trim($_POST['Body'] ?? ''));
$response = new MessagingResponse();
if (in_array($body, $stopKeywords, true)) {
// PDO: INSERT INTO sms_opt_outs (phone) VALUES (?) ON DUPLICATE KEY UPDATE phone=phone
error_log('Opted out: ' . $from);
$response->message(
'You have been unsubscribed and will receive no further messages. ' .
'Reply START to resubscribe.'
);
} elseif (in_array($body, $unstopKeywords, true)) {
// PDO: DELETE FROM sms_opt_outs WHERE phone = ?
error_log('Re-subscribed: ' . $from);
$response->message(
'You are now resubscribed and will receive messages again. ' .
'Reply STOP at any time to unsubscribe.'
);
} elseif (in_array($body, $helpKeywords, true)) {
$response->message(
'For assistance contact support@telphi.com. Reply STOP to unsubscribe.'
);
} else {
$response->message('Thank you for your message. A team member will follow up shortly.');
}
header('Content-Type: text/xml');
echo $response;
Testing and Debugging
Send the word STOP from a test phone to your Twilio number and verify the PHP error log records the opt-out and the TwiML reply contains the unsubscribe confirmation. Send START immediately after and confirm the re-subscribe confirmation TwiML is returned. Test HELP and an unrecognised keyword to verify each branch of the conditional returns the correct response. Check the Twilio Console under Messaging Logs to view your TwiML responses alongside the inbound messages for a complete conversation audit view.
Taking It Further
Replace the commented PDO placeholders with a real database implementation using a sms_opt_outs table with columns for phone number, opt-out timestamp, and keyword used to give you a full compliance audit log. Add an isOptedOut() function that runs a SELECT against the opt-out table and call it at the start of every outbound send function before the Twilio API is invoked. Extend the keyword detection with strpos($body, 'REMOVE') !== false style substring checks to catch informal opt-out phrases in addition to the standard CTIA keywords. Synchronise the opt-out table to your email marketing platform and CRM through a shared suppression list so opt-outs are respected across all channels.
Contact Telphi Consulting to build a compliant opt-out management system with cross-channel suppression for your PHP messaging platform.
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)
Be the first to comment
No comments yet. Share your thoughts below.