Yii2 验证码详细教程,解决不显示不刷新问题

本文详细介绍如何在Yii2框架中集成并使用验证码功能,包括配置captcha组件、调整控制器和模型以支持验证码验证等步骤。

1. 前台页面:index.php
NOTE'captchaAction'=>'/test/login/captcha',//【test为模块,login为控制器,需要指定,用默认控制器site无需指定】

如果你是直接在yii2默认控制器SiteController.php渲染的视图,那么上图中captchaAction参数可以不用设置。如果不是,那就必须要指定清楚,因为captchaAction默认site/captcha。(这个是导致一些朋友验证码出不来的原因)。 


<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\captcha\Captcha;
?>

<?php $form = ActiveForm::begin([
    'id' => 'login-form',
]) ?>
<?= $form->field($model, 'username')->textInput(array('id' => 'xxx')) ?>
<?= $form->field($model, 'password')->passwordInput(); ?>
<?= $form->field($model, 'rememberMe')->checkbox(); ?>

<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
    'captchaAction'=>'/test/login/captcha',//【test为模块,login为控制器,需要指定,用默认控制器sit无需指定】
]) ?>


<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']); ?>
<?php ActiveForm::end() ?>

2. 控制器:LoginController

NOTE::

1 .  

如果你的yii程序启用了权限控制,还需要设置
behaviors的rules;允许验证码对应的action在没有登录的情况下也能被访问(这个是导致一些朋友验证码出不来的原因
2. actions 增加captha

3. rules增加2项目返回值

        4. 加载视图用render,否则不能加载js刷新验证码

  return $this->render('index', array('model' => $model));

<?php
/**
 * Created by PhpStorm.
 * User: flying
 * Date: 2016/10/23
 * Time: 15:44
 */

namespace app\modules\controllers;
use yii\web\Controller;
use app\models\LoginForm;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
class LoginController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'captcha'],//【增加login】
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
//            'captcha' => [
//                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//            ],
	    //增加captcha
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength' => 4,
                'minLength' => 4
            ],

        ];
    }


    public function rules()
    {
       //返回/增加  这两项captcha
return [
            ['verifyCode', 'required'],
            ['verifyCode', 'captcha'],
        ];
    }

    public function actionIndex()
    {
        $model = new LoginForm;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            p($model);
        }
	//必须用render,否则不能刷新验证码,因为不能调用框架的js/jquery代码
        return $this->render('index', array('model' => $model));
    }
}

3. 模型:LoginForm.php

1. 添加成员变量:public $verifyCode;

2.rules增加以下内容,指定模块和控制器

['verifyCode', 'captcha', 'message'=>'验证码错误', 'captchaAction'=>'/test/login/captcha'],

   3. attributeLabels添加:
  'verifyCode' => '验证码', //【验证码添加项目】,验证码的名称,根据个人喜好设定

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $verifyCode;//【验证码添加项目】

    private $_user = false;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            ['verifyCode', 'captcha', 'message'=>'验证码错误', 'captchaAction'=>'/test/login/captcha'],//指定模块、控制器

        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }

    public function attributeLabels()
    {
        return [
            'username' => '用户名:',
            'password' => '密码:',
            'rememberMe' => '是否记住密码',
            'verifyCode' => '验证码', //【验证码添加项目】,验证码的名称,根据个人喜好设定
        ];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flying_vip_521

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值