How to display multiple recaptchas on a single page in PHP ?
RECAPTCHA is a free service from Google that helps to protect websites from spam and abuse. A “CAPTCHA” is a Turing test to tell humans and bots apart. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep malicious software from engaging in abusive activities on your website.
In this article, we are going to discuss how to display multiple Google reCAPTCHA v2 on a single page in PHP.
- Register your site at Google reCAPTCHA
- Submit the HTML form
- Get the response key on the server side
- Re-verify the key and give response to the user end.
Step 1: Register your site at Google reCAPTCHA — Register your website at Google reCAPTCHA to get the keys. The site key and server key are required to code the HTML form.
Click here to go to the Google reCAPTCHA website.
Step 2: Creating Google reCAPTCHA form in HTML — Create a Google reCAPTCHA form in HTML. We are going to create two forms, each with one input field and a button. Also, we will have an action page named action.php. To obtain reCAPTCHA in the HTML content, we must add a div element to the form and a Google reCAPTCHA CDN link to our HTML document.
CDN link : <script src=”https://www.google.com/recaptcha/api.js” async defer></script>
Div tag : <div class=”g-recaptcha” data-sitekey=”your_site_key”></div>
Note: You must substitute your Site Key for “your_site_key”.
Step 3: PHP Back end — Now let’s code the action page.
The “isset()” method is used on the server side to verify whether a valid form was submitted after the form has been submitted. Following the validation, we retrieved the name using the $name variable and the Google ReCaptcha response using the $recaptcha variable.
Step 4: Verify the captcha – We must send a post request to the following URL in order to validate the captcha.
- URL: https://www.google.com/recaptcha/api/siteverify?secret=<secret_key>&response=<response_key>
- secret_key: You will receive the secret key from the Google Console.
- response_key: When a user submits the form, this key is generated from the client side.
- The browser’s response key, known as g-recaptcha-response, is created when a form is submitted. If it’s empty or null, it signifies the user didn’t choose the captcha; thus, returns an error.