Preventing Spam & Fraud with SMS Phone Verification

Check out our updated Phone verification post here.

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.

[code lang="html"]
<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>
[/code]

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.

[code lang="js"]
<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>
[/code]

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.

[code lang="php"]
<?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);
?>
[/code]

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.

[code lang="php"]
<?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);
?>
[/code]

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