Thinkphp method of realizing registration function of SMS Verification

Source: Internet
Author: User
Tags urlencode
Registration function is a lot of Web site must do features, there is a registration function will have SMS verification code, this article to share the thinkphp implementation of SMS Verification registration function, interested friends to see together

Objective

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.co M/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

<!--register.html--><! DOCTYPE html>

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

Summary: The above is the entire content of this article, I hope to be able to help you learn.

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.