分享

yii使用验证码

 哇嘿嘿 2014-09-25

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')), 

...

     );

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多