phpyiiyii2captchaimagick

How to add captcha in Yii-2 application?


I'm trying to add the captcha to the login form.

My environment:

In login.php, LoginForm.php and SiteController.php I added the following (shown only the relevant parts):

backend\views\site\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'],
    ];
}

backend\controllers\SiteController.php:

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

I have downloaded and installed ImageMagick-7.0.2-Q16

As described here I have downloaded php_imagick-3.4.1-5.4-ts-vc9-x86.zip and extract php_imagick.dll from there. Then added php_imagick.dll in /php/ext/

In php.ini I added the following:

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

Then restart IIS, but captcha is not displayed and I see the following in the logs:

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

After restarting the operating system:

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

I read somewhere that the most recent version is working on Windows 10 but need to install the Visual C++ 2013 Redistributable Package. I checked that this package is installed.

How to add captcha in Yii-2 application? I tried different combinations of the ImageMagick and php_imagick.dll, but nothing is working.


Solution

  • I think this should work

    <?= $form->field($model, 'captcha')->widget(Captcha::className(), 
                ['template' => '<div class="captcha_img">{image}</div>'
                    . '<a class="refreshcaptcha" href="#">'
                    . Html::img('/images/imageName.png',[]).'</a>'
                    . 'Verification Code{input}',
                ])->label(FALSE); ?> 
    

    what i have done is, added a template which contains a captcha image, a refresh captcha image(provide suitable path), a label to the field and an input field for text.