【发布时间】:2020-01-15 08:41:26
【问题描述】:
我在我的项目中使用默认验证码,我有 2 个问题:
1- 刷新浏览器后,不要更改验证码。
2- 当用户未在页面上处于活动状态时,验证码不会过期。
我也读过这个link 但它对我没有帮助。因为它在我的代码 YII_ENV_TEST 中设置为空。并在 actionCaptcha 类中运行操作有一种方法可以在页面刷新期间更改验证码显然!!。
我在这里发布代码,但是尽管这些是在 Yii2 中使用 Captcha 的默认代码。
在供应商\yiisoft\yii2\captcha\CaptchaAction.php 中
class CaptchaAction extends Action
{
const REFRESH_GET_VAR = 'refresh';
.
.
.
public function run()
{
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
// AJAX request for regenerating code
$code = $this->getVerifyCode(true);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
// we add a random 'v' parameter so that FireFox can refresh the image
// when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid('', true)]),
];
}
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode());
}
.
.
.
}
在控制器/sitecontoller.php 中
/**
* {@inheritdoc}
*/
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
在我看来
<?php
$form = ActiveForm::begin([
'id' => 'login-form',
'enableAjaxValidation' => true,
'enableClientValidation' => false,
'validateOnBlur' => false,
'validateOnType' => false,
'validateOnChange' => false,
])
?>
<?=
$form->field($model, 'captcha')->widget(Captcha::className(), [
'captchaAction' => ['/site/captcha']])
?>
....
【问题讨论】:
-
在站点控制器中设置
verifyCode => true -
@mohsen 当我在 siteController 添加 verifyCode => true 时。不要加载我的验证码,我在 runActions 中添加 verifyCode => true ,在 fixedVerifyCode 之后。 : 它是否正确? public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode ' => YII_ENV_TEST ? 'testme' : null, 'verifyCode' => true, ], ]; }
标签: yii2 captcha page-refresh