Yii 內建驗證碼滿足大部分需求,若有特殊需求可自訂驗證碼,主要透過擴展 CCaptchaAction 實現。本例自訂驗證碼:隨機產生 10 以內加減法,使用者需計算正確結果才能通過驗證。
在 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;
}
}
}
public function actions() {
return array(
'captcha' => array(
'class' => 'MathCaptchaAction',
'minLength' => 1,
'maxLength' => 10,
)
);
}
