The registration function is a required function for many websites. if you have a registration function, you must have a text message verification code. This article will share with you thinkphp's text message verification registration function. if you are interested, let's take a look.
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_se Topt ($ 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 curl_close ($ ch); // $ outputJson = jso N_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', '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// 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 the 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 + 'second'; if (time = 0) {$ interval. cancel (timer); $ scope. btnSMSDisabled = false; $ scope. btnSMSText = 'reget' ;}}, 1000) ;}, function errorCallback (response) {console. log (response. data) ;}) ;}// verify the SMS verification code $ scope. next = function () {if (! $ Scope. checkOver) {console. log ('verification not passed '); 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 (respons E. data. code = '0') {$ scope. isShow1 = false; $ scope. isShow2 = true ;}}, function errorCallback (response) {console. log (response. data) ;}) ;}// refresh the image verification code $ scope. refresh = function () {$ scope. picCodeUrl = '/owner-bd/index. php/Home/CheckCode/getPicCode? '+ Math. random ();}});
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. I would like to thank you for your support for the script home website!