Yii Framework 开发教程(21) UI 组件 自定义Captcha示例

jerry Yii 2015年11月24日 收藏

Yii内置的Captcha基本上可以满足大部分需求,如果你对验证码有特殊要求,你可以自定义Captcha,这主要是通过扩展CCaptchaAction来实现的,自定义一个验证码功能,随机产生10以内的加减法,用户需要计算出正确的结果才能通过验证。
基于上例Yii Framework 开发教程(20) UI 组件 Captcha示例,做如下修改
首先在protected/components 目录下创建一个MathCaptchaAction,重载generateVerifyCode, renderImage等方法:

  1. class MathCaptchaAction extends CCaptchaAction
  2. {
  3.  
  4. protected function generateVerifyCode()
  5. {
  6. return mt_rand((int)$this->minLength,
  7. (int)$this->maxLength);
  8. }
  9.  
  10. public function renderImage($code)
  11. {
  12. parent::renderImage($this->getText($code));
  13. }
  14.  
  15. protected function getText($code)
  16. {
  17. $code=(int)$code;
  18. $rand=mt_rand(1,$code-1);
  19. $op=mt_rand(0,1);
  20. if($op)
  21. {
  22.  
  23. return $code-$rand. '+' . $rand;
  24.  
  25. }else
  26. {
  27. return $code+$rand. '-' . $rand;
  28. }
  29. }
  30. }

然后修改SiteController的rules 使用新创建的MathCaptchaAction

  1. public function actions()
  2. {
  3. return array(
  4. 'captcha'=>array(
  5. 'class' => 'MathCaptchaAction',
  6. 'minLength' => 1,
  7. 'maxLength' => 10,
  8. ));
  9. }

201212126003.png.jpg

下载地址