Configure reCaptcha in your HTML/PHP website

 

 

 

reCaptcha is a good way to ensure some scripts/bots are not being used to fill your website forms with false registrations. Integrating this feature in your website forms that accept registration or login may prove invaluable. To embed reCaptcha by Google on your website, there are three steps to be followed.

1. Register with Google reCaptcha

2. Integrating on client side

3. Integrating on server side

1. Register for Google reCaptcha

Sign in to your Google Account (if you don’t already have a Google Account, sign up first) then visit www.google.com/recaptcha/admin
Click on reCAPTCHA version 2 and fill in the required fields. When finished, click on Save.

 

 

 

 

 

 

 

 

 

2. Client side integration.

Next, you will be rediredted to a page that shows a Site Key and Secret Key assigned to you. Also, you will see the java script code snippets that are supposeed to be used with your html pages.

Paste the first snippet before the closing </head> tag on your HTML template:

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

Paste
the second snippet at the end of the </form> where you want the
reCAPTCHA widget to appear:

<div
class="g-recaptcha" data-sitekey="*****Your Site Key
Here *****"></div>

3.
Server side integration.

Add
the following code to the php file that is used with your html form.
This is the file that is defined on the
<form
action=”file.php” >

region.
Make
sure to edit the regions marked with a different colour in the code
below to your custom values.

if(isset($_POST[‘save‘]))

{

function CheckCaptcha($userResponse) {

$fields_string = ”;

$fields = array(

‘secret’ => ‘****Your Scret Key Here*****‘,

‘response’ => $userResponse

);

foreach($fields as $key=>$value)

$fields_string .= $key . ‘=’ . $value . ‘&’;

$fields_string = rtrim($fields_string, ‘&’);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, ‘https://www.google.com/recaptcha/api/siteverify’);

curl_setopt($ch, CURLOPT_POST, count($fields));

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

$res = curl_exec($ch);

curl_close($ch);

return json_decode($res, true);

}

// Call the function CheckCaptcha

$result = CheckCaptcha($_POST[‘g-recaptcha-response’]);

if ($result[‘success’]) {

//If the user has checked the Captcha box

echo “Captcha verified Successfully”;

} else {

// If the CAPTCHA box wasn’t checked

echo ‘<script>alert(“Error! Check the captcha box.“);</script>’;

}

}

Was this article helpful?

Related Articles

Leave A Comment?