How can PHP developers enhance the security of their contact forms to prevent spam submissions?

To enhance the security of contact forms and prevent spam submissions, PHP developers can implement CAPTCHA verification. This involves adding a challenge-response test to ensure that the form is being submitted by a human and not a bot.

// Add CAPTCHA verification to contact form
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["captcha"]) && $_POST["captcha"] == $_SESSION["captcha"]) {
        // Form submission is valid
        // Process the form data
    } else {
        // Invalid CAPTCHA, reject the submission
        echo "CAPTCHA verification failed. Please try again.";
    }
}

// Generate random CAPTCHA code and store it in session
$randomNumber1 = rand(1, 10);
$randomNumber2 = rand(1, 10);
$_SESSION["captcha"] = $randomNumber1 + $randomNumber2;

// Display CAPTCHA challenge in the form
echo "Please solve the CAPTCHA: $randomNumber1 + $randomNumber2 = ";
echo "<input type='text' name='captcha'>";