SoftwareWebsite

Add Google recaptcha to your site

To add a CAPTCHA to your contact form, you can use the Google reCAPTCHA service. Here’s how you can set it up:

Go to the Google reCAPTCHA website (https://www.google.com/recaptcha) and sign up for an account.
Follow the instructions to register your website and get a site key and a secret key.
In your HTML form, add a div element where you want the CAPTCHA to appear:

<form action="contact.php" method="post">
<!-- Your form fields go here -->
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
<input type="submit" value="Submit">
</form>

In the head of your HTML file, add a script tag to include the reCAPTCHA JavaScript library:

<head>
<!-- Other head content goes here -->
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>

In your PHP script, add the following code at the top to verify the CAPTCHA response:

 

<?php
// Your other PHP code goes here

// Verify the CAPTCHA response
$secret_key = "YOUR_SECRET_KEY";
$response = trim(filter_input(INPUT_POST,"g-recaptcha-response",FILTER_SANITIZE_STRING));
$remote_ip = $_SERVER["REMOTE_ADDR"];

$verify_url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret_key&response=$response&remoteip=$remote_ip";

$verify_response = file_get_contents($verify_url);
$response_data = json_decode($verify_response);

if (!$response_data->success) {
// CAPTCHA failed, display an error message
echo "Error: CAPTCHA verification failed. Please try again.";
exit;
}

// Your form processing code goes here

This code sends the CAPTCHA response and the user’s IP address to the Google reCAPTCHA server to verify that the CAPTCHA was solved correctly. If the CAPTCHA was solved correctly, the script continues to process the form data. If the CAPTCHA was not solved correctly, it displays an error message.

Tags

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close
Close