Twilio

Twilio SMS Quickstart

Tracking SMS Conversations

Twilio offers a simple way to keep track of conversations between two phone numbers by using HTTP cookies.

What is a cookie?

Just like in web applications, a cookie is a small file that your application can store on Twilio's servers to keep track of information, such as a username or account. For Twilio SMS, cookies are scoped to the "conversation" between two parties... i.e., you can have a unique cookie for each To/From phone number pair. For example, you can store a unique cookie for the any messages sent between 415-555-2222 and 415-555-1111, which will be different than the cookies used between 415-555-3333 and 415-555-1111.

Why cookies?

In web apps, you write a cookie to keep "statefulness" between separate requests from the same browser. Similarly, SMS messages are independent communications between two parties, so Twilio allows you to tie them together as a logical session via cookies. This means you can use server-side sessions to keep track of application state between requests. How cool! Twilio will expire the cookies for that conversation after four hours of inactivity, as if the user "closed the browser."

Storing Conversation Data

The cookies lets you share state across multiple messages allowing you to treat separate messages as a conversation, and store data about the conversation in the cookies for future reference.

Let's use this functionality to count how many messages a certain person has sent.

quickstart/sms/sms-conversation.php
<?php

	// start the session
	session_start();

	// get the session varible if it exists
	$counter = $_SESSION['counter'];

	// if it doesnt, set the default
	if(!strlen($counter)) {
		$counter = 0;
	}

	// increment it
	$counter++;

	// save it
	$_SESSION['counter'] = $counter;

	// make an associative array of senders we know, indexed by phone number
	$people = array(
		"4158675309"=>"Curious George",
		"4158675310"=>"Boots",
		"4158675311"=>"Virgil",
	);

	// if the sender is known, then greet them by name
	// otherwise, consider them just another monkey
	if(!$name = $people[$_REQUEST['From']])
		$name = "Monkey";

	// output the counter response
	header("content-type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
	<Sms><?php echo $name ?> has messaged <?php echo $_REQUEST['To']." ".$counter ?> times</Sms>
</Response>

Here, we use a session to store the message count. If you are unfamiliar with sessions (or cookies) in PHP, w3schools has a great introduction to both, which can be found here

Go ahead and send a few messages to your Twilio application, and watch your counter grow.

Next: Sending SMS Messages During a Phone Call