zoukankan      html  css  js  c++  java
  • 13.ThinkPHP扩展库:验证码 的使用

    安装

    安装需要使用Composer安装think-captcha扩展包

    composer require topthink/think-captcha=2.0.*
    

    image-20200528164238599

    使用方法

    扩展包内定义了一些常见用法方便使用,可以满足大部分常用场景,以下示例说明。

    在模版内添加验证码的显示代码

    直接生成了html (验证码)

    <div>{:captcha_img()}</div>
    

    或者

    生成了验证码路径

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

    上面两种的最终效果是一样的,根据需要调用即可。

    例:

    视图文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户登陆</title>
        <link rel="stylesheet" href="/static/index/css/bootstrap.css"/>
        <link rel="stylesheet" href="/static/index/css/bootstrap-theme.css"/>
    </head>
    <body>
    <br/>
    
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">用户登陆</h3>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" method="post" action="{:url('login')}">
                    <!--csrf验证-->
                    {:token()}
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">账号</label>
                        <div class="col-sm-10">
                            <!--提交参数-->
                            <input type="text" class="form-control" name="username">
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <!--提交参数-->
                            <input type="text" class="form-control" name="password">
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">验证码</label>
                        <div class="col-sm-5">
                            <!--提交参数-->
                            <input type="text" class="form-control" name="password">
                        </div>
                        <div class="col-sm-5">
                            <div>
                            	<!--验证码-->
                                <img src="{:captcha_src()}" id="vcode" />
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-success">提交</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="/static/index/js/bootstrap.js "></script>
    <script src="/static/js/jquery.min.js "></script>
    </body>
    </html>
    

    控制器

    <?php
    namespace appindexcontroller;
    use thinkController;
    use thinkfacadeRequest;
    class Login extends Controller
    {
        //登陆界面
        public function index(){
            return view('index@login/index');
        }
    
        //登陆处理
        public function login(Request $request){
    
        }
    }
    

    路由

    //登陆路由
    Route::get('login', '@index/login/index')->name('login');
    

    运行效果

    image-20200528174015252

    访问路由直接返回验证码

    如果需要自己独立生成验证码,可以调用Captcha类(thinkcaptchaCaptcha)操作。

    在控制器中使用下面的代码进行验证码生成:

    <?php
    namespace appindexcontroller;
    
    use thinkcaptchaCaptcha;
    
    class Index 
    {
    	public function verify()
        {
            $captcha = new Captcha();
            return $captcha->entry();    
        }
        
    }
    

    例:

    控制器

    <?php
    namespace appindexcontroller;
    use appindexvalidateLoginValidate;
    use thinkcaptchaCaptcha;
    use thinkController;
    use thinkRequest;
    
    class Login extends Controller
    { 
       //访问登陆验证码
        public function vcode(){
            $captcha = new Captcha();
            return $captcha->entry();
        }
    }
    
    

    路由

    //访问直接返回验证码
    Route::get('loginCode', '@index/login/vcode')->name('loginCode');
    

    运行结果

    image-20200528184652259

    验证码的验证

    方式一:验证器验证验证码

    验证器

    <?php
    
    namespace appindexvalidate;
    
    use thinkValidate;
    
    class LoginValidate extends Validate
    {
        /**
         * 定义验证规则
         * 格式:'字段名'	=>	['规则1','规则2'...]
         *
         * @var array
         */	
    	protected $rule = [
    	    'code' => 'require|captcha'
        ];
        
        /**
         * 定义错误信息
         * 格式:'字段名.规则名'	=>	'错误信息'
         *
         * @var array
         */	
        protected $message = [
            'code.captcha' => '你想干吗,验证码都输不对'
        ];
    }
    

    image-20200528181728784

    控制器

    <?php
    
    namespace appindexcontroller;
    
    use appindexvalidateLoginValidate;
    use thinkController;
    use thinkRequest;
    
    
    class Login extends Controller
    {
        //登陆界面
        public function index(){
            return view('index@login/index');
        }
    
        //登陆处理
        public function login(Request $request){
            $res = $this->validate($request->post(),LoginValidate::class);
            if(true !== $res){
                return $this->error($res);
            }
    
            dump($request->post());
        }
    }
    

    路由

    //登陆界面路由
    Route::get('login', '@index/login/index')->name('login');
    //登陆后台提交路由
    Route::post('loginSubmit', '@index/login/login')->name('loginSubmit');
    

    视图

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户登录</title>
        <link rel="stylesheet" href="/static/index/css/bootstrap.css"/>
        <link rel="stylesheet" href="/static/index/css/bootstrap-theme.css"/>
        <style>
            /*修改鼠标手势*/
            #vcode {
                cursor: pointer;
            }
        </style>
    </head>
    <body>
    
    <br>
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">用户登录</h3>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" method="post" action="{:url('loginSubmit')}">
                    <!--csrf验证-->
                    {:token()}
                    <div class="form-group">
                        <label class="col-sm-2 control-label">账号:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="username">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">密码:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="password">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">验证码:</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control" name="code">
                        </div>
                        <div class="col-sm-5">
                            <img src="{:captcha_src()}" id="vcode">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-success">用户登录</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/index/js/bootstrap.js"></script>
    <script>
    
        // 点击更新验证码图片
        $('#vcode').click(function () {
            let src = $(this).attr('src') + '?vt=' + Math.random();
            $(this).attr('src',src);
        })
    </script>
    </body>
    
    </html>
    

    运行结果

    image-20200528182023561

    方式二:独立验证

    如果没有使用内置验证功能,则可以调用内置的函数手动验证

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

    例:

     // 独立去验证验证码
     $code = $request->post('code');
     // 如果验证不通过,则返回false
     if (!captcha_check($code)) {
     	return $this->error('验证不正确');
     }
    

    运行结果

    image-20200528185501292

    验证码的配置参数

    Captcha类带有默认的配置参数,支持自定义配置。这些参数包括:

    参数 描述 默认
    codeSet 验证码字符集合
    expire 验证码过期时间(s) 1800
    useZh 使用中文验证码 false
    zhSet 中文验证码字符串
    useImgBg 使用背景图片 false
    fontSize 验证码字体大小(px) 25
    useCurve 是否画混淆曲线 true
    useNoise 是否添加杂点 true
    imageH 验证码图片高度,设置为0为自动计算 0
    imageW 验证码图片宽度,设置为0为自动计算 0
    length 验证码位数 5
    fontttf 验证码字体,不设置是随机获取
    bg 背景颜色 [243, 251, 254]
    reset 验证成功后是否重置 true

    如果使用扩展内置的方法进行验证码显示,直接在应用的config目录下面的captcha.php文件(没有则首先创建)中进行设置即可

    例:

    config目录下面的captcha.php文件

    <?php
    return [
        'length' => 2,
        'useCurve' => false,
        'useNoise' => false,
        'imageW' => 140,
        'imageH' => 40
    ];
    

    运行效果

    image-20200528174718335

    独立调用Captcha类

    实例化传入参数:

    $config =    [
        // 验证码字体大小
        'fontSize'    =>    30,    
        // 验证码位数
        'length'      =>    3,   
        // 关闭验证码杂点
        'useNoise'    =>    false, 
    ];
    $captcha = new Captcha($config);
    return $captcha->entry();
    

    或者采用动态设置的方式,如:

    $captcha = new Captcha();
    $captcha->fontSize = 30;
    $captcha->length   = 3;
    $captcha->useNoise = false;
    return $captcha->entry();
    

    验证码字体

    默认情况下,验证码的字体是随机使用扩展包内 think-captcha/assets/ttfs目录下面的字体文件,我们可以指定验证码的字体,例如:

    $captcha = new Captcha();
    $captcha->fontttf = '5.ttf'; 
    return $captcha->entry();
    

    背景图片

    支持验证码背景图片功能,可以如下设置:

    $captcha = new Captcha();
    // 开启验证码背景图片功能 随机使用扩展包内`think-captcha/assets/bgs`目录下面的图片
    $captcha->useImgBg = true; 
    return $captcha->entry();
    

    中文验证码

    如果要使用中文验证码,可以设置:

    $captcha = new Captcha();
    // 使用中文验证码(字体使用扩展包内`think-captcha/assets/zhttfs`字体文件)
    $captcha->useZh = true; 
    return $captcha->entry();
    

    指定验证码字符

    指定验证码的字符,可以设置:

    $captcha = new Captcha();
    // 设置验证码字符为纯数字
    $captcha->codeSet = '0123456789'; 
    return $captcha->entry();
    

    如果是中文验证码,可以使用zhSet参数设置,例如:

    $captcha = new Captcha();
    $captcha->useZh = true;
    // 设置验证码字符
    $captcha->zhSet = '们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这'; 
    return $captcha->entry();
    

    默认的验证码字符已经剔除了易混淆的1l0o等字符

  • 相关阅读:
    【leetcode】1020. Partition Array Into Three Parts With Equal Sum
    【leetcode】572. Subtree of Another Tree
    【leetcode】123. Best Time to Buy and Sell Stock III
    【leetcode】309. Best Time to Buy and Sell Stock with Cooldown
    【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee
    【leetcode】467. Unique Substrings in Wraparound String
    【leetcode】823. Binary Trees With Factors
    【leetcode】143. Reorder List
    【leetcode】1014. Capacity To Ship Packages Within D Days
    【leetcode】1013. Pairs of Songs With Total Durations Divisible by 60
  • 原文地址:https://www.cnblogs.com/makalochen/p/12983146.html
Copyright © 2011-2022 走看看