thinkphp SMS Verification Registration Example

Source: Internet
Author: User
Tags foreach curl datetime json pow strlen urlencode

Objective
Registration often need to use the SMS Verification code, this article records the idea and concrete implementation.
SMS verification platform using cloud, SMS authentication code generation using thinkphp.

Ideas
1, the user enters the handset number, requests obtains the short message authentication code.
2, thinkphp generated SMS authentication code, storage, and other parameters to send requests to the cloud.
3. Send SMS Verification code to the designated mobile phone number.
4, user input text message verification code.
5, thinkphp based on the correctness of the verification Code, the verification code is expired two conditions to determine whether the validation pass.

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 HTTPS requests 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 ' => ' Hu Jintao ',
' Mobile ' => ' Hu Jintao ',
' Text ' => ' "little 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 does not support HTTPS protocol by default, setting does not validate 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
The default generates four-bit random SMS authentication code.

Generate SMS Verification Code
Public Function Createsmscode ($length = 4) {
$min = POW ($length-1));
$max = POW ($length)-1;
Return to Rand ($min, $max);
}
Integration
New Table Sun_smscode in 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) not NULL,
' Create_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 = $thi S->createsmscode ();
    $paramArr = Array (
        ' apikey ' => '),
        ' mobile ' => $mobile,
        ' Text ' => ' "little Sun" Your verification code is '. $code
   );
    $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_setopt ($ch, Curlopt_ssl_verifypeer, false); Do not verify certificate
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 ' => ' modified successfully ',
' 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 the short message verification code time expires, verify that the text message 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 retrieve '
);
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 ' => ' verification 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); 60s
if ($period >=0 && $period <=20) {
return true;
}else{
return false;
}
}
Improved
In order to prevent SMS bombing, in the request to obtain the SMS authentication code, the need to add a picture verification code.

Thinkphp provides a function to generate a picture verification code, below we implement the validation code generation, refresh, and validation.

Generate and refresh picture Verification code
Get picture verification code, refresh picture Verification code
Public Function Getpiccode () {
$config = Array (
' FontSize ' =>30,//Verify code font Size
' Length ' =>4,//Verify code digits
' Usenoise ' =>false,//Close Verification code miscellaneous points
' Expire ' =>600
);
$Verify = new \think\verify ($config);
$Verify->entry (2333);//2333 is a verification code mark
}
Assuming that the corresponding URL for the function is Http://localhost/owner-bd/index.php/Home/CheckCode/getPicCode, then the image verification code address is this URL, put the page picture label SRC attribute.

Verifying Picture Verification Code
Verify that the verification code is correct
Public Function Checkpiccode ($code) {
$verify = new \think\verify ();
if ($verify->check ($code, 2333)) {
$result = Array (
' Code ' => ' 0 ',
' Ext ' => ' verify through '
);
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 take advantage of the check method provided by thinkphp, which is simple to implement. However, if you want to get the details of the verification, there is no way. For example, the verification code error, may verify the code timeout, possibly because the input verification code error, possibly because the verification code has been used, and so on. When necessary, you can override the thinkphp validation code class, or rewrite the thinkphp check method.

Run through front and back
Back-end modifications
Verify the picture validation code 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;
};
}
To get the top of the SMS Verification code function, add the call Picture validation code function, only by verifying that the request is sent 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
<!--register.html-->
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title> Registration </title>
<body ng-controller= "Registercontroller" >
<form action= "" class= "Register-form" ng-show= "IsShow1" >
<div class= "Input-group" >
<input type= "text" class= "mobile" ng-model= "mobile" placeholder= "cell phone number" >
</div>
<div class= "Input-group" >
<input type= "text" class= "Pic-code" ng-model= "Piccode" placeholder= "Picture Verification Code" >
&LT;IMG class= "img" src= "{{piccodeurl}}" alt= "ng-click=" Refresh () ">
</div>
<div class= "Input-group" >
<input type= "text" class= "Sms-code" ng-model= "Smscode" placeholder= "SMS Authentication Code" >
<button class= "btn-sms" ng-click= "Getsmscode ()" ng-disabled= "btnsmsdisabled" >{{btnSMSText}}</button>
</div>
<button class= "confirm-btn" ng-click= "Next ()" > Next </button>
</form>

<form action= "" class= "Register-form" ng-show= "IsShow2" >
<div class= "Input-group" >
<input type= "text" class= "mobile" ng-model= "mobile" placeholder= "phone number" disabled= "true" >
</div>
<div class= "Input-group" >
<input type= "password" class= "password" ng-model= "password" placeholder= "Please enter password" >
<input type= "password" class= "password" ng-model= "password2" placeholder= "Please enter password again" >
</div>
<button class= "confirm-btn" ng-click= "Getsmscode ()" > Registration </button>
</form>
</body>
Register.js
Angular.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 = ' obtain authentication 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. Btnsmstext = time+ ' sec ';
if (time = 0) {
$interval. Cancel (timer);
$scope. btnsmsdisabled = false;
$scope. Btnsmstext = ' re-acquisition ';
}
}, 1000);
}
}, function Errorcallback (response) {
Console.log (Response.data);
});
}

Verify SMS Verification Code
$scope. Next = function () {
if (! $scope. Checkover) {
Console.log (' failed to pass 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 validation. To avoid this problem, you can add a session value to the Checkpiccode and Checksmscode functions to mark it.

$_session[' Checkpiccode '] = true;
$_session[' Checksmscode '] = true;
In the final step, when you add a user to the database, verify that the two session values are true and are added when you are true.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.