public
Last active

Twilio SMS Verification Example

  • Download Gist
database.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php
$db_host='dbserver';
$db_name='dbame';
$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;
}
?>
dbschema.sql
SQL
1 2 3 4 5 6 7
-- Create syntax for 'numbers'
 
CREATE TABLE `numbers` (
`phone_number` varchar(50) DEFAULT NULL,
`verification_code` int(11) DEFAULT NULL,
`verified` bit(1) NOT NULL DEFAULT b'0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1
index.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<!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 via SMS by Twilio</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<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>
</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>
<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>
</body>
</html>
sms.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php
$db_host='dbserver';
$db_name='dbame';
$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;
}
?>
status.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?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);
?>
twilio.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
<?php
/*
Copyright (c) 2009 Twilio, Inc.
 
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
 
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
// VERSION: 2.0.5
// Twilio REST Helpers
// ========================================================================
// ensure Curl is installed
if(!extension_loaded("curl"))
throw(new Exception(
"Curl extension is required for TwilioRestClient to work"));
/*
* TwilioRestResponse holds all the REST response data
* Before using the reponse, check IsError to see if an exception
* occurred with the data sent to Twilio
* ResponseXml will contain a SimpleXml object with the response xml
* ResponseText contains the raw string response
* Url and QueryString are from the request
* HttpStatus is the response code of the request
*/
class TwilioRestResponse {
public $ResponseText;
public $ResponseXml;
public $HttpStatus;
public $Url;
public $QueryString;
public $IsError;
public $ErrorMessage;
public function __construct($url, $text, $status) {
preg_match('/([^?]+)\??(.*)/', $url, $matches);
$this->Url = $matches[1];
$this->QueryString = $matches[2];
$this->ResponseText = $text;
$this->HttpStatus = $status;
if($this->HttpStatus != 204)
$this->ResponseXml = @simplexml_load_string($text);
if($this->IsError = ($status >= 400))
$this->ErrorMessage =
(string)$this->ResponseXml->RestException->Message;
}
}
/* TwilioRestClient throws TwilioException on error
* Useful to catch this exception separately from general PHP
* exceptions, if you want
*/
class TwilioException extends Exception {}
/*
* TwilioRestBaseClient: the core Rest client, talks to the Twilio REST
* API. Returns a TwilioRestResponse object for all responses if Twilio's
* API was reachable Throws a TwilioException if Twilio's REST API was
* unreachable
*/
class TwilioRestClient {
 
protected $Endpoint;
protected $AccountSid;
protected $AuthToken;
/*
* __construct
* $username : Your AccountSid
* $password : Your account's AuthToken
* $endpoint : The Twilio REST Service URL, currently defaults to
* the proper URL
*/
public function __construct($accountSid, $authToken,
$endpoint = "https://api.twilio.com") {
$this->AccountSid = $accountSid;
$this->AuthToken = $authToken;
$this->Endpoint = $endpoint;
}
/*
* sendRequst
* Sends a REST Request to the Twilio REST API
* $path : the URL (relative to the endpoint URL, after the /v1)
* $method : the HTTP method to use, defaults to GET
* $vars : for POST or PUT, a key/value associative array of data to
* send, for GET will be appended to the URL as query params
*/
public function request($path, $method = "GET", $vars = array()) {
$fp = null;
$tmpfile = "";
$encoded = "";
foreach($vars AS $key=>$value)
$encoded .= "$key=".urlencode($value)."&";
$encoded = substr($encoded, 0, -1);
// construct full url
$url = "{$this->Endpoint}/$path";
// if GET and vars, append them
if($method == "GET")
$url .= (FALSE === strpos($path, '?')?"?":"&").$encoded;
 
// initialize a new curl object
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
switch(strtoupper($method)) {
case "GET":
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
break;
case "POST":
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
break;
case "PUT":
// curl_setopt($curl, CURLOPT_PUT, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
file_put_contents($tmpfile = tempnam("/tmp", "put_"),
$encoded);
curl_setopt($curl, CURLOPT_INFILE, $fp = fopen($tmpfile,
'r'));
curl_setopt($curl, CURLOPT_INFILESIZE,
filesize($tmpfile));
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
throw(new TwilioException("Unknown method $method"));
break;
}
// send credentials
curl_setopt($curl, CURLOPT_USERPWD,
$pwd = "{$this->AccountSid}:{$this->AuthToken}");
// do the request. If FALSE, then an exception occurred
if(FALSE === ($result = curl_exec($curl)))
throw(new TwilioException(
"Curl failed with error " . curl_error($curl)));
// get result code
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// unlink tmpfiles
if($fp)
fclose($fp);
if(strlen($tmpfile))
unlink($tmpfile);
return new TwilioRestResponse($url, $result, $responseCode);
}
}
// Twiml Response Helpers
// ========================================================================
/*
* Verb: Base class for all TwiML verbs used in creating Responses
* Throws a TwilioException if an non-supported attribute or
* attribute value is added to the verb. All methods in Verb are protected
* or private
*/
class Verb {
private $tag;
private $body;
private $attr;
private $children;
/*
* __construct
* $body : Verb contents
* $body : Verb attributes
*/
function __construct($body=NULL, $attr = array()) {
if (is_array($body)) {
$attr = $body;
$body = NULL;
}
$this->tag = get_class($this);
$this->body = $body;
$this->attr = array();
$this->children = array();
self::addAttributes($attr);
}
/*
* addAttributes
* $attr : A key/value array of attributes to be added
* $valid : A key/value array containging the accepted attributes
* for this verb
* Throws an exception if an invlaid attribute is found
*/
private function addAttributes($attr) {
foreach ($attr as $key => $value) {
if(in_array($key, $this->valid))
$this->attr[$key] = $value;
else
throw new TwilioException($key . ', ' . $value .
" is not a supported attribute pair");
}
}
 
/*
* append
* Nests other verbs inside self.
*/
function append($verb) {
if(is_null($this->nesting))
throw new TwilioException($this->tag ." doesn't support nesting");
else if(!is_object($verb))
throw new TwilioException($verb->tag . " is not an object");
else if(!in_array(get_class($verb), $this->nesting))
throw new TwilioException($verb->tag . " is not an allowed verb here");
else {
$this->children[] = $verb;
return $verb;
}
}
/*
* set
* $attr : An attribute to be added
* $valid : The attrbute value for this verb
* No error checking here
*/
function set($key, $value){
$this->attr[$key] = $value;
}
/* Convenience Methods */
function addSay($body=NULL, $attr = array()){
return self::append(new Say($body, $attr));
}
function addPlay($body=NULL, $attr = array()){
return self::append(new Play($body, $attr));
}
function addDial($body=NULL, $attr = array()){
return self::append(new Dial($body, $attr));
}
function addNumber($body=NULL, $attr = array()){
return self::append(new Number($body, $attr));
}
function addGather($attr = array()){
return self::append(new Gather($attr));
}
function addRecord($attr = array()){
return self::append(new Record(NULL, $attr));
}
function addHangup(){
return self::append(new Hangup());
}
function addRedirect($body=NULL, $attr = array()){
return self::append(new Redirect($body, $attr));
}
function addPause($attr = array()){
return self::append(new Pause($attr));
}
function addConference($body=NULL, $attr = array()){
return self::append(new Conference($body, $attr));
}
function addSms($body=NULL, $attr = array()){
return self::append(new Sms($body, $attr));
}
/*
* write
* Output the XML for this verb and all it's children
* $parent: This verb's parent verb
* $writeself : If FALSE, Verb will not output itself,
* only its children
*/
protected function write($parent, $writeself=TRUE){
if($writeself) {
$elem = $parent->addChild($this->tag, $this->body);
foreach($this->attr as $key => $value)
$elem->addAttribute($key, $value);
foreach($this->children as $child)
$child->write($elem);
} else {
foreach($this->children as $child)
$child->write($parent);
}
}
}
class Response extends Verb {
private $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response></Response>";
protected $nesting = array('Say', 'Play', 'Gather', 'Record',
'Dial', 'Redirect', 'Pause', 'Hangup', 'Sms');
function __construct(){
parent::__construct(NULL);
}
function Respond($sendHeader = true) {
// try to force the xml data type
// this is generally unneeded by Twilio, but nice to have
if($sendHeader)
{
if(!headers_sent())
{
header("Content-type: text/xml");
}
}
$simplexml = new SimpleXMLElement($this->xml);
$this->write($simplexml, FALSE);
print $simplexml->asXML();
}
function asURL($encode = TRUE){
$simplexml = new SimpleXMLElement($this->xml);
$this->write($simplexml, FALSE);
if($encode)
return urlencode($simplexml->asXML());
else
return $simplexml->asXML();
}
}
class Say extends Verb {
protected $valid = array('voice','language','loop');
}
class Play extends Verb {
protected $valid = array('loop');
}
class Record extends Verb {
protected $valid = array('action','method','timeout','finishOnKey',
'maxLength','transcribe','transcribeCallback');
}
class Dial extends Verb {
protected $valid = array('action','method','timeout','hangupOnStar',
'timeLimit','callerId');
protected $nesting = array('Number','Conference');
}
class Redirect extends Verb {
protected $valid = array('method');
}
class Pause extends Verb {
protected $valid = array('length');
function __construct($attr = array()) {
parent::__construct(NULL, $attr);
}
}
class Hangup extends Verb {
function __construct() {
parent::__construct(NULL, array());
}
}
class Gather extends Verb {
protected $valid = array('action','method','timeout','finishOnKey',
'numDigits');
protected $nesting = array('Say', 'Play', 'Pause');
function __construct($attr = array()){
parent::__construct(NULL, $attr);
}
}
class Number extends Verb {
protected $valid = array('url','sendDigits');
}
class Conference extends Verb {
protected $valid = array('muted','beep','startConferenceOnEnter',
'endConferenceOnExit','waitUrl','waitMethod');
}
class Sms extends Verb {
protected $valid = array('to', 'from', 'action', 'method', 'statusCallback');
}
// Twilio Utility function and Request Validation
// ========================================================================
class TwilioUtils {
protected $AccountSid;
protected $AuthToken;
function __construct($id, $token){
$this->AuthToken = $token;
$this->AccountSid = $id;
}
public function validateRequest($expected_signature, $url, $data = array()) {
// sort the array by keys
ksort($data);
// append them to the data string in order
// with no delimiters
foreach($data AS $key=>$value)
$url .= "$key$value";
 
// This function calculates the HMAC hash of the data with the key
// passed in
// Note: hash_hmac requires PHP 5 >= 5.1.2 or PECL hash:1.1-1.5
// Or http://pear.php.net/package/Crypt_HMAC/
$calculated_signature = base64_encode(hash_hmac("sha1",$url, $this->AuthToken, true));
return $calculated_signature == $expected_signature;
}
}
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.