How to use contact us form and Google reCAPTCHA v2.0 with PHP?

Step 1: Register and Get Google reCaptcha API keys

Google reCaptcha will be used if and only of you have both site key and secret key. You can’t use the reCaptcha on your website without special API keys. To get them go to the official Google Recaptcha website.

Once you have registered your website; it’s time to get your site key which is used to display the reCaptcha widget on your web page.

Google Recaptca Site Key

Also don’t forget to get your secret key because your site will use it for communicating with the reCaptcha server.

Google Recaptcha Secret Key

Step 2: Add the Google reCaptcha to your site

Open your website or the page where you want to use the reCaptcha with any text editor (Notepad++ is a good choice). Find your </head> closing tag and insert the following highlighted code:

<head>
 <!-- Here you can find many other tags. Leave them. -->
 <script src='https://www.google.com/recaptcha/api.js'></script>
</head>

Done! But… Wait! We forgot to update the PHP file that proceeds all data from the form! Have a look on the code snippet below, and try to integrate it into your existing code.

$secret_key = '6Lc6YjwUAAAAAKzgGGHAuJAb_thg9ipF2bc2ZiQr'; // Your Google reCaptcha secret key
 
if(!empty($_POST['g-recaptcha-response']))
{
 // Request the Google server to validate our captcha
 $request = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

 $response = json_decode($request);
 
 if($response->success)
 {
  echo 'Congratulations! You have passed the reCaptcha!';
 }
 else
 {
  echo 'Please, try again. You must complete the Captcha!';
 }
}

You have successfully integrated Google reCaptcha v2 to your php form.

2 thoughts on “How to use contact us form and Google reCAPTCHA v2.0 with PHP?

  • July 19, 2019 at 5:12 pm
    Permalink

    Hi, I just looked at your site and really impressed by it’s design and content. You are doing a great job by providing such data to the audience. Thank you so much.

    Reply
  • August 2, 2019 at 1:44 am
    Permalink

    Well I truly liked studying it. This post provided by you is very useful for proper planning.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *