Online Snippets Library

Google reCAPTCHA Example In PHP

Google reCAPTCHA service is used to protect website from spams and abuse.Here we will learn how to integrate NO CAPTCHA reCAPTCHA into our website.

We will following step to integrate No CAPTCHA reCAPTCHA into our website.

Step 1

First we will register website and get Secret Key

you can register your website on Google recaptcha from here.

Step 2

Google Provide site key and secret key that we will use in our website.

6LcGMwYTAAAAAD2-R--x7fIFa1BCi-sBigk84H0D //sitekey 6LcGMwYTAAAAAHLQqtEDr-fR4OEY07u5sxoELoHV&response= //secretkey Step 3

We have to integrate below line before "head" tag.

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

To show No CAPTCHA reCAPTCHA widget in form add below code in your form.

<div class="g-recaptcha" data-sitekey="== Your site Key =="></div> Step 5

Now we create captcha.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Google reCAPTCHA Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://www.google.com/recaptcha/api.js'></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<h1>Google reCAPTHA Example</h1>
<form id="comment_form" action="captcha.php" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="pwd" id="pwd" placeholder="Enter password">
</div>
<input type="submit" name="submit" value="Post comment"><br><br>
<div class="g-recaptcha" data-sitekey="6LcGMwYTAAAAAD2-R--x7fIFa1BCi-sBigk84H0D"></div>
</form>
</div>

</body>
</html>
Step 6

Now we create captcha.php

<?php 
if(isset($_POST['submit']))
{
$email=$_POST['email'];
$pwd=$_POST['pwd'];
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcGMwYTAAAAAHLQqtEDr-fR4OEY07u5sxoELoHV&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$jsonResponse = json_decode($response);
if($jsonResponse->success==false)
{
echo '<p>You are spammer !</p>';
}else
{
echo '<p>Thanks for your comment.</p>';
}
}?>