Yii Framework, how to add Google reCAPTCHA 2 to your site

February 9, 2017 15 Yehor Rykhnov

A simple example additing and work with Google reCAPTChA 2 in Yii Framework

Add reCAPTCHA API key

The first thing you need to do is add reCAPTCHA API key. Open Manager reCAPTCHA API on link: https://www.google.com/recaptcha/admin. Fill next fields: label and domains. After filling these fields you get a "Site key" and a "Secret key", which will need further.

Yii framework, add Google reCAPTCHA 2

To work with Google reCAPTCHA we need use extension, you can download it from the site devreadwrite.com or from the github repository: github.com/dakiquang/yiiReCaptcha.

Unpack the archive to a folder /protected/extensions/yiiReCaptcha.

Add extension to your config file /protected/config/main.php in components:

<?php

return array(
    //...

    'components'=>array(
        //...

        'reCaptcha' => array(
            'name' => 'reCaptcha',
            'class' => 'ext.yiiReCaptcha.ReCaptcha',
            'key' => '<Site key>',
            'secret' => '<Secret key>',
        ),

    ),
);

In the model for which you want to use Google's reCAPTCHA 2 add a public variable $verifyCode and in method rules add handling reCAPTCHA 2:

class ModelForm extends CFormModel {

    //...
    public $verifyCode;

    public function rules() {
    //...
        return array(
            array('verifyCode', 'required'),
            array('verifyCode', 'ext.yiiReCaptcha.ReCaptchaValidator'),
        );
    }
}

Add block with reCAPTCHA 2 to the right place in the view:

<?php

$this->widget('ext.yiiReCaptcha.ReCaptcha', array(
    'model'     => $model,
    'attribute' => 'verifyCode',
    //'isSecureToken' => true, //for multiple domains
));

Example integration reCAPTCHA 2 to the form

Let us consider an example of integration reCAPTCHA 2 to the standard form of feedback. Download and unpack the archive with the extension, add an extension to the configuration file /protected/config/main.php. File takes the form (major changes in the strings 38-43):

<?php

return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Web Application',

    'preload'=>array('log'),

    'import'=>array(
        'application.models.*',
        'application.components.*',
    ),
    'modules'=>array(
    ),

    'components'=>array(

        'user'=>array(
            'allowAutoLogin'=>true,
        ),

        'db'=>require(dirname(__FILE__).'/database.php'),

        'errorHandler'=>array(
            'errorAction'=>YII_DEBUG ? null : 'site/error',
        ),

        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),                
            ),
        ),

        'reCaptcha' => array(
            'name' => 'reCaptcha',
            'class' => 'ext.yiiReCaptcha.ReCaptcha',
            'key' => '6LcIzBQUAAAAAH4D5uZJp1K7LM1Pngivb3uwjGZE',
            'secret' => '6LcIzBQUAAAAAOf-zvcg9pkclzSjNyym5tvL1lWA',
        ),

    ),
    'params'=>array(
        'adminEmail'=>'webmaster@example.com',
    ),
);

Edit the model of the feedback form. In standard form already have a variable for CAPTCHA. You need remove or comment out the old rule validation and add a new. File /protected/models/ContactForm.php (strings: 18-19):

<?php

class ContactForm extends CFormModel
{

    public $name;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;

    public function rules()
    {
        return array(
            array('name, email, subject, body', 'required'),
            array('email', 'email'),
            //array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
            array('verifyCode', 'required'),
            array('verifyCode', 'ext.yiiReCaptcha.ReCaptchaValidator'),
        );
    }

    public function attributeLabels()
    {
        return array(
            'verifyCode'=>'Verification Code',
        );
    }
}

Adding to the view block with reCAPTCHA 2 and remove the block from the old CAPTCHA. File /protected/views/site/contact.php (strings: 57-62):

<?php

$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
    'Contact',
);
?>

<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
    <?php echo Yii::app()->user->getFlash('contact'); ?>
</div>

<?php else: ?>

<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'contact-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
    ),
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>
    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'name'); ?>
        <?php echo $form->textField($model,'name'); ?>
        <?php echo $form->error($model,'name'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'email'); ?>
        <?php echo $form->textField($model,'email'); ?>
        <?php echo $form->error($model,'email'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'subject'); ?>
        <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
        <?php echo $form->error($model,'subject'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'body'); ?>
        <?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
        <?php echo $form->error($model,'body'); ?>
    </div>

    <?php
    $this->widget('ext.yiiReCaptcha.ReCaptcha', array(
        'model'     => $model,
        'attribute' => 'verifyCode',
    ));
    ?>

    <div class="row buttons">
        <?php echo CHtml::submitButton('Submit'); ?>
    </div>

<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>

Result: