Home Backend Development PHP Tutorial Thinkphp method to implement SMS verification registration function

Thinkphp method to implement SMS verification registration function

May 31, 2018 pm 02:39 PM
php thinkphp register

The registration function is a must-have function for many websites. If you have the registration function, you must have an SMS verification code. This article will share with you how thinkphp implements the SMS verification registration function. Friends who are interested should take a look.

Preface

SMS verification codes are often needed when registering. This article records the ideas and specific implementation.

The SMS verification platform uses Yunpian, and the generation of SMS verification codes uses thinkphp.

Ideas

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

2. Thinkphp generates the SMS verification code, stores it, and sends the request to Yunpian together with other parameters.

3. Yunpian sends a text message verification code to the designated mobile phone number.

4. The user enters the SMS verification code.

5. thinkphp determines whether the verification is passed based on two conditions: whether the verification code is correct and whether the verification code has expired.

Code implementation

Verification interface

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

Use postman and enter the three necessary parameters apikey, mobile and text.

php initiates an http/https request

Use php's curl function to initiate an https request and bring in Parameters apikey, mobile and text.

// 获取短信验证码
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' => '【小太阳】您的验证码是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默认不支持https协议,设置不验证协议
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;
}
Copy after login

Generate a random SMS verification code

Generates a four-digit random SMS verification code by default code.

// 生成短信验证码
public function createSMSCode($length = 4){
$min = pow(10 , ($length - 1));
$max = pow(10, $length) - 1;
return rand($min, $max);
}
Copy after login

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(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代码:
// 获取短信验证码
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' => '【小太阳】您的验证码是'.$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); //不验证证书下同
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' => '修改成功',
'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'=> '创建成功',
'obj'=>$smscode_temp
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
}
}
}
}
Copy after login

Verify SMS verification code

Verify whether the SMS verification code time has expired, and verify whether the SMS verification code is correct.

// 验证短信验证码是否有效
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' => '验证码过期,请刷新后重新获取'
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
return;
}
if($code != $recordCode){
$result = array(
'code' => '2',
'ext' => '验证码错误,请重新输入'
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
return;
}
$result = array(
'code' => '0',
'ext' => '验证通过'
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
}
// 验证验证码时间是否过期
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;
}
}
Copy after login

Improvement

In order to prevent SMS bombing, you need to add an image verification code when requesting an SMS verification code.

thinkphp provides a function to generate image verification codes. Let's implement the generation, refresh and verification of verification codes.

Generate and refresh image verification code

// 获取图片验证码,刷新图片验证码
public function getPicCode(){
$config = array(
&#39;fontSize&#39;=>30, // 验证码字体大小
&#39;length&#39;=>4, // 验证码位数
&#39;useNoise&#39;=>false, // 关闭验证码杂点
&#39;expire&#39;=>600
);
$Verify = new \Think\Verify($config);
$Verify->entry(2333);//2333是验证码标志
}
Copy after login

Assume, the corresponding url of this function It is http://localhost/owner-bd/index.php/Home/CheckCode/getPicCode. Then, the address of the image verification code is this URL, and it can be put into the src attribute of the page image tag.

Verification image verification code

// 验证验证码是否正确
public function checkPicCode($code){
$verify = new \Think\Verify();
if($verify->check($code, 2333)){
$result = array(
&#39;code&#39; => &#39;0&#39;,
&#39;ext&#39; => &#39;验证通过&#39;
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}else{
$result = array(
&#39;code&#39; => &#39;1&#39;,
&#39;ext&#39; => &#39;验证码错误,请重新输入&#39;
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
};
}
Copy after login

For the above method, we used the one provided by thinkphp The check method is very simple to implement. However, if you want to get verification details, there is no other way. For example, if the verification code is wrong, the verification code may have timed out, the verification code may have been entered incorrectly, the verification code may have been used, etc. When necessary, you can rewrite thinkphp's verification code class, or rewrite thinkphp's check method.

Run through the front-end and back-end

Back-end modification

The verification image verification code function is changed to the called function:

public function checkPicCode($picCode){
$verify = new \Think\Verify();
if($verify->check($picCode, 2333)){
return true;
}else{
return false;
};
}
Copy after login

At the top of the function to get the SMS verification code, add the function to call the image verification code. Only after passing the verification will the request be sent to Yunpian.

// 获取短信验证码
public function getSMSCode(){
$picCode = $_POST[&#39;picCode&#39;];
if(!$this->checkPicCode($picCode)){
$result = array(
&#39;code&#39; => &#39;1&#39;,
&#39;ext&#39; => &#39;验证码错误,请重新输入&#39;
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
return;
}
/*省略*/
}
Copy after login

Front-end core code

<!--register.html-->
<!DOCTYPE html>
<html lang="zh" ng-app="sunApp">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body ng-controller="registerController">
<form action="" class="register-form" ng-show="isShow1">
<p class="input-group">
<input type="text" class="mobile" ng-model="mobile" placeholder="手机号">
</p>
<p class="input-group">
<input type="text" class="pic-code" ng-model="picCode" placeholder="图片验证码">
<img class="img" src="{{picCodeUrl}}" alt="" ng-click="refresh()">
</p>
<p class="input-group">
<input type="text" class="sms-code" ng-model="SMSCode" placeholder="短信验证码">
<button class="btn-sms" ng-click="getSMSCode()" ng-disabled="btnSMSDisabled">{{btnSMSText}}</button>
</p>
<button class="confirm-btn" ng-click="next()">下一步</button>
</form>
<form action="" class="register-form" ng-show="isShow2">
<p class="input-group">
<input type="text" class="mobile" ng-model="mobile" placeholder="手机号" disabled="true">
</p>
<p class="input-group">
<input type="password" class="password" ng-model="password" placeholder="请输入密码">
<input type="password" class="password" ng-model="password2" placeholder="请再次输入密码">
</p>
<button class="confirm-btn" ng-click="getSMSCode()">注册</button>
</form>
</body>
</html>
// register.js
angular.module(&#39;sunApp&#39;).controller(&#39;registerController&#39;, function ($scope,$http,$httpParamSerializer,$state,$interval) { 
$scope.picCodeUrl = &#39;/owner-bd/index.php/Home/CheckCode/getPicCode&#39;;
$scope.isShow1 = true;
$scope.isShow2 = false;
$scope.btnSMSText = &#39;获取验证码&#39;;
$scope.btnSMSDisabled = false;
$scope.checkOver = false;
// 获取短信验证码
$scope.getSMSCode = function(){
var param = {
mobile: $scope.mobile,
picCode: $scope.picCode
};
$http({
method:&#39;POST&#39;,
url:&#39;/owner-bd/index.php/Home/SMS/getSMSCode&#39;,
//url: &#39;/owner-fd/mock/common.json&#39;,
headers:{
&#39;Content-Type&#39;:&#39;application/x-www-form-urlencoded&#39;
},
dataType: &#39;json&#39;,
data: $httpParamSerializer(param)
}).then(function successCallback(response) {
console.log(response.data);
if(response.data.code == &#39;0&#39;){
$scope.checkOver = true;
$scope.btnSMSDisabled = true;
var time = 60;
var timer = null;
timer = $interval(function(){
time = time - 1;
$scope.btnSMSText = time+&#39;秒&#39;;
if(time == 0) {
$interval.cancel(timer);
$scope.btnSMSDisabled = false;
$scope.btnSMSText = &#39;重新获取&#39;;
}
}, 1000);
}
}, function errorCallback(response) {
console.log(response.data);
});
}
// 验证短信验证码
$scope.next = function(){
if(!$scope.checkOver){
console.log(&#39;未通过验证&#39;);
return;
}
var param = {
mobile: $scope.mobile,
code: $scope.SMSCode
};
$http({
method:&#39;POST&#39;,
url:&#39;/owner-bd/index.php/Home/SMS/checkSMSCode&#39;,
//url: &#39;/owner-fd/mock/common.json&#39;,
headers:{
&#39;Content-Type&#39;:&#39;application/x-www-form-urlencoded&#39;
},
dataType: &#39;json&#39;,
data: $httpParamSerializer(param)
}).then(function successCallback(response) {
console.log(response.data);
if(response.data.code == &#39;0&#39;){
$scope.isShow1 = false;
$scope.isShow2 = true;
}
}, function errorCallback(response) {
console.log(response.data);
});
}
// 刷新图片验证码
$scope.refresh = function(){
$scope.picCodeUrl = &#39;/owner-bd/index.php/Home/CheckCode/getPicCode?&#39;+Math.random();
}
});
Copy after login

##Optimization

The security of the above code is not very good. We can use tools to bypass front-end verification. In order to avoid this problem, you can add session value to mark in the checkPicCode and checkSMSCode functions.

$_SESSION[&#39;checkPicCode&#39;] = true;
$_SESSION[&#39;checkSMSCode&#39;] = true;
Copy after login

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

Results

Postscript


Codes that may be useful in the future:

echo json_encode($_SESSION);// 打印出session中的数据
echo session_id();// 打印当前session的id
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of the implementation steps of in_array implicit conversion in PHP

PHP detailed explanation of the heap sort algorithm

phpWhat are the methods to read local json files

The above is the detailed content of Thinkphp method to implement SMS verification registration function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles