📜  recaptcha - Html (1)

📅  最后修改于: 2023-12-03 15:19:46.861000             🧑  作者: Mango

Recaptcha - Html

Recaptcha is a Google service that helps to protect websites from spam and abuse by verifying that the user is not a robot. In this tutorial, we will be using the recaptcha-html code to add a captcha to our web page.

Steps to implement recaptcha in html
  1. To use recaptcha, you first need to sign up for a Google Recaptcha API key. You can obtain the API keys from the reCAPTCHA website.

  2. After you have obtained your API keys, include the following JavaScript code in your HTML file.

<script src='https://www.google.com/recaptcha/api.js'></script>
  1. Now, you need to add the recaptcha widget to your HTML form. To do this, add the following code inside the form tags.
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>

Replace 'YOUR_SITE_KEY' with your own website's public key.

  1. You also need to include the following code in your HTML form to verify the user's response.
<button class="g-recaptcha-submit" type="submit" value="submit">Submit</button>

This button will trigger the verification process and submit the form if the user is verified.

  1. Finally, you need to verify the user's response in your server-side code. Google provides libraries for several programming languages to simplify this process.

Here is an example of how to verify the user's response in PHP:

$recaptcha_secret = 'YOUR_SECRET_KEY';
$recaptcha_response = $_POST['g-recaptcha-response'];

$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);

if ($recaptcha->success) {
    // user is verified, continue with your form processing
} else {
    // user is not verified, show an error message
}
Conclusion

Recaptcha is a powerful tool to protect your website from spam and abuse. By following the steps above, you can easily add a recaptcha to your HTML form.