This tutorial builds a PHP webhook endpoint that Twilio calls when your number receives an inbound voice call and returns TwiML instructions that control what the caller hears and where the call goes. It targets PHP developers who need to program the call experience when someone dials their Twilio number, from playing a greeting to routing the call to an agent. You will build two PHP scripts: one that greets the caller and collects a digit using Gather, and one that handles the digit and connects the call.
Prerequisites and Setup
Install the packages with composer require twilio/sdk and expose your local PHP server with ngrok using ngrok http 8000. In the Twilio Console, navigate to your phone number's Voice configuration and set the webhook URL to your ngrok HTTPS address followed by /answer.php, with HTTP method set to POST. The PHP scripts read inbound call data from $_POST which Twilio populates automatically when it calls the webhook. Two scripts handle the flow: answer.php returns the Gather prompt, and handle-key.php reads the digit and returns the routing TwiML.
composer require twilio/sdk
# Twilio Console: Voice webhook
# https://xxxx.ngrok.io/answer.php (POST)
The Complete Code
The answer.php script builds a VoiceResponse with a Gather verb whose action attribute points to handle-key.php and numDigits set to 1 so Twilio collects exactly one keypad press. Nesting a say() call on the Gather object plays the prompt audio while the Gather verb waits for input. The handle-key.php script reads $_POST['Digits'] and either dials an agent number or plays an error message and hangs up. A fallback say() placed after the Gather in answer.php plays when no digit is pressed within the timeout period.
<?php
// answer.php
require_once 'vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$response = new VoiceResponse();
$gather = $response->gather(['numDigits' => 1, 'action' => '/handle-key.php', 'method' => 'POST']);
$gather->say('Press 1 for sales. Press 2 for support.', ['voice' => 'alice']);
$response->say('We did not receive your input. Goodbye.', ['voice' => 'alice']);
header('Content-Type: text/xml');
echo $response;
<?php
// handle-key.php
require_once 'vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$agents = ['1' => '+15550001111', '2' => '+15550002222'];
$digit = $_POST['Digits'] ?? '';
$response = new VoiceResponse();
if (isset($agents[$digit])) {
$response->say('Connecting you now. Please hold.', ['voice' => 'alice']);
$dial = $response->dial(['callerId' => $_ENV['TWILIO_PHONE_NUMBER'] ?? '']);
$dial->number($agents[$digit]);
} else {
$response->say('Invalid selection. Goodbye.', ['voice' => 'alice']);
$response->hangup();
}
header('Content-Type: text/xml');
echo $response;
Testing and Debugging
Call your Twilio number and listen for the greeting to confirm Twilio is reaching your webhook and answer.php is returning valid TwiML. If you hear only silence, verify answer.php is setting the Content-Type: text/xml header and returning a 200 status with no PHP errors in the output. Twilio error 11200 means your webhook returned a non-2xx status or invalid TwiML; check the PHP error log for exceptions that are being silently swallowed before the response is sent. Test the timeout fallback by staying silent after the greeting to confirm the post-Gather say plays the goodbye message instead of the call dropping abruptly.
Taking It Further
Add a timeout attribute to the gather() options array to control how many seconds Twilio waits before falling through to the fallback. Enable speech recognition by adding 'input' => 'speech dtmf' to the gather options so callers can say department names instead of pressing digits. Log every inbound call to a database using PDO with the caller's number, selected digit, and timestamp for analytics and capacity planning. Load the agent routing table from a database or environment file so routing changes do not require modifying PHP code and can be updated by non-developers.
Contact Telphi Consulting to implement custom inbound call handling with intelligent routing, recording, and CRM integration in PHP.
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.