YII框架 验证码使用 转载自墙角花开的博客

来源:互联网 发布:linux shutdown -h 编辑:程序博客网 时间:2024/05/01 17:07

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')), ...     );} 


原创粉丝点击