When a call comes into your Twilio number, Twilio sends the phone call information to your application as an HTTP request. Information such as the caller's phone number and, if available, their city, state, and zip code. (A full list can be found here.) Logging this information is easy to do, and could be useful for reporting later on.
This is the last of a five part series on building IVRs using Twilio's API. If you're just joining us, you can find links to the prior sections below:
When a customer dials into our IVR, we'll log their call information so that we can easily create reports later on.
For this section, we'll be working with a simple SQLite database with one table that looks like:
| id | caller | call_time |
|---|---|---|
| 1 | +14158141819 | 1270141200 |
| 2 | +14153855708 | 1270143000 |
You can use the script below to create the database and table.
$db = new PDO('sqlite:ivr.sqlite');
$db->exec('CREATE TABLE calls (id INTEGER PRIMARY KEY, caller TEXT, call_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);');
if (file_exists('ivr.sqlite'))
{
echo 'Database and tables created.';
}
else {
echo 'Database was not created. Please check to make sure this directory is writeable.';
}
This demo shows how to get the data Twilio sends for each incoming phone call and log it to a database.
handle-incoming-call.php. When someone calls the number, Twilio will request this page with the standard TwiML request parameters.
$db = new PDO('sqlite:ivr.sqlite');
$stmt = $db->prepare('INSERT INTO calls (caller) VALUES (?)');
$stmt->execute(array($_REQUEST['From']));
Pulling this information out at a later time is as easy as querying the database. The following code returns a list of all the calls that came into our IVR.
<?php
$db = new PDO('sqlite:ivr.sqlite');
$result = $db->query('SELECT caller, datetime(call_time) AS call_time FROM calls');
echo '<ul>';
foreach ($result as $row)
{
echo '<li>A call came in on '.$row['call_time'].' from '.$row['caller'].'</li>';
}
echo '</ul>';
?>