In this post we will be implementing an Ajax based reCAPTCHA v2 validation using PHP and jQuery.
Google’s new reCAPTCHA makes it easier for a user to attest that they are human by simple clicks, compared to the old reCAPTCHA where you have to figure out the CAPTCHA out of characters infused in distorted images.
You can check out the details of the new reCAPTCHA here – https://www.google.com/recaptcha/intro/index.html.
So to start, you’ll need first a Google account. One you have it, go to this link – https://www.google.com/recaptcha/admin then login with your account.
You can start creating the site and secret keys by registering a site. If you don’t have a domain, that would be ok as the keys would work fine on localhost.
After the registration, you should already see the keys
and the created site on the site list :
Now we can start to code.
Front-end code :
reCAPTCHA section and a form.
The jQuery code checks if the submit button is clicked, alerts if the reCAPTCHA is not checked and if checked, sends the reCAPTCHA information to the gocap.php script for Google validation and retrieves the result.
Loaded on a web server, code above will display :
Sometimes, the validation of the reCAPTCHA times out, this is encountered when the form is not immediately submitted after validating the reCAPTCHA.
Upon re-validation, the reCAPTCHA presents a more complex validation requirement. reCAPTCHA may also do this depending on its security algorithm on where / how the page is accessed.
This is the code for the gocap.php, the Google validator PHP script.
PHP script above gets called by the front-end aJax upon click of the submit button, reCAPTCHA validation information is submitted and the PHP code sends it to Google along with the secret key for the reCAPTCHA validation.