bitninja/ninja-recaptcha

Library to help using Google's ReCaptcha service.

1.1.5 2020-03-24 19:48 UTC

This package is auto-updated.

Last update: 2024-03-25 06:04:53 UTC


README

A library to make Google's reCAPTCHA easier to integrate.

Capabilities

  • It adds a layer of abstraction so you can easily replace Google's reCAPTCHA with a different captcha provider's solution by implementing the appropriate interfaces.
  • Separated classes for the view and the logic for verifying the responses.
  • It provides a simple solution with a pre-made form to be used anywhere on your site.
  • It also provides a more advanced solution in which you can build and customize your form in a way similar to the manipulation of DOM trees. These forms are also easily reusable.

Including ninja reCAPTCHA into your project

You'll need to add the following entries to your composer.json

{
"require": {
        "bitninja/ninja-recaptcha": "1.1.*"
},
"repositories": [
        {
                "type": "vcs",
                "url": "git@bitbucket.org:bitninjaio/ninjarecaptcha.git"
        }
]

}

Using the pre-made form

In order to use Google's reCAPTCHA service, you'll need to claim a secret and a site key. In the following examples, I'll use a test site key, which accepts every attempt and therefore it's insecure to use in a production environment.

To instantiate the classes required to render and verify the CAPTCHA, you should use the BitNinja\NinjaReCaptcha\GReCaptchaFactory class.

const SITE_KEY = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI";
const SECRET_KEY = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe";

$recaptchaFactory = new BitNinja\NinjaReCaptcha\GReCaptchaFactory(SECRET_KEY, SITE_KEY, $logger);

Here, $logger must be an implementation of PSR3's Logger Interface (see here and here). If you don't need any logging, you can use Devedge's NoLog class.

Using this factory, you can create the appropriate classes for rendering the CAPTCHA form and verifying the response.

Viewing the CAPTCHA

You can render the CAPTCHA form using the following code. The value of VERIFICATION_FORM_URI will be the action property of the form, the response will be sent to that URI.

const VERIFICATION_FORM_URI = "simple_verify.php";
$challengeView = $recaptchaFactory->createChallengeView();
echo $challengeView->render(VERIFICATION_FORM_URI);

Verifying the response

You can verify the response using the following code.

$challengeVerifier = $recaptchaFactory->createChallengeVerifier();
$result = $challengeVerifier->verify($_POST, $_SERVER['REMOTE_ADDR']);
var_dump($result);
if ($result===true)
{
                echo "Mkay.";
} else {
                echo "You shall not pass.";
}