Yii2自帶驗證碼實現
阿新 • • 發佈:2017-09-05
框架 point logs classname 行為 widget ive mage idg
總共分為三個方面:控制器配置、模型rules配置和視圖配置。
第一步:控制器配置
將下列代碼配置在actions中,請求驗證碼鏈接對應為 “控制器/captcha”
‘captcha‘ => [ ‘class‘ => ‘yii\captcha\CaptchaAction‘, // ‘backColor‘=>0x000000,//背景顏色 ‘maxLength‘ => 4, //最大顯示個數 ‘minLength‘ => 4,//最少顯示個數 ‘padding‘ => 5,//間距 ‘height‘=>45,//高度 ‘width‘ => 75, //寬度 // ‘foreColor‘=>0xffffff, //字體顏色 ‘offset‘=>4, ],
第二步:模型rules配置,即驗證配置。
首先聲明公共變量
public $verifyCode
其次在rules方法中配置驗證
[‘verifyCode‘, ‘captcha‘,‘captchaAction‘=>‘user/captcha‘,‘on‘ => [‘login‘]]
在這條配置中的"captchaAction"加入了配置,即控制器的路由,如果不進行配置的話會走site/captcha的路由,這是框架樣例的路由。
第三步:視圖中的配置
在ActiveForm中加入如下代碼即可了
<?= $form->field($model,‘verifyCode‘)->widget( Captcha::className(), [ ‘template‘ => ‘{image}{input}‘, ‘captchaAction‘=>‘user/captcha‘, // 此註意要使用自己配置的那個控制器驗證碼路由 ‘imageOptions‘=>[ ‘style‘=>‘cursor:pointer;width:77px‘] ] )
最後有一個巨坑的問題:由於編碼過程中使用了一些windows下的換行符或者空格,導致了未知的輸出,會導致驗證碼圖片不能夠正常的生成。
這是需要在CaptchaAction類中的renderImageByGD方法中加入如下代碼:
imagecolordeallocate($image, $foreColor); ob_clean(); // 此行為插入代碼,目的是清空緩存區為輸出圖片提供幹凈空間。 ob_start(); imagepng($image); imagedestroy($image);
Yii2自帶驗證碼實現