Listening to user responses and commands

This recipe is the brain of the system; it handles users sending in responses and also handles what to do if a user wants to be unsubscribed. This script will listen on a phone number and do exactly that.

The listener.php file replaces tracker.php, and it will handle pausing, resuming, and the responses.

Getting ready

The complete source code for this recipe can be found in the Chapter3/ folder.

How to do it...

Let's build on our previous subscriber tracker and add some extra functionality. We'll call this recipe listener.php.

  1. Upload the listener.php file (with the following content) on your web server.
    <?php
    include("config.php");
    include("pdo.class.php");
    $pdo = Db::singleton();
    if( isset($_POST['Body']) ){
      $phone = $_POST['From'];
      $phone = str_replace('+','',$phone);
      $action = strtolower($_POST['Body']);
      switch($action){
        case "pause":
          $sql = "UPDATE subscribers SET status=0 WHERE phone_number='{$phone}'";
          $pdo->exec( $sql );
          $msg = "We have unsubscribed you. Text 'unpause' to be resubscribed";
          break;
        case "unpause":
          $sql = "UPDATE subscribers SET status=1 WHERE phone_number='{$phone}'";
          $pdo->exec( $sql );
          $msg = "We have resubscribed you. Text 'pause' to be unsubscribed";
          break;
        default:
          $sid = $_POST['SmsSid'];
          $sql = "UPDATE responses SET answer='{$action}' WHERE phone_number='{$phone}' AND sms_sid='{$sid}'";
          break;
      }
      print_sms_reply($msg);
    }
    function print_sms_reply ($sms_reply){
      echo "<?xml version="1.0" encoding="UTF-8"?>
    ";    
      echo "<Response>
    <Sms>
    ";
      echo $sms_reply;
      echo "</Sms></Response>
    ";
    }
    ?>
  2. Finally, you have to point your Twilio phone number to it.
    How to do it...

    Insert the URL to this page in the SMS Request URL box. Then, any calls that you receive on this number will be processed via listener.php.

How it works...

The listener.php file serves three purposes, all depending on the value of the $action variable:

  • If $action is "pause", the subscriber is unsubscribed and will no longer be sent any surveys
  • If $action is "unpause", the subscriber is resubscribed and will receive surveys again
  • Finally, if $action is anything else, it is considered a response and stores the subscriber's answer in the database
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset