Adding Google reCAPTCHA Checkbox to Form
How to add Google reCAPTCHA to Form
Google reCAPTCHA is a widget, it helps to ensure the end user is a human not a robot. It allows preventing sharing information from unauthorized parties. It secures the website from spambots. So every website, it is best to use this widget when sharing the site info to the end users.
In this blog, we discuss how to integrate google reCAPTCHA v2 to a PHP website.
Here are the instructions for adding a widget to login form in your web project.
1. Search in google for 'google reCAPTCHA v2 '.
2. Sign in to google reCAPTCHA.
3. In admin settings, click (+) to create a new captcha for your site
4. It opens new window, enter all the details and click submit
5. In the dashboard, select recently created site from the dropdown, click settings(gear icon)
6. Copy reCAPTCHA keys and add in the program. That's all you need to do.
Create an index.php and copy the entire code below given in the index file, save it in a project. Start server and open it in a browser.
index.php
<html> <head> <script src='https://www.google.com/recaptcha/api.js'></script> <title>Integrating Google reCAPTCHA Demo Coding-zon </title> </head> <body> <h1> Integrating Google reCAPTCHA Demo </h1> <form action="" method="post"> Name : <input type="text" name="name"><br> Email : <input type="text" name="email"><br><br> <div class="g-recaptcha" data-sitekey="your_site_key"></div> <input type="submit" name="submit" value="submit"> </form> <?php if(isset($_POST['submit'])) { /* ********** 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<br /><br />"; echo $_POST['name'] .' '.$_POST['email']; } else { // If the CAPTCHA box wasn't checked echo '<script>alert("Error Message");</script>'; } }
//In this function, there is a fields array. Replace 'your_secret_key' with the key that you got from Google.
function CheckCaptcha($userResponse) { $fields_string = ''; $fields = array( 'secret' => 'your_secret_key','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); }
?> </body>
</html>
Output:
Comments
Post a Comment