Skip to contentSkip to navigationSkip to topbar
On this page

Programmable Voice Quickstart for PHP


With just a few lines of code, your PHP web application can make and receive phone calls with Twilio Programmable Voice.

This PHP Voice quickstart will teach you to do this using Twilio's Voice REST API, the Twilio PHP helper library(link takes you to an external page), the built-in PHP development web server, and ngrok(link takes you to an external page) to expose your local server to Twilio.

We'll use the Composer package manager for dependency management (don't want to? Try our Non Composer PHP Voice Quickstart).

In this quickstart, you will learn how to:

  1. Sign up for Twilio and get your first voice-enabled Twilio phone number
  2. Check and install any PHP prerequisites using Composer(link takes you to an external page)
  3. Make an outbound phone call and play an MP3
  4. Receive and respond to an inbound phone call to read a message to a caller using Text to Speech

Prefer to get started by watching a video? Check out our video on how to place and receive phone calls with PHP(link takes you to an external page).


Sign up for Twilio and get a phone number

sign-up-for-twilio-and-get-a-phone-number page anchor
(information)

Info

Already have a Twilio account and a voice-enabled Twilio phone number? Log in(link takes you to an external page) then jump to the next step.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to make calls to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
  • Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page). This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

If you don't currently own a Twilio phone number with Voice functionality, you'll need to purchase one. After navigating to the Buy a Number(link takes you to an external page) page, check the "Voice" box and click "Search."

Search for a Phone Number.

You'll then see a list of available phone numbers and their capabilities. Find a number that you like and click "Buy" to add it to your account.

Buy a Phone Number.

Install PHP and the Twilio PHP helper library

install-php-and-the-twilio-php-helper-library page anchor
(information)

Info

If you already have PHP and the Twilio PHP Helper Library installed in your working directory, you're all set for this step. Feel free to skip ahead and move on to sending your first text message.

To make your first outbound voice call, let's make sure you're set up with PHP and able to install Twilio's PHP Helper library.

When doing web development in PHP, we strongly suggest using Composer(link takes you to an external page) for your package management. This quickstart relies on Composer to install the PHP Helper library. (If you choose not to use Composer, you can find manual Twilio PHP installation instructions on the PHP Helper Library page(link takes you to an external page).)

Install PHP

install-php page anchor

If you're using a Mac or *nix machine, you may already have PHP installed. In your terminal, run:

php --version

If PHP is not installed, follow the PHP installation instructions(link takes you to an external page).

If you're using a Windows machine, follow the official PHP tutorial to install PHP(link takes you to an external page).

(error)

Danger

While many versions of PHP 7.x will work for this quickstart, please pay attention to supported PHP releases(link takes you to an external page).When doing web development, always update your PHP version to a release which receives security updates.

Install Composer for package management

install-composer-for-package-management page anchor

Composer is the de facto canonical package manager for PHP web development. For this tutorial, Composer is required. If you don't want to install Composer, try our non Composer PHP Voice Quickstart.

Install the Twilio PHP Helper Library

install-the-twilio-php-helper-library page anchor

Now we need to install the Twilio PHP Helper Library.

First, navigate to the directory where you will complete this quickstart then choose one of the following methods to install the helper library.

From a terminal, you can run the following command:

composer require twilio/sdk

Or, you can create a file named composer.json instead. In that file, add:

1
{
2
"require": {
3
"twilio/sdk": "^5.0"
4
}
5
}
6

Next, run

composer install

Composer will grab the latest 5.x version of the Twilio PHP Helper Library.

To not use Composer, try this PHP Voice Quickstart.


Make an outgoing phone call with PHP

make-an-outgoing-phone-call-with-php page anchor

Now that we have PHP and the PHP Helper Library installed, we can make an outgoing phone call in a single API request. Create a new file called make_call.php and type or paste in this code sample.

Make a voice call

make-a-voice-call page anchor

Make a Voice call with the PHP Helper Library

