tp5验证码

图形验证码

登录时,没有图形验证码的话,很容被机器人进行模拟登录,对网站安全有很大的威胁。因此,验证码是登录功能所必须的。下面,我们就给我们的登录功能,加上验证码。

下面功能相关的目录
在这里插入图片描述

  1. 首先使用Composer安装think-captcha扩展包,通过命令行,进入 D:\www\phper。(您根据实际情况处理)

composer require topthink/think-captcha

若用Composer安装了验证码扩展包后,运行显示如下错误:

Fatal error: Class 'Route' not found in E:\www\vendor\topthink\think-captcha\src\helper.php on line 12*

这是由于tp5版本对应的安装包不一致导致的,5.0版本安装1.*版本的扩展包 5.1版本是用于2.0版本,tp5.0执行如下:

composer require topthink/think-captcha 1.*

若之后还是错误的依旧的时候,只能使用以下绝招了:

composer remove topthink/think-captcha
composer remove topthink/think-testing

  1. 完整安装之后,我们在 application 下的 config.php 中添加如下配置:
<?php
//配置文件:验证码的配置必须加到 applocation 下面的config 中才可以准确的控制。
return [
	
	'captcha'  => [
			// 验证码字符集合
			'codeSet'  => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
			// 验证码字体大小(px)
			'fontSize' => 25,
			// 是否画混淆曲线
			'useCurve' => true,
			// 验证码图片高度
			'imageH'   => 30,
			// 验证码图片宽度
			'imageW'   => 100,
			// 验证码位数
			'length'   => 5,
			// 验证成功后是否重置
			'reset'    => true
	]
];

  1. 在登录页面中,index\view\login\index.html 中,密码下面,加入如下的代码:
<!--注意此处的代码: onclick="javascript:this.src='{:captcha_src()}?tm='+Math.random();" 段代码是用来完成,点击验证码图案,换一个验证码的功能。-->

<div class="form-group">
   <label>验证码</label>
   <input type="text" placeholder="请输入验证码" class="form-control" name="captcha">
   <img src="{:captcha_src()}" alt="captcha" onclick="javascript:this.src='{:captcha_src()}?tm='+Math.random();" style="cursor: pointer"/>
</div>

若找不到图片,路径报错:'控制器不存在:Captcha’或者图片不显示,请如下操作:
1.请检查路由url_route_on 设置是否开启了true
2.vendor/topthink/think-captcha/src/captchaController.php、index()方法加入ob_clean()函数

4.然后修改 doLogin 方法,添加验证码验证的处理。首先我们要在 Login.php 的开的头加入:

use think\captcha;

5.控制器 captcha_check 验证码检测,才能正确的使用。

// 处理登录逻辑
   public function doLogin()
   {
   	$param = input('post.');
   	if(empty($param['user_name'])){
   		
   		$this->error('用户名不能为空');
   	}
   	
   	if(empty($param['user_pwd'])){
   		
   		$this->error('密码不能为空');
   	}
   	
   	if(empty($param['captcha'])){
   		
   		$this->error('验证码不能为空');
   	}
   	
   	// 处理验证码
   	if(!captcha_check($param['captcha'])){
			
   		$this->error('验证码错误');
   	};
   	
   	// 验证用户名
   	$has = db('users')->where('user_name', $param['user_name'])->find();
   	if(empty($has)){
   		
   		$this->error('用户名密码错误');
   	}
   	
   	// 验证密码
   	if($has['user_pwd'] != md5($param['user_pwd'])){
   		
   		$this->error('用户名密码错误');
   	}
   	
   	// 记录用户登录信息
   	cookie('user_id', $has['id'], 3600);  // 一个小时有效期
   	cookie('user_name', $has['user_name'], 3600);
   	
   	$this->redirect(url('index/index'));
   }

  1. 验证码添加成功
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35311094/article/details/85942556