YII验证码使用方法

       Web开发的过程中, 经常会用到验证码, 以防止机器人不断的提交数据, 造成网站的瘫痪. Yii里提供了一个验证码的插件, 就是Captcha. 在项目中使用Captcha需要以下一些设置:

       在Controller里添加方法 actions

public function actions() {  
   return array(  
       'captcha'=> array(  
               'class'=>'CCaptchaAction',
               'width'=>140,    //默认120
               'height'=>70,    //默认50
               'padding'=>2,    //文字周边填充大小
               'backColor'=>0xFFFFFF,      //背景颜色
               'foreColor'=>0x2040A0,     //字体颜色
               'minLength'=>6,      //设置最短为6位
               'maxLength'=>7,       //设置最长为7位,生成的code在6-7直接rand了
               'transparent'=>false,      //显示为透明,默认中可以看到为false
               'offset'=>-2,        //设置字符偏移量
               #'controller'=>'admin',        //拥有这个动作的controller
   ));  
}

2.然后在相应的view中插入下面代码:

<?php if (extension_loaded('gd')): ?>
           <div class="row">
               <?php echo CHtml::activeLabelEx($model, 'verifyCode') ?>
           <div>
           <?php $this->widget('CCaptcha'); ?>
           <?php echo CHtml::activeTextField($model,'verifyCode'); ?>
           </div>
           <div class="hint">Please enter the letters as they are shown in the image above.
           <br/>Letters are not case-sensitive.</div>
           </div>
       <?php endif; ?>

具体情况可以根据自己需要具体修改

 3.在model中添加一个verifycode属性,然后通过captcha验证器来验证用户输入的验证码:

class User extends CActiveRecord {  
   public $verifyCode; //为User Model 设置一个新的属性  
   public function rules() {  
       return array(  
       .........  
       array('verifyCode', 'captcha', 'on'=>'login', 'allowEmpty'=> !extension_loaded('gd')),  
   );  
   }  
}

 第三步要注意的是'on'=>'login'对于刚接触yii的人添加很多时候不成功都是没有理解这段的意思。这段代码是指你要应用的场景。如果你在controller里没有设置场景,就去掉这一段代码。都添加完成后可以看手册调整controller中相关参数可以更改样式:



 

猜你喜欢

转载自guhao022.iteye.com/blog/1974641