yii使用验证码(非原创)

文章原出处:http://blog.sina.com.cn/s/blog_92863deb01011rni.html  是我喜欢的风格,简洁。

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

第一步在Controller里添加方法 actions

 public function actions()
    { 
            return array( 
                    // captcha action renders the CAPTCHA image displayed on the contact page
                    'captcha'=>array(
                            'class'=>'CCaptchaAction',
                            'backColor'=>0xFFFFFF, 
                            'maxLength'=>'4',       // 最多生成几个字符
                             'minLength'=>'2',       // 最少生成几个字符
                           'height'=>'40'
                    ), 
            ); 
    }

同时, 需要将captacha添加到accessRules里, 以允许所有用户访问该方法.如下

array('allow',  // allow all users to perform 'index' and 'view' actions
    'actions'=>array('index','view','captcha'),
    'users'=>array('*'),
   ),

第二在你的视图里面加上以下代码  

<?php $this->widget('CCaptcha'); ?> 

// 下面这个可以点击图片进行换验证码

  <div><?php $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>array('alt'=>'点击换图','title'=>'点击换图','style'=>'cursor:pointer'))); ?></div>

 

第三 我们需要在我们的form model中添加一个verifycode的属性来存放用户输入的验证码,然后通过captcha验证器来验证用户输入的验证码的准确性。

 public $verifyCode;

并在rules中添加如下

public function rules()
 {

  return array(

...

array('verifyCode', 'captcha', 'on'=>'login', 'allowEmpty'=> !extension_loaded('gd')), 

...

     );

posted @ 2013-04-12 16:58  zyliang  阅读(423)  评论(0编辑  收藏  举报