How to implement reCaptcha v3

This post explains how to implement the Google reCaptcha v3 easily in your site code.

You can use this method or code in any PHP site, including WordPress, Joomla!, Drupal, etc.

The code consists of three parts:

  1. Generate site-key and secret-key from google recaptcha for your site
  2. First part of code goes into your form page where you have the form which is submitting the data.
  3. Second part of code that goes on the backend code which receives the submitted form data and works with it.

Lets see the simple code example which you can copy to your project.

Generate site-key & secret-key from google recaptcha admin panel

To generate the google recaptcha site key and secret key, follow these steps:

  1. Go to: https://www.google.com/recaptcha/admin/create
  2. register a new site with type v3 for google recaptcha
  3. save the site-key and secret-key shown in the end, or keep the page open to copy them in steps below.

Frontend code for Google reCaptcha v3

The following code goes on the frontend of your page that contains the code for the form.

<script src="https://www.google.com/recaptcha/api.js?render=<site-key>"></script>
<script>
  grecaptcha.ready(function() {
   grecaptcha.execute("<site-key>", {action: "anythinghere"})
   .then(function(token) {
    console.log(token)
    document.getElementById("g-recaptcha-response").value = token;
   }); 
  }); 
 </script>

<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response" value="" />

Change <site-key> in two places above to your google recaptcha v3 site secret and anythinghere to what you want (not important in this simple implementation.

Also, move the input field inside your form.

Backend code for Google reCaptcha v3

The backend code deals with the submitted form data.

Assuming that you submitted the form using method="post", we can use the following code:




if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ) {

	//your site secret key
	$secret = '';
	//get verify response data
	$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
	$responseData = json_decode($verifyResponse);
	if($responseData->success) {
	
		// your successful form submission related code here
	
	}
}

Change secret-key to your google recaptcha secret-key.

Please let me know if you’ve any difficulty in setting up google recaptcha v3 on your site and want me to do it for you.

hire best wordpress php css developer
Need Help? Hire me now!
I can help you in anything related to webdevelopment, including: HTML, CSS, PHP & MySql, WordPress (plugins & themes development, others), regular expressions, server management, etc.

Leave a Reply

Your email address will not be published.