美文网首页
ThinkPHP6.0 验证码

ThinkPHP6.0 验证码

作者: 皮蛋馅儿 | 来源:发表于2020-04-05 20:59 被阅读0次

1、使用Composer安装think-captcha扩展包

composer require topthink/think-captcha

2、在视图直接调用即可

{:captcha_img()}

或者

<img src="{:captcha_src()}" alt="captcha" />

3、以上便完成了验证码的使用,如果你想要自定义验证码或者生成多个不同设置的验证码,可以通过以下方法:
在\config\captcha.php文件,return的数组里面添加配置

// 添加额外的验证码设置
'custom' => [
    'length' => 4,
],

\app\admin\controller目录下,新建Verify.php

<?php

namespace app\admin\controller;

use app\BaseController;
use think\captcha\facade\Captcha;

class Verify extends BaseController
{
    public function captcha()
    {
        // 这里的custom是/config/captcha.php里面定义的额外验证码设置
        return Captcha::create('custom');
    }
}

自定义验证码视图调用

<img src="{:url('verify/captcha')}" onclick="this.src='{:url('verify/captcha')}?' + Math.random();">

4、验证码验证
验证码库需要开启Session才能生效。默认没有开启,在\app\middleware.php开启session

<?php
// 全局中间件定义文件
return [
    // 全局请求缓存
    // \think\middleware\CheckRequestCache::class,
    // 多语言加载
    // \think\middleware\LoadLangPack::class,
    // Session初始化
     \think\middleware\SessionInit::class
];

验证

if (!captcha_check($captcha)) {
    // 验证失败
}

相关文章

网友评论

      本文标题:ThinkPHP6.0 验证码

      本文链接:https://www.haomeiwen.com/subject/aihpphtx.html