首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii Framework 教程(21):自訂驗證碼 MathCaptchaAction 範例

     編輯:PHP 綜合知識

Yii 內建驗證碼滿足大部分需求,若有特殊需求可自訂驗證碼,主要透過擴展 CCaptchaAction 實現。本例自訂驗證碼:隨機產生 10 以內加減法,使用者需計算正確結果才能通過驗證。

建立 MathCaptchaAction

在 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 使用新驗證碼

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

執行結果

MathCaptchaAction 執行結果

範例下載:CustomCaptchaDemo.zip

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved