Getting notified when the time comes

Ok, we're done adding reminders; now, how do we get reminded? Simple, a cron job that runs each hour and notifies us of upcoming reminders an hour before they are due.

Getting ready

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

How to do it…

Now we're building the part of our reminder system that notifies us when the time comes for the reminder.

  1. Download the Twilio Helper Library from https://github.com/twilio/twilio-php/zipball/master and unzip it.
  2. Upload the Services/ folder to your website.
  3. Upload sql.sql to your database.
  4. Upload config.php to your website and make sure the following variables are set:
    <?php
      session_start();
      $accountsid = '';//YOUR TWILIO ACCOUNT SID
      $authtoken = '';//YOUR TWILIO AUTH TOKEN
      $fromNumber = '';//PHONE NUMBER CALLS WILL COME FROM
    
      $dbhost = '';//YOUR DATABASE HOST
      $dbname = '';//YOUR DATABASE NAME
      $dbuser = '';//YOUR DATABASE USER
      $dbpass = '';//YOUR DATABASE PASS
    ?>
  5. Upload cron.php to your web server using the following code:
    <?php
    include("config.php");
    include("pdo.class.php");
    include 'Services/Twilio.php';
    
    $pdo = Db::singleton();
    $client = new Services_Twilio($accountsid, $authtoken);
    
    $curtime = strtotime("+1 hour");
    $curtime2 = strtotime("+2 hour");
    $sql = "SELECT * FROM reminders where (`timestamp` BETWEEN  $curtime AND $curtime2) AND `notified` = 0";
    
    $res = $pdo->query( $sql );
    while( $row = $res->fetch() ){
      $msg = "Reminder: ".$row['message']. ' @ '.date('h:i A',$row['timestamp']);;
      $pdo->exec("UPDATE reminders SET `notified` = 1,`status`=1 WHERE `ID`='{$row['ID']}';");
      $ph = $row['phone_number'];
      $ph2 = $row['phone_number2'];
      $client->account->sms_messages->create( $fromNumber, $ph, $msg );
      if( !empty($ph2) ){
        $client->account->sms_messages->create( $fromNumber, $ph2, $msg );
      }
    }
  6. Set cron.php to run on an hourly cron as follows:
    0 * * * * /usr/bin/curl -I "http://www.mywebsite.com/cron.php"

How it works…

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP; this library is at the heart of your Twilio-powered apps.

In step 3, we loaded our database schema into our database.

In step 4, we uploaded config.php that contains our authentication information to communicate with Twilio's API.

In step 5, we uploaded cron.php, and in step 6, we set it up to run hourly.

First, we populate the $curtime variable with whatever the time will be one hour from the present. Then we grab all the reminders that are due for that time and send a text message about it.

..................Content has been hidden....................

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