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
查看全套教程:http://www.bianceng.cn/webkf/PHP/201301/35265.htm