---
title: "Yii Framework 开发教程(21) UI 组件 自定义Captcha示例"
author: "mapdigit"
date: "2012-12-26T18:43:00Z"
tags: []
slug: "yii-framework-21-ui-captcha"
draft: false
lastmod: "2013-03-22T14:04:41Z"
id: 1834211
url: "https://mapdigit.iteye.com/blog/1834211"
---

Yii内置的Captcha基本上可以满足大部分需求，如果你对验证码有特殊要求，你可以自定义Captcha，这主要是通过扩展CCaptchaAction来实现的，本例自定义一个验证码功能，随机产生10以内的加减法，用户需要计算出正确的结果才能通过验证。  
本例基于上例[Yii Framework 开发教程(20) UI 组件 Captcha示例](http://www.imobilebbs.com/wordpress/archives/4007)，做如下修改

首先在protected/components 目录下创建一个MathCaptchaAction，重载generateVerifyCode, renderImage等方法：

```
class MathCaptchaAction extends CCaptchaAction
{

	protected function generateVerifyCode()
	{
		return mt_rand((int)$this->minLength,
			(int)$this->maxLength);
	}

	public function renderImage($code)
	{
		parent::renderImage($this->getText($code));
	}

	protected function getText($code)
	{
		$code=(int)$code;
		$rand=mt_rand(1,$code-1);
		$op=mt_rand(0,1);
		if($op)
		{

			return $code-$rand. '+' . $rand;

		}else
		{
			return $code+$rand. '-' . $rand;
		}
	}
}
```

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

```
public function actions()
{
	return array(
		'captcha'=>array(
				'class' => 'MathCaptchaAction',
				'minLength' => 1,
				'maxLength' => 10,
		));
}
```

[![201212126003](http://www.imobilebbs.com/wordpress/wp-content/uploads/2012/12/201212126003.png)](http://www.imobilebbs.com/wordpress/archives/4013/attachment/201212126003)本例[下载](http://www.imobilebbs.com/download/yii/CustomCaptchaDemo.zip)