Integrating Google reCAPTCHA with Symfony Forms: A Step-by-Step Guide
In today’s digital age, protecting your website from spam and bots is crucial. Google reCAPTCHA offers a free and effective solution. This guide will walk you through integrating reCAPTCHA with Symfony forms.
Registering Your Site on Google reCAPTCHA
- Sign In and Register:
- Visit Google reCAPTCHA and sign in with your Google account.
- Click on the “Get reCAPTCHA” button and fill out the registration form.
2. Setting the Label:
- Choose a label that will help you identify your site easily.
3. Choosing reCAPTCHA Type:
- Checkbox: Users click a checkbox to prove they’re not robots.
- Invisible: Less intrusive, triggered via a JavaScript API call.
Note: A site can only use one reCAPTCHA type.
4. Setting Domains:
- Add your domain(s). This ensures reCAPTCHA only works on these domains. For testing, use
localhost
.
5. Generate Keys:
- Obtain your site key and secret key.
Configuring Your Symfony Application
- Install reCAPTCHA PHP Library:
Run the following command from your project directory:
composer require google/recaptcha
2. Add API Keys in .env File:
RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key
3. Register reCAPTCHA Class as a Service:
- Define the service in your configuration file.
4. Add a Twig Global Variable:
Add the site key as a global variable so it’s available in all Twig templates.
Adding reCAPTCHA to Your Forms
- Integrate reCAPTCHA in Forms:
Add the data-sitekey
attribute to your form field.
<div class="g-recaptcha" data-sitekey="{{ recaptcha_site_key }}"></div>
2. Include reCAPTCHA Script:
Add the script to your Twig template:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Verifying reCAPTCHA Response
When the form is submitted, Google sends g-recaptcha-response
as POST data. Verify it in your controller to ensure the user is human.
use ReCaptcha\ReCaptcha;
$recaptcha = new ReCaptcha($secret);
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
// Verified!
} else {
// Verification failed
}
Conclusion
Integrating Google reCAPTCHA with Symfony forms is straightforward and significantly enhances your site’s security. By following these steps, you can protect your website from unwanted spam and bot activities.