Yii 2.0 使用验证码

Yii2.0 提供了验证码组件。调用起来比较方便。以登录页面添加验证码为例。

1. 模型中添加字段和验证规则。

commonmodelsLoginForm

添加如下代码

public $captcha;

//rules() 方法内添加
['captcha', 'required'],
['captcha', 'captcha'],

2. 控制器中添加captcha的action  

backendcontrollersSiteController

复制代码
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
            // 新添加的
            'captcha' => [
                'class' => 'yiicaptchaCaptchaAction',
            ],
        ];
    }    
复制代码

3. 视图中引入验证码widget

ackendviewssitelogin.php

use yiicaptchaCaptcha;

<?= $form->field($model, 'captcha')->widget(Captcha::className()) ?>

需要注意的是这个widget包含了一个显示图片的img标签和一个输入验证码的文本框。 比较丑。可以稍微调整

<?= $form->field($model, 'captcha')->widget(Captcha::className(),['options' => [
                        'placeholder' => '请输入上方显示的字母'
                            ,'class' => 'form-control'
                            ,'style' => 'margin-top:10px;'
                    ]])->label(false); ?>

注意事项:

1. 图片访问地址是/site/captcha?v=5538ed905b396,但显示的是个叉叉。

有可能地址被限制访问了。在site控制中的behaviors,将captcha动作加入到可访问列表中

复制代码
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
   // 加入captcha,使其可访问/site/captcha 'actions' => ['login', 'error','captcha'], 'allow' => true, ]......... ], ], ]; }
复制代码

2. 点击图片不刷新新的验证码

查看下是否加载了yii.js ,yii.valiadation.js ,yii.captcha.js等yii的asset包

如果没有,应该是该视图对应的layout问题,尝试在$content上下加入<?php $this->beginBody() ?>和<?php $this->endBody() ?>。

原文地址:https://www.cnblogs.com/mafeifan/p/4451838.html