Site icon WDB24

Google reCAPTCHA v2 Integration in PHP [with Example]

wdb24.com - web development blog

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:

Steps in Google reCAPTCHA v2 Integration in PHP:

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.

Exit mobile version