在使用yii高级版做页面时,后台登陆用到了验证码,这个很简单,yii给出了示例:
1: 在LoginForm添加验证规则
public $verifyCode;
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
['verifyCode', 'captcha'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
2、在控制器中使用验证
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'height' => 49,
'width' => 120,
'minLength' => 4,
'maxLength' => 4
],
];
}
3、在页面显示验证码
<div class="code-box">
<div class="code-input"><?= $form->field($model, 'verifyCode')->textInput(['autofocus' => true, 'placeholder'=>yii::t('common', 'verifyCode')])->label(false) ?></div>
<div class="code-img"><?= Captcha::widget(['name'=>'captchaimg','captchaAction'=>'site/captcha','imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;'],'template'=>'{image}']);?></div>
</div>
$("#captchaimg").click(function(){
$.ajax({
url: "<?=Url::to(['site/captcha', 'refresh'=>true])?>",
dataType: 'json',
cache: false,
success: function(data) {
$("#captchaimg").attr('src', data['url']);
}
});
});
然而在前端页面,由于我不想使用bootstrap,就把自带的assets文件夹删除了,而我想做在线留言功能,也需要验证码,这就需要自己去验证了
1、在控制器加入验证码
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'height' => 32,
'width' => 80,
'minLength' => 4,
'maxLength' => 4
],
];
}
2、在页面显示验证码
<tr>
<td width="60" height="40" valign="middle" class="ly">验 证 码</td>
<td><input style="padding-left:2px; height:30px; width:160px; border:#CCC 1px solid; line-height:30px;" name="code" type="text" id="code" size="24">
<img src="<?=Url::to(['message/captcha'])?>" style="vertical-align:middle;"></td>
</tr>
3、验证
$code = Yii::$app->request->post('code');
if($code == ''){
return $this->redirect(['index']);
}
$captcha = $this->createAction('captcha');
if(!$captcha->validate($code, false)){
return $this->redirect(['index']);
}