This tutorial builds a multi-level interactive voice response system in PHP using TwiML Gather verbs and Redirect verbs so callers can navigate a phone menu by pressing digits on their keypad. It targets PHP developers who need structured call routing across departments without expensive PBX hardware. You will implement a main menu and two sub-menus with proper loopback handling and a fallback for callers who make no selection within the timeout period.
Prerequisites and Setup
Install the Twilio PHP SDK with composer require twilio/sdk and map your IVR tree before writing any PHP, since each menu level becomes a pair of PHP files: one for the prompt and one for the digit handler. Expose your local server with ngrok and set your Twilio number's voice webhook to /ivr/main.php. Each PHP file in the IVR reads $_POST['Digits'] to determine what the caller pressed and constructs the appropriate next TwiML response. A redirect() call after the Gather verb in each menu file loops the caller back to the same menu if the digit collection times out without input.
composer require twilio/sdk
# File structure:
# ivr/main.php - main menu prompt
# ivr/main-handler.php - main digit handler
# ivr/sales.php - sales sub-menu
# ivr/support.php - support sub-menu
The Complete Code
Each menu PHP file builds a VoiceResponse with a nested Gather whose action points to the handler for that level and whose timeout is set to 5 seconds. Handler files read $_POST['Digits'] and use a switch or match expression to either redirect to a sub-menu, dial an agent, or loop back to the same menu on invalid input. The shared $agents array maps department keys to phone numbers and is defined in a separate config.php so routing updates do not require touching menu logic. The callerId on every Dial verb is set to your Twilio number so agents see a consistent outbound caller ID rather than the caller's real number.
<?php
// ivr/main.php
require_once '../vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$response = new VoiceResponse();
$gather = $response->gather(['numDigits' => 1, 'action' => '/ivr/main-handler.php', 'timeout' => 5]);
$gather->say('Press 1 for sales. Press 2 for support. Press 3 for billing.', ['voice' => 'alice']);
$response->redirect('/ivr/main.php');
header('Content-Type: text/xml'); echo $response;
<?php
// ivr/main-handler.php
require_once '../vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$agents = ['billing' => '+15550005555'];
$digit = $_POST['Digits'] ?? '';
$response = new VoiceResponse();
switch ($digit) {
case '1': $response->redirect('/ivr/sales.php'); break;
case '2': $response->redirect('/ivr/support.php'); break;
case '3':
$response->say('Connecting you to billing.', ['voice' => 'alice']);
$dial = $response->dial();
$dial->number($agents['billing']);
break;
default:
$response->say('Invalid option.', ['voice' => 'alice']);
$response->redirect('/ivr/main.php');
}
header('Content-Type: text/xml'); echo $response;
<?php
// ivr/sales.php
require_once '../vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$response = new VoiceResponse();
$gather = $response->gather(['numDigits' => 1, 'action' => '/ivr/sales-handler.php', 'timeout' => 5]);
$gather->say('For new accounts press 1. For existing accounts press 2.', ['voice' => 'alice']);
$response->redirect('/ivr/sales.php');
header('Content-Type: text/xml'); echo $response;
<?php
// ivr/sales-handler.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.', ['voice' => 'alice']);
$dial = $response->dial();
$dial->number($agents[$digit]);
} else {
$response->redirect('/ivr/sales.php');
}
header('Content-Type: text/xml'); echo $response;
Testing and Debugging
Call your Twilio number and navigate through each menu branch to confirm every digit maps to the correct next action. Test the timeout fallback by staying silent after each prompt to verify the redirect() loops back to the same menu rather than the call dropping. Use the Twilio Console Call Logs to see the exact sequence of TwiML fetches, HTTP statuses, and verb executions for each test call, which makes it straightforward to pinpoint which PHP file is failing. If a redirect results in an infinite loop without any audio, check that the target PHP file exists on the server and is returning a valid non-redirect TwiML response.
Taking It Further
Move the agents array and menu structure to a database table so operations staff can update routing without touching PHP code. Add time-based routing at the top of each handler that checks date('H') against business hours and redirects to a voicemail script outside those hours. Use the play() method instead of say() to play pre-recorded MP3 audio files for a professional sound that does not rely on text-to-speech synthesis. Enable speech input by adding 'input' => 'speech dtmf' to each Gather so callers can speak department names as an alternative to pressing digits.
Contact Telphi Consulting to architect and deploy a production IVR with analytics, call recording, and CRM integration built on 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.