1
<?php
2
require __DIR__ . '/vendor/autoload.php';
3
use Twilio\Rest\Client;
4
5
// Your Account SID and Auth Token from twilio.com/console
6
// To set up environmental variables, see http://twil.io/secure
7
$account_sid = getenv('TWILIO_ACCOUNT_SID');
8
$auth_token = getenv('TWILIO_AUTH_TOKEN');
9
// In production, these should be environment variables. E.g.:
10
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]
11
12
// A Twilio number you own with Voice capabilities
13
$twilio_number = "+15017122661";
14
15
// Where to make a voice call (your cell phone?)
16
$to_number = "+15558675310";
17
18
$client = new Client($account_sid, $auth_token);
19
$client->account->calls->create(
20
$to_number,
21
$twilio_number,
22
array(
23
"url" => "http://demo.twilio.com/docs/voice.xml"
24
)
25
);
26

When you run the code, it will start a phone call between the two numbers passed as arguments. We've added two variables to show you the 'From' and 'To' number and they will map like this:

  • (From) / twilio_number: The Twilio phone number you purchased
  • (To) / to_number: The number to call (perhaps your cell phone?)

Inside the array, the url argument points to some TwiML. TwiML is a language Twilio uses internally to initiate or respond to actions, such as a sequence for a voice call. This particular TwiML causes Twilio to read a message with text to speech then play an MP3 to the 'To' / to_number number.

Before you can run this code, you need to swap in a couple of account specific values.

Replace the placeholder credentials with your own

replace-the-placeholder-credentials-with-your-own page anchor

Substitute the placeholder values for account_sid and auth_token with your Twilio account credentials.

To find these, visit https://www.twilio.com/console(link takes you to an external page) and log in. On this page, you'll find your unique Account SID and Auth Token. You can reveal the Auth Token by clicking the 'eye' icon:

Reveal Your Auth Token.

Open make_call.php and replace the values for account_sid and auth_token with your unique values.

(error)

Danger

Note: It's easier to hardcode your credentials for this quickstart, but you should use environment variables to keep them secret in production. Check out how to set environment variables(link takes you to an external page) for more information, and see the code comments for a reading example. This repo(link takes you to an external page) is also an excellent reference for environment variables in PHP.

Replace the twilio_number phone number

replace-the-twilio_number-phone-number page anchor

Earlier, you purchased or found a voice-enabled phone number(link takes you to an external page). Paste the number into the twilio_number variable using E.164 formatting:

[+][country code][phone number including area code]

For example, +18005551212.

Replace the to_number phone number

replace-the--phone-number-2 page anchor

Again using E.164 formatting, substitute the phone number which will receive the outgoing call. You should use a personal phone number here so you'll receive the call and hear the magic after running the code.

(warning)

Warning

If you're using a Twilio trial account, you can only make outgoing calls to phone numbers you have verified with Twilio. Phone numbers can be verified with your Twilio Console's Verified Caller IDs(link takes you to an external page). For full trial account limitations, see our guide on how to work with your free Twilio trial account.

Save the script and invoke it to test an outgoing call. For OSX and *NIX, this should look like:

php make_call.php

If you substituted everything correctly, you'll soon hear a great message and a brand new song! If not, don't ever give up and follow the console prompts.


Receive and respond to inbound voice calls with PHP

receive-and-respond-to-inbound-voice-calls-with-php page anchor

When someone calls your Twilio phone number, Twilio makes an HTTP request to your server asking for instructions on how to handle the call. For this quickstart, we'll reply to the sender and thank them for their phone call using Twilio's text to speech capabilities.

Again, we'll use the Twilio PHP Library for this step. We will use PHP's built-in development web server in combination with ngrok to instruct Twilio on how to manage the call.

Create a new file, answer_call.php, in the same directory as make_call.php. Then copy and paste or type the following code.

(Note: if you do not use the same directory as you did when we made our first call, please follow the PHP Helper Library install step above)

