thinkphp implementation of SMS verification registration function _php Example

Source: Internet
Author: User
Tags curl datetime 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 Authentication 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 the Curl_setopt protocol ($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 curl_close ($ch);
Echo $output; }

Generate Random SMS Verification code

The default generates four-bit random SMS authentication code.

Generate SMS Authentication code public
function Createsmscode ($length = 4) {
$min = POW ($length-1));
$max = POW ($length)-1;
Return 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) is not NULL, ' Create_at ' datetime NOT NULL, ' UPDATE_AT ' datetime NOT NULL, PRIMARY KEY (' id ')) engine=myisam auto_increment=3 DEFAULT C
Harset=utf8; 
thinkphp code://Get SMS Authentication 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 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 the certificate with 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 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 = $s
Mscode->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_enco
De ($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, refresh after regain '); Echo Json_encode ($result, Json_unescaped_uni
CODE);
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 ' => ' validated 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 ';//$smsC
Odetimestr = ' 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 captcha public
function Getpiccode () {
$config = array (
' fontsize ' =>30,//Authenticode font size
') Length ' =>4,//Verify code digits
' usenoise ' =>false,//Close verification code clutter
' expire ' =>600
);
$Verify = new \think\verify ($config);
$Verify->entry (2333);//2333 is the verification code flag
}

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 validation code is correct public
function Checkpiccode ($code) {
$verify = new \think\verify ();
if ($verify->check ($code, 2333)) {
$result = array (
' code ' => ' 0 ',
' ext ' => ' verify pass '
);
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 Authentication 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>  

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.

Results

Postscript

Code that might be useful in the future:

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 series to introduce the thinkphp to realize the registration of SMS, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.