您的位置:首页 > 编程语言 > PHP开发

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

2017-08-10 23:09 363 查看
最近看群里问yii2验证码怎么弄的朋友比较多,网站里也有相关教程,不过比较简洁,我想需要来一个详细点的。
我把使用Captcha(验证码)分4步:
1、确认有没有处理图片的php扩展库,gd库和imagick库开启一个即可。(这步一般可以略过)                                             yii2 通过requirements.php的检查结果yii2会检查开启的这两个库,优先使用imagick库。2、视图文件设置如果你是直接在yii2默认控制器SiteController.php渲染的视图,那么上图中captchaAction参数可以不用设置。如果不是,那就必须要指定清楚,因为captchaAction默认site/captcha。如下图:(这个是导致一些朋友验证码出不来的原因)。 3、控制器设置
A框部分,指定验证码的类和fixedVerifyCode刷新固定验证码,
至于fixedVerifyCode的作用,可以参考:http://blog.csdn.net/poly_sunny/article/details/19995801
B部分,看了就知道是设置验证码长、宽、高等参数。
如果你的yii程序启用了权限控制,还需要设置
允许验证码对应的action在没有登录的情况下也能被访问(这个是导致一些朋友验证码出不来的原因)。4、模型设置 和 验证码校验['verifyCode', 'captcha','captchaAction'=>'/user/security/captcha'], C :声明模型属性verifyCode为public,既是第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] viewplain copyclass UserLogin extends CFormModel  {      public $username;      public $password;      public $rememberMe;      public $verifyCode;        public function rules()      {          return array(              // username and password are required              array('username, password,verifyCode', 'required'),              // rememberMe needs to be a boolean              array('rememberMe', 'boolean'),              // password needs to be authenticated              array('password', 'authenticate'),              // verifyCode needs to be entered correctly              array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),          );      }        /**      * Declares attribute labels.      */      public function attributeLabels()      {          return array(              'rememberMe'=>Yii::t('user',"Remember me next time"),              'username'=>Yii::t('user',"username or email"),              'password'=>Yii::t('user',"password"),              'verifyCode'=>Yii::t('user','Verification Code'),          );      }  2,Controller在LoginController控制器加入映射动作CCaptchaAction[php] viewplain copypublic function actions()  {      return array(          // captcha action renders the CAPTCHA image displayed on the contact page          'captcha'=>array(              'class'=>'CCaptchaAction',              'backColor'=>0xf4f4f4,              'padding'=>0,              'height'=>30,              'maxLength'=>4,          ),          );  }    ublic function actionLogin()  {            if (Yii::app()->user->isGuest) {          $model=new UserLogin;          // collect user input data          if(isset($_POST['UserLogin']))          {                            $model->attributes=$_POST['UserLogin'];  /在此核对验证码              if($this->createAction('captcha')->validate($model->verifyCode, false))              {                  // validate user input and redirect to previous page if valid                  if($model->validate()) {                  //admin login only                  if( Yii::app()->getModule('user')->isAdmin()==1 )                  {                  $this->lastViset();                  if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false)                      $this->redirect(Yii::app()->controller->module->returnUrl);                  else                      $this->redirect(Yii::app()->user->returnUrl);                  }else                  {//if no admin when login out                      $this->redirect(Yii::app()->controller->module->logoutUrl);                  }              }              }else              {//提示错误                  $model->addError('verifyCode','验证码不对');              }          }          // display the login form          $this->render('/user/login',array('model'=>$model));      } else          $this->redirect(Yii::app()->controller->module->returnUrl);  }  在验证用户名密码前,检查验证码:[php] viewplain copyif($this->createAction('captcha')->validate($model->verifyCode, false))                  { 3,view在视图中显示验证码图片,输入框[php] viewplain copy<?php $this->widget('CCaptcha'); ?>          <?php echo CHtml::activeTextField($model,'verifyCode',array('tabindex'=>1)); ?> [php] viewplain copy<pre name="code" class="php"><p><img src="http://my.csdn.net/uploads/201205/18/1337330851_3646.jpg" alt="">  </p><p>---------------------------the end------------------------------------</p></pre>  <pre></pre>  <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',]);?><?phpecho 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代码的,可以调试样式 ?><?phpActiveForm::end();?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: