How can CAPTCHA be implemented to protect PHP contact forms from spam?
To protect PHP contact forms from spam, CAPTCHA can be implemented to verify that the form submission is made by a human and not a bot. This can help prevent automated spam submissions and ensure that genuine users are interacting with the form.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["captcha"]) && $_POST["captcha"] == $_SESSION["captcha"]) {
// CAPTCHA verification passed, process the form submission
// Add your form processing logic here
} else {
// CAPTCHA verification failed, display an error message
echo "CAPTCHA verification failed. Please try again.";
}
}
// Generate a random CAPTCHA code and store it in the session
$randomNumber1 = rand(1, 10);
$randomNumber2 = rand(1, 10);
$_SESSION["captcha"] = $randomNumber1 + $randomNumber2;
// Display the CAPTCHA image and input field in the form
echo "<img src='captcha.php' alt='CAPTCHA'>";
echo "<input type='text' name='captcha' placeholder='Enter the sum of $randomNumber1 + $randomNumber2'>";
?>