How to use google reCAPTCHA in website with PHP code example

To implement Google reCAPTCHA on your website, You need Google reCAPTCHA Site Key , Secret Key. You can find that detail by reading How to setup Google Recaptcha on your website post.

Create web form in your file. Add google reCAPTCHA script and  Add google reCAPTChA div inside your form. you can get the div code from google reCAPTCHA site when created the reCAPTCHA. Replace the REPLACE_WITH_YOUR_SITE_KEY with actual key.

 

//google reCAPTCHA script
<script src='https://www.google.com/recaptcha/api.js'></script>

// form which having google reCAPTCHA div
<form action="" method="post">
	User Name: <input type="text" name="username">
	Email: <input type="email" name="email">

	<div class="g-recaptcha" data-sitekey="REPLACE_WITH_YOUR_SITE_KEY"></div>

	<input type="text" tye="button" value="submit">
</form>

 

When form submit to  PHP file , you need to add following code that verify your reCAPTCHA.

 

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
    //your site secret key
    $secret = REPLACE_WITH_YOUR_SECRET_KEY;
    //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)
    {
        // add your code
    }
    else
    {
        $errMsg = 'Robot verification failed, please try again.';
    }
}
else
{
    $errMsg = 'Please click on the reCAPTCHA box.';
}

 

Woo! Your reCAPTCHA code is run.

 

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes1
No0
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.