Integrate Google reCAPTCHA v3 – Example in PHP (using AJAX)

Google reCAPTCHA is one of the best way to protect website from bots. Currently google provides V2 and V3 of reCAPTCHA. In this tutorial we are going to Integrate Google reCAPTCHA v3 in PHP. I am going to use Ajax form submit in my example.

Before jumping into the coding let see how reCAPTCHA v3 works.

In simple words, Google reCAPTCHA v3 is a javascript API which returns score on the basis of user interaction. It won’t show any image or code to fill in.

Get reCAPTCHA site key and secret key.

First of all you need to get site key and secret key for Google reCAPTCHA v3.

  • Site key will use in front end to get reCAPTCHA response
  • Secret key will use in backend to validate the response from reCAPTCHA.

For local testing use localhost as domain

google recaptcha v3 get keys
google recaptcha v3 site and secret key

Integrate Google reCAPTCHA v3 example in PHP

I will be using simple HTML form with 2 fields only.

google recaptcha form

Form HTML:

Below is the simple html form with 2 fields only. Also there is a hidden input type which will use in google response.

Javascript Code:

First of all I include Google reCAPTCHA script and pass my site key as render value. Then on form submit I invoke grecaptcha.ready function and under grecaptcha.ready I call grecaptcha.execute function which takes site key as first parameter and object as second parameter. In object parameter I pass action as a key with submit as a value. After getting the token, I will put that token value into hidden field and then I will trigger jquery ajax function to post the form response to ajax_response.php file

Ajax Response:

At the top of the file I have created a custom php function getData() which will trigger cURL get request. Then I am checking subject and message must have values. If any one of two come with empty value, I will return error response. $urlGoogleCaptcha holds google url. $recaptchaResonse calls getData() function with $urlGoogleCaptcha and $dataArray. $dataArray is an array having recaptcha secret key and google verfication response. $recaptchaResonse holds the google response in array (google returns response in json format getData() function convert json response into an array).

 

Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.