本文目录导读:

在ThinkPHP框架中,验证码的生成和使用主要通过think\captcha扩展包实现,下面是完整的使用指南:
安装验证码扩展包
composer require topthink/think-captcha
配置验证码
1 默认配置(config/captcha.php)
<?php
return [
// 验证码字符集合
'codeSet' => '2345678abcdefhjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ',
// 验证码字体大小(px)
'fontSize' => 25,
// 是否画混淆曲线
'useCurve' => true,
// 验证码图片高度
'imageH' => 0,
// 验证码图片宽度
'imageW' => 0,
// 验证码位数
'length' => 4,
// 验证成功后是否重置
'reset' => true
];
2 自定义配置
在config/captcha.php中自定义配置参数:
return [
'codeSet' => 'abc123456',
'fontSize' => 20,
'useCurve' => false,
'useNoise' => true, // 是否添加杂点
'imageH' => 60,
'imageW' => 200,
'length' => 5,
'bg' => [243, 251, 254], // 背景颜色
];
后端生成验证码
1 控制器方法
<?php
namespace app\index\controller;
use think\Controller;
use think\captcha\Captcha;
class Login extends Controller
{
/**
* 生成验证码
*/
public function verify()
{
$captcha = new Captcha();
// 可以在这里设置验证码配置
$captcha->fontSize = 25;
$captcha->length = 4;
$captcha->useNoise = true;
// 生成并输出验证码
return $captcha->entry();
}
/**
* 登录处理
*/
public function checkLogin()
{
$code = input('post.code');
if (!captcha_check($code)) {
$this->error('验证码错误');
}
// 验证通过,继续处理登录逻辑
// ...
}
}
2 使用助手函数
// 直接输出验证码
public function verify()
{
return captcha();
}
// 或者指定配置
public function verify()
{
return captcha('config1'); // 使用config1配置
}
前端显示验证码
1 HTML代码
<!-- 基础显示 -->
<div class="form-group">
<label>验证码:</label>
<input type="text" name="code" placeholder="请输入验证码">
<img src="{:url('index/login/verify')}" alt="验证码"
onclick="this.src='{:url('index/login/verify')}?time='+Math.random()"
id="captcha_img">
</div>
2 点击刷新验证码
<script>
$(document).ready(function() {
$('#captcha_img').click(function() {
var url = "{:url('index/login/verify')}";
url += '?time=' + new Date().getTime();
$(this).attr('src', url);
});
});
// 或者使用更简洁的写法
function refreshCaptcha() {
document.getElementById('captcha_img').src =
"{:url('index/login/verify')}?time=" + Math.random();
}
</script>
验证码验证
1 使用助手函数验证
// 控制器中验证
public function login()
{
if(request()->isPost()){
$data = input('post.');
// 第一种验证方式:助手函数
if(!captcha_check($data['code'])){
return json(['code'=>0, 'msg'=>'验证码错误']);
}
// 第二种验证方式:手动验证
$captcha = new Captcha();
if(!$captcha->check($data['code'])){
return json(['code'=>0, 'msg'=>'验证码错误']);
}
// 验证通过,处理登录逻辑
// ...
}
}
2 使用验证器验证
// 创建验证器类(app/validate/Login.php)
namespace app\validate;
use think\Validate;
class Login extends Validate
{
protected $rule = [
'username' => 'require',
'password' => 'require',
'code' => 'require|captcha',
];
protected $message = [
'username.require' => '用户名不能为空',
'password.require' => '密码不能为空',
'code.require' => '验证码不能为空',
'code.captcha' => '验证码不正确',
];
}
// 控制器中使用验证器
public function login()
{
if(request()->isPost()){
$data = input('post.');
$validate = Validate::rule([
'username' => 'require',
'password' => 'require',
'code' => 'require|captcha',
]);
if(!$validate->check($data)){
return json(['code'=>0, 'msg'=>$validate->getError()]);
}
// 验证通过
// ...处理登录逻辑
}
}
高级用法
1 中文验证码
// 配置中文验证码
$config = [
'useZh' => true, // 使用中文
'fontSize' => 20, // 字体大小需要适当增大
'length' => 4, // 中文字数
];
return captcha($config);
2 AJAX验证示例
<script>
function checkCode() {
var code = $('#code').val();
$.ajax({
url: "{:url('index/login/checkCode')}",
type: 'post',
data: {code: code},
dataType: 'json',
success: function(res){
if(res.code == 1){
alert('验证码正确');
}else{
alert(res.msg);
refreshCaptcha(); // 刷新验证码
}
}
});
}
</script>
3 多次验证控制
// 控制验证码验证次数
public function checkCode()
{
$code = input('post.code');
// 验证验证码
if(!captcha_check($code)){
return json(['code'=>0, 'msg'=>'验证码错误']);
}
return json(['code'=>1, 'msg'=>'验证码正确']);
}
完整示例
<?php
namespace app\index\controller;
use think\Controller;
use think\captcha\Captcha;
use think\Validate;
class Login extends Controller
{
// 显示登录页面
public function index()
{
return $this->fetch();
}
// 生成验证码
public function verify()
{
$config = [
'fontSize' => 25,
'length' => 4,
'useNoise' => true,
'useCurve' => true,
'bg' => [243, 251, 254],
];
$captcha = new Captcha($config);
return $captcha->entry();
}
// 处理登录
public function doLogin()
{
$data = input('post.');
// 验证器验证
$validate = new Validate([
'username' => 'require|length:3,20',
'password' => 'require|length:6,20',
'code' => 'require|captcha',
], [
'username.require' => '用户名不能为空',
'password.require' => '密码不能为空',
'code.require' => '验证码不能为空',
'code.captcha' => '验证码错误',
]);
if (!$validate->check($data)) {
return json(['code' => 0, 'msg' => $validate->getError()]);
}
// 验证通过,处理登录逻辑(这里省略)
return json(['code' => 1, 'msg' => '登录成功']);
}
}
后端模板文件(login.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">登录页面</title>
<style>
.form-group { margin: 10px 0; }
.captcha-img { cursor: pointer; vertical-align: middle; }
.captcha-input { width: 120px; padding: 5px; }
</style>
</head>
<body>
<form id="loginForm">
<div class="form-group">
<label>用户名:</label>
<input type="text" name="username" placeholder="请输入用户名">
</div>
<div class="form-group">
<label>密码:</label>
<input type="password" name="password" placeholder="请输入密码">
</div>
<div class="form-group">
<label>验证码:</label>
<input type="text" name="code" class="captcha-input" placeholder="请输入验证码">
<img src="{:url('index/login/verify')}" class="captcha-img"
onclick="this.src='{:url('index/login/verify')}?time='+Math.random()">
</div>
<button type="button" onclick="doLogin()">登录</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function doLogin() {
$.post("{:url('index/login/doLogin')}", $('#loginForm').serialize(), function(res){
alert(res.msg);
if(res.code == 1){
window.location.href = "{:url('index/index/index')}";
} else {
// 刷新验证码
$('.captcha-img')[0].src = "{:url('index/login/verify')}?time=" + Math.random();
}
}, 'json');
}
</script>
</body>
</html>
注意事项
-
安全性:验证码在服务器端存储,每次验证成功后会自动重置(可以在配置中设置
'reset' => false禁用)。 -
兼容性:确保PHP安装了GD库,否则验证码无法生成。
-
样式调整:可以通过配置参数调整验证码的字体大小、背景色、干扰元素等。
-
多语言:如果使用中文验证码,需要确保服务器支持相应字体。
通过以上方法,你可以在ThinkPHP项目中轻松实现验证码功能。