PHP development framework YiiFramework tutorial (21) UI component custom Captcha example
The Yii built-in Captcha can basically meet most of the requirements. if you have special requirements on the verification code, you can customize Captcha.
It is implemented by extending CCaptchaAction. In this example, a verification code function is defined to randomly generate addition and subtraction less than 10.
The user must calculate the correct results to pass the verification.
This example is based on the Captcha sample of the UI component in the previous Yii Framework Development Tutorial (20 ).
First, create a MathCaptchaAction in the protected/components directory and reload generateVerifyCode,
RenderImage and other methods:
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;
}
}
}
Modify the rules of SiteController and use the newly created MathCaptchaAction.
Public function actions ()
{
Return array (
'Captcha '=> array (
'Class' => 'mathcaptchaaction ',
'Minlength' => 1,
'Maxlength' => 10,
)