Preface
Registration often need to use SMS Verification code, this article records the idea and concrete implementation.
SMS verification platform using cloud tablets, SMS verification code generation using thinkphp.
Ideas
1, the user input mobile phone number, request to obtain SMS verification code.
2, thinkphp generate SMS verification code, storage, and other parameters along with the sending of requests to cloud tablets.
3. Send SMS Verification code to the designated mobile phone number of cloud tablets.
4, the user input SMS verification code.
5, thinkphp According to the verification code is correct, the verification code is expired two conditions to determine whether the validation passed.
Code implementation
Validating interfaces
Interface Address: Https://sms.yunpian.com/v1/sms/send.json.
Using Postman, enter three required parameters Apikey, mobile, and text.
PHP Initiates HTTP/HTTPS request
Use PHP's Curl function to initiate an HTTPS request with parameters Apikey, mobile, and text.
//get SMS Verification Code Public Function Getsmscode () {//Create curl Resource $ch = Curl_init (); /Set Url$url = ' Https://sms.yunpian.com/v1/sms/send.json '; curl_setopt ($ch, Curlopt_url, $url); Set Param$paramarr = Array (' apikey ' = ' ****** ', ' mobile ' = ' ****** ', ' text ' = ' "small Sun" Your verification code is 1234 '); $param = '; foreach ($paramArr as $key = + $value) {$param. = UrlEncode ($key). ' = '. UrlEncode ($value). ' & ';} $param = substr ($param, 0, strlen ($param)-1); curl_setopt ($ch, Curlopt_postfields, $param); curl_setopt ($ch, Curlopt_ HEADER, 0); curl_setopt ($ch, Curlopt_post, 1);//curl default does not support HTTPS protocol, set non-authentication protocol curl_setopt ($ch, Curlopt_ssl_verifypeer, FALSE); curl_setopt ($ch, Curlopt_ssl_verifyhost, false); Return the transfer as a string curl_setopt ($ch, Curlopt_returntransfer, 1); $output contains the output string $output = Curl_exec ($ch); Close Curl resource to free up system resources curl_close ($CH); echo $output;}
Generate Random SMS Verification code
A four-bit random SMS verification code is generated by default.
Generate SMS Verification Code Public Function Createsmscode ($length = 4) {$min = POW ($length-1)); $max = POW ($length)-1;return ran D ($min, $max);}
Integration
Create a new table Sun_smscode in the database:
DROP TABLE IF EXISTS ' Sun_smscode '; CREATE TABLE ' Sun_smscode ' (' id ' int (8) NOT NULL auto_increment, ' mobile ' varchar (one) ' NOT null, ' code ' int (4) is not NULL, ' Crea Te_at ' datetime not NULL, ' update_at ' datetime not null,primary KEY (' id ')) engine=myisam auto_increment=3 DEFAULT charset= utf8;thinkphp code://Get SMS Verification Code Public Function Getsmscode () {//Create curl Resource $ch = Curl_init ();//Set url$url = ' https: Sms.yunpian.com/v1/sms/send.json '; curl_setopt ($ch, Curlopt_url, $url); Set param$mobile = $_post[' mobile ']; $code = $this->createsmscode (); $paramArr = Array (' apikey ' = ' ****** ', ' Mobile ' + $mobile, ' text ' + ' "little Sun" your captcha is '. $code); $param = '; foreach ($paramArr as $key + = $value) {$param. = ur Lencode ($key). ' = '. UrlEncode ($value). ' & ';} $param = substr ($param, 0, strlen ($param)-1); curl_setopt ($ch, Curlopt_postfields, $param); curl_setopt ($ch, Curlopt_ HEADER, 0); curl_setopt ($ch, Curlopt_post, 1); curl_setopt ($ch, Curlopt_ssl_verifypeer, false); Do not verify certificates under curl_setopt ($ch, curlopt_ssl_verifyhost, false); Return the transfer as a string curl_setopt ($ch, Curlopt_returntransfer, 1); $output contains the output string $output = Curl_exec ($ch); Close Curl resource to free up system resources curl_close ($CH); $outputJson = Json_decode ($output); $outputArr = Json_decode ($output, true);//echo $outputJson->code;//echo $ outputarr[' Code '];if ($outputArr [' code '] = = ' 0 ') {$data [' mobile '] = $mobile; $data [' code '] = $code; $smscode = D (' Smscode ') ); $smscodeObj = $smscode->where ("mobile= ' $mobile '")->find (), if ($SMSCODEOBJ) {$data [' update_at '] = Date (' y-m-d H:i:s '), $success = $smscode->where ("mobile= ' $mobile '")->save ($data), if ($success!== false) {$result = Array (' Code ' = ' 0 ', ' ext ' = ' Modify succeeded ', ' obj ' = $SMSCODEOBJ);} Echo Json_encode ($result, Json_unescaped_unicode);} else{$data [' create_at '] = Date (' y-m-d h:i:s '); $data [' update_at '] = $data [' Create_at '];if ($smscode->create ($data) {$id = $smscode->add (), if ($id) {$smscode _temp = $smscode->where ("id=" $id")->find (); $result = Array (' Code ' = ' 0 ', ' ext ' = ' create success ', ' obj ' = $smscode _temp); Echo Json_encode ($result, Json_unescaped_unicode);}}}}
Verify SMS Verification Code
Verify that the SMS verification code time expires and verify that the SMS verification code is correct.
Verify that the SMS verification code is valid public function Checksmscode () {$mobile = $_post[' mobile '); $code = $_post[' code ']; $nowTimeStr = Date (' y-m-d h:i:s '); $smscode = d (' Smscode '); $smscodeObj = $smscode->where ("mobile= ' $mobile '")->find (); if ($ Smscodeobj) {$smsCodeTimeStr = $smscodeObj [' Update_at ']; $recordCode = $smscodeObj [' Code ']; $flag = $this->checktime ($nowTimeStr, $SMSCODETIMESTR), if (! $flag) {$result = array (' Code ' = ' 1 ', ' ext ' = ' Verification code expires, please refresh and re-fetch '); Echo Json_ Encode ($result, json_unescaped_unicode); return;} if ($code! = $recordCode) {$result = array (' Code ' = ' 2 ', ' ext ' = ' Verification Code error, please re-enter '); Echo Json_encode ($result, Json_ Unescaped_unicode); return;} $result = Array (' Code ' = ' 0 ', ' ext ' = ' verify through '); Echo Json_encode ($result, Json_unescaped_unicode);}} Verify that the verification code time expires public Function checktime ($NOWTIMESTR, $SMSCODETIMESTR) {//$nowTimeStr = ' 2016-10-15 14:39:59 ';//$ Smscodetimestr = ' 2016-10-15 14:30:00 '; $nowTime = Strtotime ($nowTimeStr); $smsCodeTime = Strtotime ($SMSCODETIMESTR); $ Period = Floor ($nowTime-$smsCodetime)/60); 60sif ($period >=0 && $period <=20) {return true;} Else{return false;}}
Improved
In order to prevent SMS bombing, in the request to obtain SMS verification code, you need to add a picture verification code.
Thinkphp provides a function to generate a picture verification code, which we can implement to generate, refresh, and validate the captcha.
Generate and refresh picture verification codes
Get the picture verification code, refresh the picture captcha public Function Getpiccode () {$config = array (' fontSize ' =>30,//captcha font size ' length ' =>4,// Verify number of code points ' usenoise ' =>false,//Turn off captcha ' expire ' =>600); $Verify = new \think\verify ($config); $Verify->entry (2333) ;//2333 is the CAPTCHA flag}
Assuming that the corresponding URL of the function is Http://localhost/owner-bd/index.php/Home/CheckCode/getPicCode, then the address of the image verification code is the URL, which is placed in the SRC attribute of the page image tag.
Verify the Image Verification code
Verify that the CAPTCHA is correct public function Checkpiccode ($code) {$verify = new \think\verify (); if ($verify->check ($code, 2333)) {$ result = Array (' Code ' = ' 0 ', ' ext ' = ' verify passed '); Echo Json_encode ($result, Json_unescaped_unicode);} else{$result = Array (' Code ' = ' 1 ', ' ext ' = ' Verification Code error, please re-enter '); Echo Json_encode ($result, Json_unescaped_unicode);};}
In this way, we use the check method provided by thinkphp, which is very simple to implement. However, if you want to get the details of the verification, there is no way. For example, the verification code is wrong, the verification code may be timed out, possibly because the code is wrong, possibly because the code has been used and so on. When necessary, you can override the Thinkphp code class, or override the Thinkphp check method.
Run-through front and back
Back-end modification
Verify the image captcha function and change to the called function:
Public Function Checkpiccode ($picCode) {$verify = new \think\verify (); if ($verify->check ($picCode, 2333)) {return true;} Else{return false;};}
At the top of the SMS Verification code function, add the call Image verification code function, only through authentication, send the request to the cloud slice.
Get SMS Verification Code Public Function Getsmscode () {$picCode = $_post[' Piccode '];if (! $this->checkpiccode ($picCode)) {$result = Array (' Code ' = ' 1 ', ' ext ' = ' Verification Code error, please re-enter '); Echo Json_encode ($result, Json_unescaped_unicode); return;} /* Omit */}
Front-End Core code
<title>Registered</title>Register.jsangular.module (' Sunapp '). Controller (' Registercontroller ', function ($scope, $http, $ Httpparamserializer, $state, $interval) {$scope. Piccodeurl = '/owner-bd/index.php/home/checkcode/getpiccode '; $ Scope.isshow1 = true; $scope. IsShow2 = False, $scope. Btnsmstext = ' Get Verification code '; $scope. btnsmsdisabled = false; $scope. checkover = false;//Get SMS Verification Code $scope.getsmscode = function () {var param = {mobile: $scope. Mobile,piccode: $scope. Piccode}; $http ({ Method: ' POST ', url: '/owner-bd/index.php/home/sms/getsmscode ',//url: '/owner-fd/mock/common.json ', headers:{' Content-type ': ' application/x-www-form-urlencoded '},datatype: ' JSON ', data: $httpParamSerializer (param)}). Then ( function Successcallback (response) {Console.log (Response.data), if (Response.data.code = = ' 0 ') {$scope. Checkover = True ; $scope. btnsmsdisabled = True;var time = 60;var Timer = Null;timer = $interval (function () {time = time-1; $scope. Btnsmstex t = time+ ' s ', if (time = = 0) {$interval. Cancel (timer), $scope. btnsmsdisabled = false; $scope. Btnsmstext = ' regain}}, function Errorcallback (response) {console.log (response.data);}); Verify SMS Verification Code $scope.next = function () {if (! $scope. Checkover) {Console.log (' failed validation '); return;} var param = {mobile: $scope. Mobile,code: $scope. Smscode}; $http ({method: ' POST ', url: '/owner-bd/index.php/home/sms/checksmscode ',//url: '/owner-fd/mock/ Common.json ', headers:{' content-type ': ' application/x-www-form-urlencoded '},datatype: ' JSON ', data: $ Httpparamserializer (param)}). Then (function Successcallback (response) {console.log (response.data); if ( Response.data.code = = ' 0 ') {$scope. IsShow1 = false; $scope. IsShow2 = True;}}, Function Errorcallback (response) { Console.log (Response.data);}); Refresh Picture Verification Code $scope.refresh = function () {$scope. Piccodeurl = '/owner-bd/index.php/home/checkcode/getpiccode? ' +math.random ();}});
Optimization
The above code, security is not very good, we can use the tool to bypass the front-end verification. To avoid this problem, you can add session values to the Checkpiccode and Checksmscode functions to mark them.
$_session[' checkpiccode ' = true;$_session[' checksmscode '] = true;
In the final step, when adding users to the database, verify that the two session values are true, and then add them if they are true.
Results
Postscript
The code that might be useful later:
echo Json_encode ($_session);//print out the data in session Echo session_id ();//print the ID of the current session
The above is a small part of the thinkphp to introduce the implementation of SMS verification registration, we hope to have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for the support of the Scripting House website!