Thinkphp implements text message verification and registration, and thinkphp text message

Source: Internet
Author: User
Tags urlencode

Thinkphp implements text message verification and registration, and thinkphp text message

Preface

Text message verification codes are often used during registration. This article records the ideas and implementation.

The text message verification platform uses cloud tablets, and the text message verification code is generated using thinkphp.

Ideas

1. the user enters the mobile phone number and requests to obtain the SMS verification code.

2. thinkphp generates a text message verification code, stores it, and sends a request to the cloud disk together with other parameters.

3. Send the SMS verification code to the specified mobile phone number.

4. Enter the text message verification code.

5. thinkphp checks whether the verification is successful Based on the Verification Code and whether the verification code expires.

Code Implementation

Verification Interface

Interface address: https://sms.yunpian.com/v1/sms/send.json.

Use postman to enter three required parameters: apikey, mobile, and text.

Php initiates http/https requests

Use the php curl function to initiate https requests and include the apikey, mobile, and text parameters.

// Obtain the 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' => '[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); // by default, curl does not support https. Set the unverified 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 a random SMS Verification Code

Four random SMS verification codes are generated by default.

// Generate the SMS verification code public function createSMSCode ($ length = 4) {$ min = pow (10, ($ length-1); $ max = pow (10, $ length) -1; return rand ($ min, $ max );}

Integration

Create a 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 (11) 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 the 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' => '[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 resources c Url_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 = '$ mo Bile '")-> save ($ data); if ($ success! = False) {$ result = array ('code' => '0', 'text' => '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', 'text' => 'created successfully ', 'obj' => $ smscode_temp ); echo json_encode ($ result, JSON_UNESCAPED_UNICODE );}}}}}

Verify SMS Verification Code

Verify that the SMS verification code expires and that the SMS verification code is correct.

// Verify whether 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', 'text' => 'verification code expired. Please refresh it and obtain it again '); echo json_encode ($ result, JSON_UNESCAPED_UNICODE); return;} if ($ code! = $ RecordCode) {$ result = array ('code' => '2', 'text' => 'verification code error, please input it again '); echo json_encode ($ result, JSON_UNESCAPED_UNICODE); return ;}$ result = array ('code' => '0', 'text' => 'verified pass'); echo json_encode ($ result, JSON_UNESCAPED_UNICODE) ;}// check whether the verification code time has expired public function checkTime ($ nowTimeStr, $ smsCodeTimeStr) {// $ nowTimeStr = '2017-10-15 14:39:59 '; // $ smsCodeTimeStr = '2017-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 ;}}

Improvement

To prevent SMS bombing, you must add an image verification code when requesting to obtain the SMS verification code.

Thinkphp provides a function for generating image verification codes. The following describes how to generate, refresh, and verify the verification codes.

Generate and refresh the image Verification Code

// Obtain the image verification code and refresh the image verification code public function getPicCode () {$ config = array ('fontsize' => 30, // The Verification Code font size 'length' => 4, // The number of digits of the Verification Code 'usenoise '=> false, // close the verification code miscellaneous 'expire' => 600); $ Verify = new \ Think \ Verify ($ config ); $ Verify-> entry (2333); // 2333 indicates the verification code}

Assume 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 image Verification Code

// Verify whether the verification code is correct. public function checkPicCode ($ code) {$ Verify = new \ Think \ verify (); if ($ verify-> check ($ code, 2333 )) {$ result = array ('code' => '0', 'text' => 'verification passed'); echo json_encode ($ result, JSON_UNESCAPED_UNICODE );} else {$ result = array ('code' => '1', 'text' => 'verification code error, please input it again '); echo json_encode ($ result, JSON_UNESCAPED_UNICODE );};}

In the above method, we use the check method provided by thinkphp to implement it very easily. However, if you want to obtain the verification details, there is no way. For example, if the verification code is incorrect, the verification code may have timed out, or the verification code may have been used. If necessary, you can rewrite the verification code class of thinkphp or the check Method of thinkphp.

Frontend and backend

Backend Modification

Verify the image verification code function and change it 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 function for obtaining the SMS verification code, add and call the image verification code function to send a request to the cloud.

// Obtain the SMS verification code public function getSMSCode () {$ picCode =$ _ POST ['piccode']; if (! $ This-> checkPicCode ($ picCode) {$ result = array ('code' => '1', 'text' => 'verification code error, please input it again '); echo json_encode ($ result, JSON_UNESCAPED_UNICODE); return;}/* omitted */}

Core front-end code

<! --Register.html --> <! DOCTYPE html> 

Optimization

The above code is not safe. We can use tools to bypass front-end verification. To avoid this problem, you can add the session value to the checkPicCode and checkSMSCode functions.

$_SESSION['checkPicCode'] = true;$_SESSION['checkSMSCode'] = true;

In the last step, when adding a user to the database, verify whether the two session values are both true and then add them if they are both true.

Results

Postscript

Code that may be useful in the future:

Echo json_encode ($ _ SESSION); // print the data in the session echo session_id (); // print the id of the current session

The above is a small series of Thinkphp text message verification registration, hope to help you, if you have any questions, please leave a message, the small series will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.