Google reCAPTCHA v2 Integration in PHP [with Example]

Getting fake inquiries, comments, and messages from users is really a headache. To get rid of spamming there are several libraries and tools which may solve this problem. But spammers usually find a way to bypass that spam prevention tool. Google also offers a spam filtering service called Google reCAPTCHA that minimizes the chances of getting spam. In this tutorial we will see how to integrate google reCAPTCHA v2 in PHP.

Steps in getting Google reCAPTCHA V2 Site Key and Secret Key:

  • First of all go to https://www.google.com/recaptcha/admin/create
  • Add label e.g: MySite
  • Select reCAPTCHA v2
  • Add domain name (e.g wdb24.com, example.com). For local host testing type localhost
  • Accept term of service and Submit
  • After submission you will receive SITE KEY and SECRET KEY
register google reCAPTCHA v2 site key secret key
google reCAPTCHA v2 site key secret key

Steps in Google reCAPTCHA v2 Integration in PHP:

  • Create a form and add before submit button.
  • Add api.js in footer like this
  • Once form will submit, get the user’s response token in $_POST['g-recaptcha-response'].
  • Verify token by sending it to https://www.google.com/recaptcha/api/siteverify?secret=SECRET_KEY&response=G-RECAPTCHA-RESPONSE.
  • Verify token returns JSON response with 4 keys.
    • Success : true|false
    • challenge_ts: timestamp,
    • hostname: string,
    • error-codes:[…]
  • If response success returns true, User is legit otherwise user is fake.

Now let’s see a working example of google reCAPTCHA v2 in PHP. I will create a simple contact form with no validation and database insertion code. Here my aim is to show you the integration process.

HTML:

In the above HTML I have used bootstrap for styling. $error_code and $success_msg will print error and success messages. $captchaSiteKey variable holds the Site Key.

PHP:

In the above code $captchaSiteKey and $captchaSecretKey holds SITE KEY and SECRET KEY. curlRequest() is a custom PHP function that takes url as a parameter and will return json response after using CURL. Next I have added isset condition for submit and g-catpcha-response. If both have values, then I will get g-catpcha-response response and send to google. Once I will receive the JSON response in $verifyRecaptcha. I will decode it and match $decodeGoogleResponse['success'] key. If $decodeGoogleResponse['success'] equals to 1 which means user is legit and I can add contact form data in database. Otherwise use is fake and I will print invalid captcha error.

 

Posted in PHP

Leave a Reply

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