How do you turn a handful of isolated messages to and from the same party into a true conversation? You need some way to remember state between each message that is exchanged. This is because SMS is a stateless protocol. Building traditional web applications has this same hurdle, as HTTP is also a stateless protocol. This problem has been solved for web applications through the use of HTTP cookies and, rather than reinvent the wheel, the Twilio Messaging API uses the same solution.
This guide will show you how to use Programmable Messaging to accomplish this in your PHP application. The code snippets in this guide are written using the PHP language version 5.3 or higher, and make use of the Twilio PHP SDK.
If you haven't written your own SMS webhooks with PHP before, you may want to first check out our guide, Receive and Reply to SMS and MMS Messages in PHP. Ready to go? Let's get started!
Twilio Conversations, a more recent product offering, is an omni-channel messaging platform that allows you to build engaging conversational, two-way messaging experiences. Be sure to check out our Conversations product to see if it's a better fit for your needs.
The cookies let 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.
You can store the data directly in a cookie, or you can use a session state management framework.
Let's try using session counters to see if a particular user has messaged us before. If they're a new sender, we'll thank them for the new message. If they've sent us messages before, we'll specify how many messages we've gotten from them.
1<?php23// start the session4session_start();56// get the session varible if it exists7$counter = $_SESSION['counter'];89// if it doesnt, set the default10if(!strlen($counter)) {11$counter = 0;12}1314// increment it15$counter++;1617// save it18$_SESSION['counter'] = $counter;1920// make an associative array of senders we know, indexed by phone number21$people = array(22"+14158675308"=>"Rey",23"+12349013030"=>"Finn",24"+12348134522"=>"Chewy",25);2627// if the sender is known, then greet them by name28if(!$name = $people[$_REQUEST['From']]) {29$name = "Friend";30}3132// output the counter response33header("content-type: text/xml");34echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";35?>36<Response>37<Message><?php echo $name ?> has messaged <?php echo $_REQUEST['To']." ".$counter ?> times</Message>38</Response>