ThinkPHP5——安装验证码和使用

1、使用composer安装验证码 首先要安装composer,大部分“composer require topthink/think-captcha”命令无法运行或者提示不是内部文件或可执行命令,都是因为没有安装composer,或安装不成功。直接百度搜composer即可,有链接,百度经验里也有教程,不在这里详细介绍了。 composer安装成功后,在你的项目主目录地址栏里输入cmd,然后输入composer require topthink/think-captcha来下载安装captcha,当然此时有很大概率会报错,来说一下我遇到的两个问题吧: 第一:网络问题,输入“composer require topthink/think-captcha”窗口一直无响应,此时需要使用以下命令修改composer配置文件,使用国内镜像。原因你懂的。
composer config -g repo.packagist composer https://packagist.phpcomposer.com
第二:版本问题:此时有大概率会引版本不符而报错,错误提示代码如下: 因为官方的5.0版本的扩展库版本号都是1.*2.0版本均为ThinkPHP5.1版本专用,我们只需要更换版本就可以:
composer require topthink/think-captcha 1.*
 注:安装验证码要在项目的根目录安装  2、使用
<?php
namespace app\index\controller;
class Captcha extends \think\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('验证码正确');
        }
        
        // 方法二:函数助手
        if (!captcha_check($code)) {
            $this->error('验证码错误');
        } else {
            $this->success('验证码正确');
        }
    }    
}
注:验证码检测是指验证码提交是对它进行验证,不提交这个check()不会调用
<body>
    <h2>验证码示例</h2>
    <FORM method="post" class="form" action="{:url('check')}">
        输入验证码:<INPUT type="text" class="text" name="code"><br/>
        <div id="captcha_image">{:captcha_img()}</div><!--模版内验证码的显示-->
        <INPUT type="submit" class="btn" value=" 提交 ">
    </FORM>
    <div class="copyright">
        <a title="官方网站" href="http://www.thinkphp.cn">ThinkPHP</a>
        <span>V5</span>
        <span>{ 十年磨一剑-为API开发设计的高性能框架 }</span>
    </div>
</body>
<script>
    //点击图片切换验证码
    $('#captcha_image').click(function(){
        $(this).find('img').attr('src','/captcha.html?r='+Math.random());
    });
</script>