Receive an incoming voice call

receive-an-incoming-voice-call page anchor

Receive and respond a Voice call with the PHP Helper Library

1
<?php
2
require __DIR__ . '/vendor/autoload.php';
3
use Twilio\TwiML\VoiceResponse;
4
5
// Start our TwiML response
6
$response = new VoiceResponse;
7
8
// Read a message aloud to the caller
9
$response->say(
10
"Thank you for calling! Have a great day.",
11
array("voice" => "Polly.Amy")
12
);
13
14
echo $response;

Save answer_call.php, then start a local PHP development server with:

php -S localhost:8000

In a browser tab open the URL http://localhost:8000/answer_call.php(link takes you to an external page).

If everything went well, you should now see XML in your browser with the message we'd like to read to incoming calls. That's all the code you need - there are just a few more steps before everything is wired up.

Next, let's expose this endpoint to Twilio.


Allow Twilio to talk to your PHP application

allow-twilio-to-talk-to-your-php-application page anchor

Before we can instruct Twilio on what to do in response to an incoming call, you first need to expose your server to the public. When you run your local development server, the odds are very high it is only accessible from your local network. But don't worry - we'll show you a way to test your server.

Many Twilio products and services use webhooks to communicate with your application. For example, when Twilio receives an incoming call, it reaches out to a specific URL you provide to search for instructions on how to handle the response. The small piece of code in answer_call.php is an example of one instruction you can use to 'speak' back to the caller. However, when you run the server it will only be exposed to you locally, not to the broader public. We need to figure out a way to fix that.

While there are many ways to make this code public (for example by deploying it to a host), we recommend a tool called ngrok. When you start ngrok, it provides a unique URL on the ngrok.io domain and forwards incoming requests to your local development environment.

The architecture looks like this:

How ngrok helps Twilio reach your local server.

If you don't already use ngrok, visit the download page(link takes you to an external page) and install it for your operating system.

If you're working on Mac or Linux, you're all set after you decompress it. If you're on Windows, follow our guide on how to install and configure ngrok on Windows. For more info on ngrok (including some great tips and tricks) check out our this ngrok blog post(link takes you to an external page).

Once you download an install ngrok, open a new terminal tab or window (leaving your development server running) and start it with this command:

./ngrok http 8000

You should see output similar to this:

Ngrok server terminal output.

Copy the public URL from this output, paste it into your browser, and append answer_call.php. You should see the same XML you saw previously, except now you can access this from anywhere you've got internet access.

Now that you're public let's tell Twilio where to find the server.


Configure your webhook URL

configure-your-webhook-url page anchor

Now that your server is publicly accessible, you need to configure your Twilio phone number to access your webhook URL when new calls come in.

  1. Visit the Console's Numbers page(link takes you to an external page).
  2. Click on your voice-enabled phone number.
  3. Find the "Voice & Fax" section. Make sure the "Accept Incoming" selection is set to "Voice Calls." The default "Configure With" selection is what you'll need: "Webhooks/TwiML...".
  4. In the "A Call Comes In" section, select "Webhook" and paste in the URL you want to use, appending/answer_call.php :
Voice call webhook with ngrok.

Save your changes, and you're ready to roll!

If your local development server is still running and ngrok is still going, you're ready for the fun part - testing!

Make a phone call to your Twilio phone number. You'll see and hear a number of things happen in short succession:

  1. You'll see an HTTP request in the ngrok console
  2. The development server will print out some messages to the console
  3. You'll hear the message once the call connects

And there you go - working outbound and inbound calling with PHP.


Now you know the basics of making and responding to phone calls with PHP.

This PHP app only used the <Say> TwiML verb to read a message to the caller using text to speech. With different TwiML verbs, you can create other powerful constructs and call flows. Try a few, such as <Record>, <Gather>, and <Conference>.

Check out these pages to learn more:

We can't wait to see what you build!

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.