Yii內置的Captcha基本上可以滿足大部分需求,如果你對驗證碼有特殊要求,你可以自定義Captcha,這主要是通過擴展 CCaptchaAction來實現的,本例自定義一個驗證碼功能,隨機產生10以內的加減法,用戶需要計算出正確的結果才能通過驗證。
本例基於上例Yii Framework 開發教程(20) UI 組件 Captcha示例,做如下修改
首先在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,
));
}

本例下載:http://www.imobilebbs.com/download/yii/CustomCaptchaDemo.zip