Preventing Spam & Fraud with SMS Phone Verification

If you’ve used a service like Google Calendar that sends out reminders via SMS, you may recall that when you set up your mobile device to receive alerts, the application verified that you were the owner of the device. This is done by sending you a short verification code that you then entered on the web site. Once this process is complete, the application can safely send you alerts knowing that you are the owner of that number. Other applications have used this technique to help prevent spam and fraud as well.

In a previous post we walked through how to build a simple phone verification system that called a user and prompted them to enter in a code over the phone. Here’s another take on that concept, this time around we’re going to send the code via an SMS text message to their phone and have them type it in their web browser.

Basic Steps

  1. User visits verification web page and enters phone number
  2. A random verification code is generated and sent to the user’s phone number via a text message
  3. The web site prompts the user to enter the verification code
  4. The code is checked against the one stored in the database and the appropriate response is returned.

Step One: Collect user’s phone number

We start by creating an index.php page with two forms, one to collect the phone number, and one to verify the code.

<form id="enter_number">
   <p>Enter your phone number:</p>
   <p><input type="text" name="phone_number" id="phone_number" /></p>
   <p><input type="submit" name="submit" value="Verify" /></p>
</form>
<form id="verify_code" style="display: none;" action="status.php" method="post">
   <p>Sending you a text message with your verification code.</p>
   <p>Once received, enter it here:</p>
   <h1 id="verification_code"><input type="text" name="verification_code" maxlength="6" size="7" /></h1>
   <input type="hidden" value="" id="phone_number2" name="phone_number" />
   <p><input type="submit" value="Verify" /></p>
</form>

Using jQuery we intercept the submission of the first form and show the second one which was initially hidden. At the same time we also copy the phone number value entered into a hidden form field to use later on.

<script type="text/javascript">
   $(document).ready(function(){
      $("#enter_number").submit(function(e) {
         e.preventDefault();
         initiateSms();
      });
   });
   function initiateSms() {
      $.post("sms.php", { phone_number : $("#phone_number").val() },
      showVerifyForm,
      "json");
   }
   function showVerifyForm() {
      $("#phone_number2").val($("#phone_number").val());
      $("#enter_number").fadeOut("fast");
      $("#verify_code").fadeIn();
   }
</script>

Step Two: Generate code, store it and send it to the user

When the first form is submitted we make a POST request to sms.php which contains our code for generating the random code, saving the code and phone number to our database and sending the text message to the user. We’re using the Twilio PHP Helper Library again to make it even easier to send the text message.

<?php
   require("twilio.php");
   require("database.php");
   // require POST request
   if ($_SERVER['REQUEST_METHOD'] != "POST") die;
   // generate "random" 6-digit verification code
   $code = rand(100000, 999999);
   // save verification code in DB with phone number
   // does not check for duplicates like it should
   $number = mysql_real_escape_string($_POST["phone_number"]);
   db(sprintf("INSERT INTO numbers (phone_number, verification_code) VALUES('%s', %d)", $number, $code));
   mysql_close();
   // Set our AccountSid and AuthToken
   $AccountSid = "ACxxxxxxxxxxxxxxxxxxxxxxx";
   $AuthToken = "xxxxxxxxxxxxxxxxxxxxxxxx";
   // Instantiate a new Twilio Rest Client
   $client = new TwilioRestClient($AccountSid, $AuthToken);
   // call data
   $data = array(
      "From" => "555-111-2222", // Verified Outgoing Caller ID or Twilio number
      "To" => $number,          // The phone number you wish to send a message to
      "Body" => "Verification code: $code"
   );
   // send text message
   $response = $client-&gt;request("/2008-08-01/Accounts/$AccountSid/SMS/Messages", "POST", $data);
?>

Steps Three and Four: Collect and validate user-entered code

Now that the user has been sent the text message with the verification code then can enter it in the second form we created above. That form is sent to status.php which checks the database for a match and let’s the user know if the verification succeeded or failed.

<?php
   require("database.php");
   // require POST request
   if ($_SERVER['REQUEST_METHOD'] != "POST") die;
   $number = mysql_real_escape_string($_POST["phone_number"]);
   $code = mysql_real_escape_string($_POST["verification_code"]);
   $result = db(sprintf("select * from numbers where phone_number='%s'", $number));
   $msg = "Invalid code. Please try again.";
   if($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
      if ($line["verification_code"] == $code) {
         db(sprintf("UPDATE numbers SET verified = 1 WHERE phone_number = '%s'", $number));
         $msg = "Verified!";
      }
   }
   mysql_close();
   die($msg);
?>

That’s it!

SMS text messages are a great way to have your web application reach out and interact with people even when they’re not sitting at their computers. With this simple verification technique you can confidently send messages to your users mobile devices knowing the messages are reaching their intended destination.

Download Complete Example

Twilio SMS Verification on Github

Posted by John Sheehan on May 11, 2010
  • Elena

    The Google Calendar link is wrong.
    Cheers.

  • Elena

    The Google Calendar link is wrong.
    Cheers.

  • http://profile.typepad.com/lindsayjeff Jeff Lindsay

    I love the photo at the top.

  • http://profile.typepad.com/lindsayjeff Jeff Lindsay

    I love the photo at the top.

  • Sysmith011

    MOBILE# +639192616111—SMS ONLY

    • Summersmith04

      summer smith
      my cell# +639192616111

  • Sysmith011

    MOBILE# +639192616111—SMS ONLY

    • Summersmith04

      summer smith
      my cell# +639192616111

  • http://www.facebook.com/people/James-Labbe/100000617441351 James Labbe

    njnfsnjfnjdngfrkl

  • http://www.facebook.com/people/James-Labbe/100000617441351 James Labbe

    njnfsnjfnjdngfrkl

  • http://thaiprepaidcard.com/ Bryan

    The Github example has the wrong file named sms.php.  Should be as listed here.

  • http://thaiprepaidcard.com/ Bryan

    The Github example has the wrong file named sms.php.  Should be as listed here.

  • http://www.facebook.com/people/Cbs-Infosys/100000036910105 Cbs Infosys

    Too many bugs in the code posted. Finally fixed it..

  • http://www.facebook.com/people/Cbs-Infosys/100000036910105 Cbs Infosys

    Too many bugs in the code posted. Finally fixed it..

  • Abhilash Raj R.S

    Its not working

    • http://www.twilio.com Twilio

      If you have issues building, email help@twilio.com and we can help walk you through it. 

  • Abhilash Raj R.S

    Its not working

    • http://www.twilio.com Twilio

      If you have issues building, email help@twilio.com and we can help walk you through it.