Milind Daraniya

How to Add Google reCAPTCHA in Yii 2

Published August 6th, 2023 16 min read

Google reCAPTCHA is a widely used tool to protect your website from spam and abuse. Integrating reCAPTCHA into your Yii 2 application can help enhance its security and user experience. In this tutorial, we'll guide you through the steps to add Google reCAPTCHA to a Yii 2 application.

Step 1: Obtain reCAPTCHA API Keys

Before you begin, you need to obtain reCAPTCHA API keys. Visit the reCAPTCHA website (https://www.google.com/recaptcha) and sign up for an account. After registering your site, you'll receive a Site Key and a Secret Key.

Step 2: Install reCAPTCHA Library

Yii 2 has a wrapper for the reCAPTCHA library. To install it, open your terminal and navigate to your project directory. Run the following command:

composer require himiklab/yii2-recaptcha-widget

Step 3: Configure the Widget

In your Yii 2 application, open the configuration file (config/web.php) and add the following lines to configure the reCAPTCHA widget:

return [
    // ...
    'components' => [
        // ...
        'reCaptcha' => [
            'class' => 'himiklab\yii2\recaptcha\ReCaptchaConfig',
            'siteKeyV2' => 'YOUR_SITE_KEY',
            'secretV2' => 'YOUR_SECRET_KEY',
            // Uncomment the following lines if you want to use reCAPTCHA v3
            //'siteKeyV3' => 'YOUR_V3_SITE_KEY',
            //'secretV3' => 'YOUR_V3_SECRET_KEY',
        ],
    ],
];

Replace YOUR_SITE_KEY and YOUR_SECRET_KEY with the keys you obtained from the reCAPTCHA website.

Step 4: Use the Widget in a Form

In your Yii 2 application's form, you can now add the reCAPTCHA widget. For example, if you're using Yii's ActiveForm, you can include the reCAPTCHA widget like this:

use yii\widgets\ActiveForm;
use himiklab\yii2\recaptcha\ReCaptcha;

$form = ActiveForm::begin();
// ... Your other form fields ...

// Add the reCAPTCHA widget
echo $form->field($model, 'reCaptcha')->widget(ReCaptcha::class);

// ... Submit button and form end ...
ActiveForm::end();

Step 5: Validate reCAPTCHA

In your controller action, make sure to validate the reCAPTCHA response before processing the form submission:

use Yii;

public function actionSubmitForm()
{
    $model = new YourFormModel();

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        // Validate reCAPTCHA response
        if (!$model->validateReCaptcha()) {
            $model->addError('reCaptcha', 'reCAPTCHA verification failed.');
            return $this->render('form', ['model' => $model]);
        }

        // Process the form submission
        // ...
    }

    return $this->render('form', ['model' => $model]);
}

Conclusion

By adding Google reCAPTCHA to your Yii 2 application, you can significantly improve its security and protect it from spam and abuse. With the help of the Yii 2 reCAPTCHA wrapper, integrating reCAPTCHA into your forms is straightforward and effective. Users will appreciate the enhanced security measures, and you'll have greater peace of mind regarding the integrity of your application. Happy coding and stay secure!