如何在 Yii-2 应用程序中添加验证码?

2024-01-29

我正在尝试将验证码添加到登录表单中。

我的环境:

  • Yii 2
  • PHP 5.4.45 版本
  • IIS 10.0
  • Windows 10

In login.php, LoginForm.php and SiteController.php我添加了以下内容(仅显示相关部分):

后端\视图\站点\login.php:

use yii\captcha\Captcha;
...
<?= $form->field($model, 'captcha')->widget(Captcha::className()) ?>
...

common\models\LoginForm.php:

...
public $captcha;
...
public function rules()
{
    return [
        ... 
        [['username', 'password', 'captcha'], 'required'],           
        ['captcha', 'captcha'],
    ];
}

后端\控制器\SiteController.php:

public function actions()
{
    return [
        ...
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
    ];
}

我已经下载并安装了ImageMagick-7.0.2-Q16 https://www.imagemagick.org/script/download.php

如上所述here https://pecl.php.net/package/imagick/3.4.1/windows我已经下载了 php_imagick-3.4.1-5.4-ts-vc9-x86.zip 并从那里提取 php_imagick.dll 。然后添加 php_imagick.dll 在/php/ext/

In php.ini我添加了以下内容:

...
[PHP_IMAGICK]
extension=php_imagick.dll
...

然后重新启动 IIS,但未显示验证码,我在日志中看到以下内容:

2016-08-10 07:28:21 [127.0.0.1][-][h1a65krn8scqc9auk56flmesi6][error][yii\base\InvalidConfigException] exception 'yii\base\InvalidConfigException' with message 'Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.' in C:\projects\aisnew\vendor\yiisoft\yii2\captcha\Captcha.php:180

重新启动操作系统后:

2016-08-10 07:01:22 [127.0.0.1][-][h1a65krn8scqc9auk56flmesi6][error][yii\base\ErrorException:32] exception 'yii\base\ErrorException' with message 'PHP Startup: ' in Unknown:0

我在某处读到最新版本可以在 Windows 10 上运行,但需要安装 Visual C++ 2013 Redistributable Package。我检查了这个软件包是否已安装。

如何在 Yii-2 应用程序中添加验证码?我尝试了 ImageMagick 和 php_imagick.dll 的不同组合,但没有任何效果。


我刚刚为我的 Yii2 网站制作了自定义代码。这是一个基于文本的验证码。检查一下是否可以帮助您。 在模型中:-

public $captcha;
public $recaptcha;

......

[['name', 'captcha','recaptcha'], 'required'],
['recaptcha', 'compare', 'compareAttribute' => 'captcha', 'operator' => '=='],

在控制器中的这一行定义 $model 后创建和更新操作:-

$model->captcha = rand(11111,99999);

并在视图部分添加这些行:-

<?= $form->field($model, 'captcha')->hiddenInput()->label(false) ?>
<div class="form-group">
     <mark><b><?= $model->captcha ?></b></mark>                    
</div>
<?= $form->field($model, 'recaptcha')->textInput(['placeholder' => 'Enter Captcha'])->label(false) ?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Yii-2 应用程序中添加验证码? 的相关文章

随机推荐