This tutorial builds a click-to-call feature using PHP and Twilio that accepts a visitor's phone number from a web form, dials them back using Twilio's outbound calls API, and bridges them to a support or sales agent via a TwiML connect script. It targets PHP developers who want a "Call Me Now" button that puts a website visitor on a live call within seconds. You will build a PHP POST handler that validates the number, creates the Twilio call, and a TwiML endpoint that connects the visitor to your agent once they answer.
Prerequisites and Setup
Install the packages with composer require twilio/sdk vlucas/phpdotenv and store your Twilio credentials and the agent's phone number as environment variables in a .env file. The click-to-call flow works in two steps: Twilio dials the visitor's number first, and once they answer, Twilio fetches TwiML from your connect-agent.php script to dial and bridge the agent. The visitor's number must be validated as E.164 format on the server before being passed to the API to prevent injection or invalid API calls. Expose your local server with ngrok during development since TwiML URLs must be publicly accessible HTTPS endpoints.
composer require twilio/sdk vlucas/phpdotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
AGENT_PHONE_NUMBER=+15559998888
The Complete Code
The call.php handler reads and validates the visitor's phone number with a regex, calls $client->calls->create() with the visitor as the recipient and the TwiML connect URL as the instruction source, and returns a JSON confirmation response. The connect-agent.php TwiML endpoint builds a VoiceResponse with a brief say() prompt followed by a Dial verb targeting the agent's number. The callerId attribute on the Dial verb shows your Twilio number on the agent's screen rather than the visitor's number, maintaining caller ID consistency. A successful calls->create() returns a call object with a SID starting with CA that you can return to the browser for reference or logging.
<?php
// call.php
require_once 'vendor/autoload.php';
use TwilioRestClient;
use TwilioExceptionsRestException;
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
header('Content-Type: application/json');
$phone = trim($_POST['phone'] ?? '');
if (!preg_match('/^+[1-9]d{7,14}$/', $phone)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid phone. Use E.164 format, e.g. +15551234567']);
exit;
}
$client = new Client($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
try {
$call = $client->calls->create(
$phone,
$_ENV['TWILIO_PHONE_NUMBER'],
['url' => 'https://xxxx.ngrok.io/connect-agent.php']
);
echo json_encode(['message' => 'Calling you now!', 'sid' => $call->sid]);
} catch (RestException $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
<?php
// connect-agent.php
require_once 'vendor/autoload.php';
use TwilioTwiMLVoiceResponse;
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
$response = new VoiceResponse();
$response->say('Please hold while we connect you to a specialist.', ['voice' => 'alice']);
$dial = $response->dial(['callerId' => $_ENV['TWILIO_PHONE_NUMBER']]);
$dial->number($_ENV['AGENT_PHONE_NUMBER']);
header('Content-Type: text/xml');
echo $response;
Testing and Debugging
Submit the form with your own mobile number and wait for Twilio to call you within a few seconds. When you answer, you should hear the hold message and be connected to the agent number you configured. If the visitor's phone rings but the agent is never called, check that your ngrok URL resolves to connect-agent.php and that the Dotenv file is loading the AGENT_PHONE_NUMBER variable correctly. Error code 13224 in the Twilio Console means Twilio could not fetch the TwiML from connect-agent.php; confirm your server is running and the script has no PHP syntax errors that would prevent it returning a valid response.
Taking It Further
Add agent availability logic that checks a schedule table in the database and returns a voicemail TwiML instead of dialling the agent if no one is available during the requested time. Implement a call queue by using Twilio TaskRouter so multiple simultaneous click-to-call requests are handled in order when agents are busy. Log each click-to-call event to a database with the visitor's number, referring URL from the HTTP Referer header, timestamp, and resulting call SID for marketing attribution and conversion tracking. Add a whisper to the Dial verb using a Conference noun so the agent hears a brief recorded or spoken context note before the visitor is connected to the call.
Contact Telphi Consulting to implement a production click-to-call solution with agent routing, queueing, 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.