生成驗證碼
在要使用驗證碼的Controller里面實現actions方法:
<?php
class TestController extends Controller{
public function actions(){
return [
'captchatest' => [
'class' => CaptchaAction::className(),
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,//本行可能引起更換驗證碼失效,必須刷新瀏覽器
'backColor' => 0x66b3ff,//背景顏色
'maxLength' => 4,//最大顯示個數
'minLength' => 4,//最少顯示個數
'padding' => 6,//驗證碼字體大小,數值越小字體越大
'height' => 34,//高度
'width' => 100,//寬度
'foreColor' => 0xffffff,//字體顏色
'offset' => 13,//設置字符偏移量
]
];
}
}
以上代碼通過實現actions方法創建了一個叫captchatest的action,上面的action我只填了兩個參數,還有其他參數可以參考yii\captcha\CaptchaAction的publish屬性
在頁面中使用驗證碼,在要使用驗證碼的view里面插入以下代碼:
<?php
use \yii\captcha\CaptchaAction;
echo Captcha::widget([
'name'=>'captchaimg',
'captchaAction'=>'captchatest',
'imageOptions'=>['id'=>'captchaimg', 'title'=>'換一個', 'alt'=>'換一個','style'=>'cursor:pointer;margin-top:10px; height: 22px;'],
'template'=>'{image}']);
// 以上代碼主要需要正確填寫captchaAction,填寫你剛才創建的captchaAction,需要完整的namespace,然后會生成一個img
驗證驗證碼,在action中接收到表單傳來的驗證碼后,使用:
$this->createAction('captchatest')->validate($captchCode, false);
$captchCode為用戶輸入的驗證碼,validate函數會返回true/false,該函數的第二個參數為是否對大小寫敏感
點擊刷新驗證碼
生成的驗證碼有時用戶看不清楚,需要重新刷新,可以使用該圖片的url加上refresh參數,然后會返回一個json數據,其中有一個url的屬性,調用該url即可獲取新驗證碼,
如圖片地址為:/index.php?r=test%2Fcaptchatest&v=5680ce41e9cb0
刷新地址便是:/index.php?r=test%2Fcaptchatest&v=5680ce41e9cb0&refresh=1
JS代碼如下:
<script>
$(function(){
$("#captchaimg").click(function(){
var imgUrl = $("#captchaimg").attr('src');
$("#captchaimg").attr('src', imgUrl+'&refresh=1');
});
})
</script>
解決頁面刷新驗證碼不刷新
只需要繼承 \yii\captcha\CaptchaAction
,然后重寫 run() 方法中調用為 getVerifyCode(true) 可以解決問題
<?php
namespace admin\controllers\action;
use yii\web\Response;
class CaptchaAction extends \yii\captcha\CaptchaAction
{
/**
* 默認驗證碼刷新頁面不會自動刷新
*/
public function run()
{
$this->setHttpHeaders();
\Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode(true));
}
}
在 SiteController 控制器中注冊 CaptchaAction 方法:
<?php
public function actions()
{
return [
//默認驗證碼刷新頁面不會自動刷新
'captcha' => [
'class' => 'admin\controllers\action\CaptchaAction', // 注意這是重寫后的CaptchaAction
'testLimit' => 1,
'maxLength' => 6,
'minLength' => 6,
'padding' => 1,
'height' => 50,
'width' => 140,
'offset' => 1,
],
];
}
設置驗證碼驗證規則:
<?php
class JoinForm extends \yii\base\Model
{
/**
* 驗證碼
* @var
*/
public $captcha;
... ...
/**
* 規則
*/
public function rules()
{
return [
[['captcha'], 'required'],
//驗證碼校驗
['captcha', 'captcha', 'captchaAction' => '/site/captcha'],
];
}
}