程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP開發框架Yii Framework教程(21) UI 組件 自定義Captcha示例

PHP開發框架Yii Framework教程(21) UI 組件 自定義Captcha示例

編輯:PHP綜合

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved