Google ReCAPTCHA server side validation-PHP

Hasitha Charaka 🔵
3 min readOct 30, 2020
reCAPTCHA

here is small process about how to validate HTML form using google recaptcha with server side validation

WHAT IS reCAPTCHA ?

reCAPTCHA is a free service that protect your site from spam and abuse.It used advanced risk analysis techniques to tell humans and bots apart.

How to Setup reCAPTCHA ?

first of all you need google account for use this service i assume you already own it.

the go to the this link :- https://www.google.com/recaptcha/admin

then click on the “+” button it will show below form insert

  1. label name
  2. reCAPTCHA type here i used reCAPTCHA v2 -> “I’m not a robot” Checkbox
  3. add domain (if you using local host just put localhost)
  4. add select the owner & accept the T&C
  5. submit the form

here is my form

after submit you will receive SITE KEY and SECRET KEY

copy those keys here is the sample html form and validation php script.

replace_your_site_key with copied site key
<?php
$email; $comment; $captcha;

if(isset($_POST['email']))
$email=$_POST['email'];
if(isset($_POST['comment']))
$comment=$_POST['comment'];
if(isset($_POST['g-recaptcha-response']))
$captcha=$_POST['g-recaptcha-response'];

if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}

$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
echo '<h2>You are spammer ! Get the @$%K out</h2>';
}
else
{
echo '<h2>Thanks for posting comment.</h2>';
}
?>

after replacing those keys all set now we have to check if it is working .

here is form output

fill the input fields and post it if it is success you will see message “ Thanks for posting comment.”

if not something went wrong check your secret-key & site-key are place correctly.

more info :- https://developers.google.com/recaptcha/intro

If you enjoy my content and would like to support me, you can do so through Buy Me a Coffee. Your support means the world to me and will help me to continue creating and improving the quality of my work. By buying me a coffee, you’ll be providing me with the motivation and resources to keep pursuing my passion and bringing you the content that you love. Your generosity will help cover the costs of hosting, equipment, and other expenses associated with my work. Thank you so much for considering supporting me through Buy Me a Coffee, and for being a part of my community!https://www.buymeacoffee.com/hasithacharaka

happy Coding ❤

--

--