12-1 ThinkPHP5验证码的使用

12-1 ThinkPHP5验证码的使用

心托泵规邪泡筋干梯稻娟讣幕

要使用验证码需要按照手册使用composer安装验证码类库

也可以点击下方红字下载完整版thinkphp5框架

ThinkPHP5.0.21完整版下载

下载上方的框架,配置好后进行下方的步骤

配置验证码(具体配置可以参考手册):

12-1 ThinkPHP5验证码的使用第1张

<?php
return [
    'captcha'=>[
        // 验证码字体大小
        'fontSize' => 30,
        // 验证码位数
        'length' => 4,
        // 使用中文验证码
//        'useZh'=>true,
        //是否画混淆曲线
        'useCurve'=>false,
        //是否添加杂点
        'useNoise'=>false
    ],

    //调试模式
    'app_debug'=> true,

];

12-1 ThinkPHP5验证码的使用第2张

D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }
}

D:\phpStudy\PHPTutorial\WWW\tp5\application\index\view\index\index.html:

<h3>验证码实例</h3>
<form action="{:url('check')}" method="post">
    输入验证码:<input type="text" name="code">
    <div>{:captcha_img()}</div>
    <p><button>提交</button></p>
</form>

执行:

12-1 ThinkPHP5验证码的使用第3张

此时每刷新界面一次,验证码变化一次。

期望目标:点击图片更换验证码

审查元素:只需要点击图片将验证码图片的地址添加get参数即可,这样即实现点击一次换一次url地址。

12-1 ThinkPHP5验证码的使用第4张

D:\phpStudy\PHPTutorial\WWW\tp5\application\index\view\index\index.html:

<h3>验证码实例</h3>
<form action="{:url('check')}" method="post">
    输入验证码:<input type="text" name="code">
    <div>{:captcha_img()}</div>
    <p><button>提交</button></p>
</form>
<script src="/static/jquery/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    $('img').click(function ()
    {
        $('img').attr('src','/captcha.html?a='+Math.random(1,1000))
    })
</script>

执行,此时点击一下验证码图片就会更换验证码

12-1 ThinkPHP5验证码的使用第5张


D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:

创建check()方法,用于验证验证码

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    //检验验证码是否正确
    public function check($code="")
    {
        //实例化验证码类
        $captcha=new \think\captcha\Captcha();
        if(!$captcha->check($code))
        {
            $this->error('验证码错误');
        }
        else
        {
            $this->success('验证码正确');
        }

    }

}

执行:

12-1 ThinkPHP5验证码的使用第6张

12-1 ThinkPHP5验证码的使用第7张

12-1 ThinkPHP5验证码的使用第8张

12-1 ThinkPHP5验证码的使用第9张


check()方法使用助手函数改写:

D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    //检验验证码是否正确
    public function check($code="")
    {
        //助手函数:
        if(!captcha_check($code))
        {
            $this->error('验证码错误');
        }
        else
        {
            $this->success('验证码正确');
        }

    }

}

在配置文件里面允许验证码使用中文

执行:

12-1 ThinkPHP5验证码的使用第10张

12-1 ThinkPHP5验证码的使用第11张

12-1 ThinkPHP5验证码的使用第12张

12-1 ThinkPHP5验证码的使用第13张


采茶刀椿裸氦拇搁蝗称诺砍豢