Skip to content

Instantly share code, notes, and snippets.

@jonmarkgo
Created March 28, 2012 17:11
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jonmarkgo/2228315 to your computer and use it in GitHub Desktop.
Save jonmarkgo/2228315 to your computer and use it in GitHub Desktop.
Simple Phone Verification with Twilio, PHP, MySQL, and jQuery
<?php
require("Services/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
// attempts to delete existing entries first
$number = mysql_real_escape_string($_POST["phone_number"]);
db(sprintf("DELETE FROM numbers WHERE phone_number='%s'", $number));
db(sprintf("INSERT INTO numbers (phone_number, verification_code) VALUES('%s', %d)", $number, $code));
mysql_close();
// initiate phone call via Twilio REST API
// Set our AccountSid and AuthToken
$AccountSid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$AuthToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);
try {
// make call
$call = $client->account->calls->create(
'+18881234567', // Verified Outgoing Caller ID or Twilio number
$number, // The phone number you wish to dial
'http://example.com/twiml.php' // The URL of twiml.php on your server
);
} catch (Exception $e) {
echo 'Error starting phone call: ' . $e->getMessage();
}
// return verification code as JSON
$json = array();
$json["verification_code"] = $code;
header('Content-type: application/json');
echo(json_encode($json));
?>
<?php
$db_host='localhost';
$db_name='dbname';
$db_user='dbuser';
$db_passwd='dbpassword';
mysql_connect($db_host, $db_user, $db_passwd)
or die('Could not connect: ' . mysql_error());
mysql_select_db($db_name) or die('Could not select database');
function db($sql)
{
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
return $result;
}
?>
--
-- Table structure for table `numbers`
--
CREATE TABLE IF NOT EXISTS `numbers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`phone_number` varchar(50) DEFAULT NULL,
`verification_code` int(11) DEFAULT NULL,
`verified` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Phone Verification by Twilio</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#enter_number").submit(function(e) {
e.preventDefault();
initiateCall();
});
});
function initiateCall() {
$.post("call.php", { phone_number : $("#phone_number").val() },
function(data) { showCodeForm(data.verification_code); }, "json");
checkStatus();
}
function showCodeForm(code) {
$("#verification_code").text(code);
$("#verify_code").fadeIn();
$("#enter_number").fadeOut();
}
function checkStatus() {
$.post("status.php", { phone_number : $("#phone_number").val() },
function(data) { updateStatus(data.status); }, "json");
}
function updateStatus(current) {
if (current === "unverified") {
$("#status").append(".");
setTimeout(checkStatus, 3000);
}
else {
success();
}
}
function success() {
$("#status").text("Verified!");
}
</script>
</head>
<body>
<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>
<div id="verify_code" style="display: none;">
<p>Calling you now.</p>
<p>When prompted, enter the verification code:</p>
<h1 id="verification_code"></h1>
<p><strong id="status">Waiting...</strong></p>
</div>
</body>
</html>
<?php
require("database.php");
// require POST request
if ($_SERVER['REQUEST_METHOD'] != "POST") die;
$number = mysql_real_escape_string($_POST["phone_number"]);
$result = db(sprintf("select * from numbers where phone_number='%s'", $number));
$json = array();
$json["status"] = "unverified";
if($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($line["verified"] == "1") {
$json["status"] = "verified";
}
}
mysql_close();
header('Content-type: application/json');
echo(json_encode($json));
?>
<?php
require("Services/Twilio.php");
require("database.php");
$response = new Services_Twilio_Twiml();
if (empty($_POST["Digits"])) {
$gather = $response->gather(array('numDigits' => 6));
$gather->say("Please enter your verification code.");
}
else {
// grab db record and check for match
$result = db(sprintf("select * from numbers where phone_number='%s'", $_POST["Called"]));
if($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($_POST["Digits"] === $line["verification_code"]) {
db(sprintf("UPDATE numbers SET verified = 1 WHERE phone_number = '%s'", $_POST["Called"]));
$response->say("Thank you! Your phone number has been verified.");
}
else {
// if incorrect, prompt again
$gather = $response->gather(array('numDigits' => 6));
$gather->say("Verification code incorrect, please try again.");
}
}
mysql_close();
}
print $response;
?>
@narendratops
Copy link

i m no getting the prompt

@reuben98
Copy link

Help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment