您的位置:首页 > 编程语言 > PHP开发

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

2014-01-19 09:56 495 查看

Yii内置的Captcha基本上可以满足大部分需求,如果你对验证码有特殊要求,你可以自定义Captcha,这主要是通过扩展CCaptchaAction来实现的,本例自定义一个验证码功能,随机产生10以内的加减法,用户需要计算出正确的结果才能通过验证。

本例基于上例Yii
Framework 开发教程(20) UI 组件 Captcha示例,做如下修改

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

[php]
view plaincopyprint?

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;
}
}
}

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

[php]
view plaincopyprint?

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

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




本例下载

更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: