yii2.0-captcha验证码--详细设置

来源:互联网 发布:如何加入淘宝热卖 编辑:程序博客网 时间:2024/05/17 08:31

最近看群里问yii2验证码怎么弄的朋友比较多,网站里也有相关教程,不过比较简洁,我想需要来一个详细点的。

我把使用Captcha(验证码)分4步:

1、确认有没有处理图片的php扩展库,gd库和imagick库开启一个即可。(这步一般可以略过)

                                             yii2 
通过requirements.php的检查结果

11111.png

yii2会检查开启的这两个库,优先使用imagick库。

22222.png

2、视图文件设置

3333.png

444444.png


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

3、控制器设置


666666.png

A框部分,指定验证码的类和fixedVerifyCode刷新固定验证码,至于fixedVerifyCode的作用,可以参考:http://blog.csdn.net/poly_sunny/article/details/19995801
B部分,看了就知道是设置验证码长、宽、高等参数。
如果你的yii程序启用了权限控制,还需要设置

1212.png


允许验证码对应的action在没有登录的情况下也能被访问(这个是导致一些朋友验证码出不来的原因)。

4、模型设置 和 验证码校验

8888888.png

['verifyCode', 'captcha','captchaAction'=>'/user/security/captcha'],

 

C :声明模型属性verifyCodepublic,既是第2步中的fields的第二个参数值,两者需保持一致。

D rules中如果正确定义了'captcha'的规则,则验证码的检测比较不需要其他多余代码,model::valide()的时候会自动校验。如果不定义,也可以自己写校验代码:

      use yii\captcha\CaptchaValidator;

      $caprcha = new CaptchaValidator();

$caprcha->validate($value);

或者

$this->createAction('captcha')->validate( \Yii::$app->request->post( $model->formName() )['verifyCode'], false)



[方法二]

首先对应控制器中定义captcha,对应模型中声明captcha变量。

 public function actions() {        return [            'captcha' =>  [                'class' => 'yii\captcha\CaptchaAction',                'height' => 50,                'width' => 80,                'minLength' => 4,                'maxLength' => 4            ],        ];    }

设置一些简单属性,也可以不设。

对应视图中添加表单:

  <?= $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className()                                        ,['captchaAction'=>'user/captcha',                                        'imageOptions'=>['alt'=>'点击换图','title'=>'点击换图', 'style'=>'cursor:pointer']]);?>

captchaAction 指定captcha所在的控制器路径,默认是‘site/captcha’,不换到指定位置的话,很容易,验证码就显示不出来。
imageOptions设定一些参数,例如 手势,提示等等。

对应布局中,如下:以确保你在点击验证码可以自动刷新

<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
//your codes...
<?= $contents; ?>
//your codes...
<?php $this->endBody() ?>
<?php $this->endPage() ?>

最后,控制器中调用render而非renderPartial:
return $this->render('login',['user_login'=>$user_login]);


都说是yii里的一个小bug,需手动修改 \yii\captcha\CaptionAction run方法里的 return $this->renderImage($this->getVerifyCode(true));← 写入参数 ‘true’(默认是false),验证码 方会刷新。

【方法三】

1,Model:

将验证码加入UserLogin的一个属性:

[php] view plain copy
  1. class UserLogin extends CFormModel  
  2. {  
  3.     public $username;  
  4.     public $password;  
  5.     public $rememberMe;  
  6.     public $verifyCode;  
  7.   
  8.     public function rules()  
  9.     {  
  10.         return array(  
  11.             // username and password are required  
  12.             array('username, password,verifyCode''required'),  
  13.             // rememberMe needs to be a boolean  
  14.             array('rememberMe''boolean'),  
  15.             // password needs to be authenticated  
  16.             array('password''authenticate'),  
  17.             // verifyCode needs to be entered correctly  
  18.             array('verifyCode''captcha''allowEmpty'=>!CCaptcha::checkRequirements()),  
  19.         );  
  20.     }  
  21.   
  22.     /** 
  23.      * Declares attribute labels. 
  24.      */  
  25.     public function attributeLabels()  
  26.     {  
  27.         return array(  
  28.             'rememberMe'=>Yii::t('user',"Remember me next time"),  
  29.             'username'=>Yii::t('user',"username or email"),  
  30.             'password'=>Yii::t('user',"password"),  
  31.             'verifyCode'=>Yii::t('user','Verification Code'),  
  32.         );  
  33.     }  

2,Controller

在LoginController控制器加入映射动作CCaptchaAction

[php] view plain copy
  1. public function actions()  
  2. {  
  3.     return array(  
  4.         // captcha action renders the CAPTCHA image displayed on the contact page  
  5.         'captcha'=>array(  
  6.             'class'=>'CCaptchaAction',  
  7.             'backColor'=>0xf4f4f4,  
  8.             'padding'=>0,  
  9.             'height'=>30,  
  10.             'maxLength'=>4,  
  11.         ),  
  12.         );  
  13. }  
  14.   
  15. ublic function actionLogin()  
  16. {  
  17.       
  18.     if (Yii::app()->user->isGuest) {  
  19.         $model=new UserLogin;  
  20.         // collect user input data  
  21.         if(isset($_POST['UserLogin']))  
  22.         {  
  23.               
  24.             $model->attributes=$_POST['UserLogin'];  
  25. /在此核对验证码  
  26.             if($this->createAction('captcha')->validate($model->verifyCode, false))  
  27.             {  
  28.                 // validate user input and redirect to previous page if valid  
  29.                 if($model->validate()) {  
  30.                 //admin login only  
  31.                 if( Yii::app()->getModule('user')->isAdmin()==1 )  
  32.                 {  
  33.                 $this->lastViset();  
  34.                 if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false)  
  35.                     $this->redirect(Yii::app()->controller->module->returnUrl);  
  36.                 else  
  37.                     $this->redirect(Yii::app()->user->returnUrl);  
  38.                 }else  
  39.                 {//if no admin when login out  
  40.                     $this->redirect(Yii::app()->controller->module->logoutUrl);  
  41.                 }  
  42.             }  
  43.             }else  
  44.             {//提示错误  
  45.                 $model->addError('verifyCode','验证码不对');  
  46.             }  
  47.         }  
  48.         // display the login form  
  49.         $this->render('/user/login',array('model'=>$model));  
  50.     } else  
  51.         $this->redirect(Yii::app()->controller->module->returnUrl);  
  52. }  

