在项目公共目录直接创建captcha类:
class Captcha extends CCaptchaAction{
public function run(){
if (isset($_GET[self::REFRESH_GET_VAR])){
$code = $this->getVerifyCode(true);
echo CJSON::encode(array(
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
'url' => $this->getController()->createUrl($this->getId(), array('v' => uniqid())),
));
}else {
$this->renderImage($this->getVerifyCode(true));
Yii::app()->end();
}
}
}
在需要使用验证码的模型里面加上验证规则:
array('verifycode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'message' => '验证码错误!'),
在需要调用的控制器启动验证码组件: