vihuvac/recaptcha-bundle

This bundle provides an easy reCAPTCHA form field integration into a Symfony Project

Installs: 52 903

Dependents: 2

Suggesters: 0

Security: 0

Stars: 9

Watchers: 1

Forks: 8

Open Issues: 2

Type:symfony-bundle

v2.2.0 2018-01-17 21:09 UTC

README

⚠️ DEPRECATED:

Unfortunately I want to inform this bundle is getting deprecated, I recommend using EWZRecaptchaBundle instead. Sorry for the inconvenience. 😔

This bundle provides easy reCAPTCHA form field for Symfony in order to protect your website from spam and abuse.

Latest Stable Version Latest Unstable Version Gitter License

Total Downloads Monthly Downloads Daily Downloads

Installation

Step 1: Using composer and enable the Bundle

To install the bundle via composer, just run from the command line (terminal):

$ composer require vihuvac/recaptcha-bundle

Composer will automatically download all the required files, and install them for you. All that is left to do is to update your AppKernel.php file, and register the new bundle:

// app/AppKernel.php

<?php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Vihuvac\Bundle\RecaptchaBundle\VihuvacRecaptchaBundle(),
    );
}

Step 2: Configure the bundle

Add the following to your config file:

# app/config/config.yml

vihuvac_recaptcha:
    site_key:   here_is_your_site_key
    secret_key: here_is_your_secret_key
    locale_key: kernel.default_locale

NOTE:

This bundle uses a secure API (HTTPS Protocol). Google API solves the requests by the Browser (Client).

The site_key parameter is the same than the public_key parameter and the secret_key parameter is the same than the private_key parameter (parameters used in the previous versions).

You can easily enable and disable the reCAPTCHA feature using any one of the booleans true or false through the enabled parameter, e.g:

# app/config/config.yml

vihuvac_recaptcha:
    // ...
    enabled: true

If you want to use the language used by the locale request as the language for the reCAPTCHA, you must activate the resolver (deactivated by default):

# app/config/config.yml

vihuvac_recaptcha:
    // ...
    locale_from_request: true

You can load the reCAPTCHA using the Ajax API (optional):

# app/config/config.yml

vihuvac_recaptcha:
    // ...
    ajax: true

Additionally you can add HTTP Proxy configuration (optional):

# app/config/config.yml

vihuvac_recaptcha:
    // ...
    host: proxy.your-domain.com
    port: 3128
    auth: proxy_username:proxy_password

In case you have turned off the domain name checking on reCAPTCHA's end, you'll need to check the origin of the response by enabling the verify_host option:

# app/config/config.yml

vihuvac_recaptcha:
    // ...
    verify_host: true

Congratulations! You're ready!

Basic Usage

When creating a new form class add the following line to create the field:

Symfony and PHP Reference
<?php

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", "vihuvac_recaptcha");
    // ...
}
Symfony and PHP Reference

Note:

To denote the form type, you have to use the fully qualified class name - like TextType::class in PHP 5.5+ or Symfony\Component\Form\Extension\Core\Type\TextType. Before Symfony 2.8, you could use an alias for each type like text or date. The old alias syntax will still work until Symfony 3.0. For more details, see the 2.8 UPGRADE Log.

<?php

use Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType as RecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", RecaptchaType::class);
    // ...
}

You can pass extra options to reCAPTCHA with the attr > options option, e.g:

<?php

use Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType as RecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", RecaptchaType::class, array(
        "attr" => array(
            "options" => array(
                "theme" => "light",
                "type"  => "audio",
                "size"  => "normal",
                "defer" => false,   // Set true if you want to use the Ajax API.
                "async" => false    // Set true if you want to use the Ajax API.
            )
        )
    ));
    // ...
}

reCAPTCHA tag attributes and render parameters:

Support Google's Invisible reCAPTCHA! It's super easy:

<?php

use Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType as RecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", RecaptchaType::class, array(
        "attr" => array(
            "options" => array(
                "theme"    => "light",
                "type"     => "image",
                "size"     => "invisible",          // Set size to the invisible reCAPTCHA.
                "defer"    => false,                // Set true if you are using the Ajax API.
                "async"    => false,                // Set true if you are using the Ajax API.
                "callback" => "onReCaptchaSuccess", // Callback will be set by default if it's not defined (along with JS function that validates the form on success).
                "bind"     => "buttonSubmit",       // This is the form submit button id (html attribute).
                // ...
             )
        )
    ));
    // ...
}

Note: If you use the pre-defined callback, you would need to add recaptcha-form class to your <form> tag.

If you need to configure the language for the reCAPTCHA depending on your site language (ideal for multi-language sites) you can pass the language with the "language" option:

<?php

use Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType as RecaptchaType;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", RecaptchaType::class, array(
        "language" => "en",
        // ...
    ));
    // ...
}

To validate the field use:

<?php

use Vihuvac\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;

/**
 * @Recaptcha\IsTrue
 */
public $recaptcha;

Another method would consist to pass the validation constraints as an options of your FormType. This way, your data class contains only meaningful properties. If we take the example from above, the buildForm method would look like this. Please note that if you set mapped => false then the annotation will not work. You have to also set constraints:

<?php

use Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType as RecaptchaType;
use Vihuvac\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaTrue;

public function buildForm(FormBuilder $builder, array $options)
{
    // ...
    $builder->add("recaptcha", RecaptchaType::class, array(
        "attr" => array(
            "options" => array(
                "theme" => "light",
                "type"  => "audio",
                "size"  => "normal"
            )
        ),
        "mapped"      => false,
        "constraints" => array(
            new RecaptchaTrue()
        )
    ));
    // ...

Cool! The form template resource is now auto registered via container extension. However, you can always implement your own custom form widget:

PHP:

<?php $view["form"]->setTheme($form, array("VihuvacRecaptchaBundle:Form")) ?>

<?php echo $view["form"]->widget($form["recaptcha"], array(
    "attr" => array(
        "options" => array(
            "theme" => "light",
            "type"  => "audio",
            "size"  => "normal"
        )
    )
)) ?>

Twig:

{% form_theme form "VihuvacRecaptchaBundle:Form:vihuvac_recaptcha_widget.html.twig" %}

{{
    form_widget(
        form.recaptcha, {
            "attr": {
                "options": {
                    "theme": "light",
                    "type": "audio",
                    "size": "normal"
                },
            }
        }
    )
}}

If you are not using a form, you can still implement the reCAPTCHA field using JavaScript:

PHP:

<div id="recaptcha-container"></div>
<script type="text/javascript">
    $(document).ready(function() {
        $.getScript("<?php echo \Vihuvac\Bundle\RecaptchaBundle\Form\Type\VihuvacRecaptchaType::RECAPTCHA_API_JS_SERVER ?>", function() {
            Recaptcha.create("<?php echo $form['recaptcha']->get('site_key') ?>", "recaptcha-container", {
                theme: "light",
                type: "audio",
                "size": "normal"
            });
        });
    };
</script>

Twig:

<div id="recaptcha-container"></div>
<script type="text/javascript">
    $(document).ready(function() {
        $.getScript("{{ constant('\\Vihuvac\\Bundle\\RecaptchaBundle\\Form\\Type\\VihuvacRecaptchaType::RECAPTCHA_API_JS_SERVER') }}", function() {
            Recaptcha.create("{{ form.recaptcha.get('site_key') }}", "recaptcha-container", {
                theme: "light",
                type: "audio",
                "size": "normal"
            });
        });
    });
</script>

Customization:

If you want to use a custom theme, put your chunk of code before setting the theme:

<div id="recaptcha_widget">
    <div id="recaptcha_image"></div>
    <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect please try again</div>

    <span class="recaptcha_only_if_image">Enter the words above:</span>
    <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>

    <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />

    <div><a href="javascript:Recaptcha.reload()">Get another CAPTCHA</a></div>
    <div class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type("audio")">Get an audio CAPTCHA</a></div>
    <div class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type("image")">Get an image CAPTCHA</a></div>

    <div><a href="javascript:Recaptcha.showhelp()">Help</a></div>
 </div>

{% form_theme form "VihuvacRecaptchaBundle:Form:vihuvac_recaptcha_widget.html.twig %}

{{
    form_widget(
        form.recaptcha, {
            "attr": {
                "options" : {
                    "theme" : "custom",
                },
            }
        }
    )
}}

Further reading: Google Official Doc.

Tests

Execute this command to run tests:

$ cd recaptcha-bundle/
$ ./vendor/bin/phpunit

Note: If you are running tests only and within the bundle, as first step you should run composer install in order to install the required dependencies. Then you'll be able to run the tests!