YII2.0自带验证码

1.首先弄个model出来

<?php
namespace app\models;
use yii\captcha\Captcha;
use Yii;
use yii\base\Model;

class LoginFormModle extends Model
{
    public static $name;

    public static $email;

    public static $subject;

    public static $body;

    //命名个变量,用来储存验证码的值
    public static $verifyCode;

    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['name', 'email', 'subject', 'body'], 'required'],
            // email has to be a valid email
            ['email', 'email'],
            // verifyCode needs to be entered correctly
            ['verifyCode', 'captcha','captchaAction'=>'/login/captcha','message'=>'验证码不正确!'],
        ]; 
    }
    /*
    * * @return array customized attribute labels
    */
    public function attributeLabels()
    {
        return [
            // 'verifyCode' => 'Verification Code',
            'verifyCode' => '',
        ];
    }
}

2.在controller里加入下面代码

 /**********************verifyCode****************************/
    /**
     * @用户授权规则
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup','login'],//这里一定要加
                'rules' => [
                    [
                        'actions' => ['login','captcha'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions'=>['logout','edit','add','del','index','users','thumb','upload','cutpic','follow','nofollow'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }
    /**     图片
     * @验证码独立操作  下面这个actions注意一点,验证码调试出来的样式也许你并不满意,这里就可
    以需修改,这些个参数对应的类是@app\vendor\yiisoft\yii2\captcha\CaptchaAction.php,可以参照这个
    类里的参数去修改,也可以直接修改这个类的默认参数,这样这里就不需要改了
     */
    public function actions()
    {
        return  [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'backColor'=>0x00B956,//背景颜色
                'maxLength' => 4, //最大显示个数
                'minLength' => 4,//最少显示个数
                'padding' => 5,//间距
                'height'=>40,//高度
                'width' => 130,  //宽度
                'foreColor'=>0xffffff,     //字体颜色
                'offset'=>4,        //设置字符偏移量 有效果
                //'controller'=>'login',        //拥有这个动作的controller
                'fontFile' => '@webroot/ttf/Baker.ttf'
            ],
        ];
    }

3.用的时候先声明

$loginForm = new LoginFormModle(); //然后要渲染在页面里面

4.页面使用

<?php  //头部引用
use common\widgets;
use yii\captcha\Captcha;
?>

                <p>
                    <label>图片验证码</label>
                    <input type="text" name="img_code" class="ipt smipt" placeholder="请输入图片验证码" />
                    <?php echo Captcha::widget(['name'=>'captchaimg','captchaAction'=>'login/captcha','imageOptions'=>['id'=>'captchaimg', 'name'=>'captchaimg','title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);?>
                </p>
                <p>
//'captchaAction'=>'login/captcha' 这个是我方法的路径

5.验证码点击刷新问题

 //解决验证码不刷新的问题
    $(function () {
        alert(123);
        changeVerifyCode();
        $('#captchaimg').click(function () {
            changeVerifyCode();
        });
    });

    //更改或者重新加载验证码
    function changeVerifyCode() {
        //项目URL
        $.ajax({
            //使用ajax请求site/captcha方法,加上refresh参数,接口返回json数据
            url: "/login/captcha?refresh",
            dataType: 'json',
            cache: false,
            success: function (data) {
                //将验证码图片中的图片地址更换
                $("#captchaimg").attr('src', data['url']);
            }
        });
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容