在验证用户名密码前,检查验证码:

[php] view plain copy
  1. if($this->createAction('captcha')->validate($model->verifyCode, false))  
  2.                 { 

3,view

在视图中显示验证码图片,输入框

[php] view plain copy
  1. <?php $this->widget('CCaptcha'); ?>  
  2.         <?php echo CHtml::activeTextField($model,'verifyCode',array('tabindex'=>1)); ?> 
[php] view plain copy
  1. <pre name="code" class="php"><p><img src="http://my.csdn.net/uploads/201205/18/1337330851_3646.jpg" alt="">  
  2. </p><p>---------------------------the end------------------------------------</p></pre>  
  3. <pre></pre>  
  4. <pre></pre>  
【方法四】

Yii2.0的自带的验证依赖于GD2或者ImageMagick扩展。

使用步骤如下:

重写yii\web\Controller::actions()方法,用ID"captcha"注册一个CaptchaAction类的action。

在表单模型里面添加一个属性,用来保存用户输入的验证码字符串;这个属性的验证器是"captcha"。

在视图里面,把yii\captcha\Captcha Widget插入到表单里面。

第一步,控制器:

在任意controller里面重写方法

/** * @inheritdoc*/public function actions(){    return [         'captcha' => [              'class' => 'yii\captcha\CaptchaAction',              'maxLength' => 5,              'minLength' => 5         ],     ];}

第二步,表单模型:

假如是一个登陆表单。

这里只给出验证码相关的部分。

class LoginForm extends Model{    public $verifyCode;         public function rules()    {        return [            ['verifyCode', 'required'],            ['verifyCode', 'captcha'],        ];    }}

验证规则里面验证码的验证器是captcha。

第三步,视图:

用ActiveForm生成对应字段。

<?= $form->field($model, 'verifyCode', [        'options' => ['class' => 'form-group form-group-lg'],])->widget(Captcha::className(),[       'template' => "{image}",       'imageOptions' => ['alt' => '验证码'],]); ?>

验证码,生成和验证的整个流程就完成了。

【方法五】

 *这个是对应前台模版的action */public function actionLogin(){       $loginForm = new LoginForm();//这里要把刚才写的类new下,注意你们要引入文件路径额       $this->render('login',array('loginForm'=>$loginForm));//变量传到前台模版}/** * @用户授权规则 */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,//                    ],  //默认的写法                        'captcha' => [                                    'class' => 'yii\captcha\CaptchaAction',                                    'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,                                    'backColor'=>0x000000,//背景颜色                                    'maxLength' => 6, //最大显示个数                                    'minLength' => 5,//最少显示个数                                    'padding' => 5,//间距                                    'height'=>40,//高度                                    'width' => 130,  //宽度                                      'foreColor'=>0xffffff,     //字体颜色                                    'offset'=>4,        //设置字符偏移量 有效果                                    //'controller'=>'login',        //拥有这个动作的controller                            ],];}

到这里第二步 控制器的代码就完成了,其中要加入的类,你们自己要留意,别落下!

第三步:

在view的模版里,我这里是login.php加入以下代码

 <?php           $form = ActiveForm::begin([                              'id' => 'login-form',                                                                         ]);   ?><?php echo Captcha::widget(['name'=>'captchaimg','captchaAction'=>'login/captcha','imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);//我这里写的跟官方的不一样,因为我这里加了一个参数(login/captcha),这个参数指向你当前控制器名,如果不加这句,就会找到默认的site控制器上去,验证码会一直出不来,在style里是可以写css代码的,可以调试样式 ?><?php ActiveForm::end(); ?>


原创粉丝点击