YII2中原生提供了验证码模块使用非常简单。我们以登陆时增加验证码为例:
首先在site的controller里面新加一个action用户访问验证码我们命名为captcha
public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'maxLength'=>4, 'minLength'=>4, ], ]; }
同时我们要放开权限让未登录的用户也能访问这个action
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login', 'error','captcha'], 'allow' => true, ], [ 'actions' => ['logout', 'index'], 'allow' => true, 'roles' => ['@'], ], ], ], ......
这个时候我们在浏览器里面敲/site/captcha就可以看到一个4位验证码图片啦。接下来我们把验证码和登陆框组合起来
<?= $form ->field($model, 'verifyCode') ->label(false) ->widget(Captcha::className(), [ 'template' => '<div class="input-group"> {input} <span class="input-group-addon" style="padding-left:10px; padding-right:10px;">{image}</span> </div>', 'options' => ['class' => 'form-control', 'maxlength'=>"4", 'placeholder'=>"验证码" ], 'imageOptions' =>['style'=>'height:20px', 'border'=>'0', 'alt'=>"点击更换验证码" ] ]) ?>
这里会使用loginForm的Model中的verifyCode属性,所以记得给loginForm中加入verifyCode
class LoginForm extends Model { //...... public $verifyCode; //......
至此验证码的显示部分已经完成,你可以去页面上查看包含验证码的输入框了,接下来我们要完成验证码的验证部分,继续修改loginForm在rules中加入验证码验的验证rule
public function rules() { return [ // username and password are both required [['username', 'password'], 'required','message' => '请输入信息'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ['verifyCode', 'captcha','message' => '验证码不正确'], ]; }
好了 大功告成,接下来如果你验证码没输入正确就可以在页面上看到错误提示啦。