What are some best practices for integrating a Captcha in a PHP contact form to prevent spam?

To prevent spam in a PHP contact form, one best practice is to integrate a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart). This helps ensure that the form submission is coming from a real person and not a bot. By adding a CAPTCHA, you can significantly reduce the amount of spam submissions received through the contact form.

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['captcha']) && !empty($_POST['captcha'])) {
        if ($_POST['captcha'] == $_SESSION['captcha']) {
            // CAPTCHA validation successful, process the form submission
            // Insert code to handle form submission here
        } else {
            // CAPTCHA validation failed, display error message
            echo "CAPTCHA validation failed. Please try again.";
        }
    } else {
        // CAPTCHA field is empty, display error message
        echo "Please complete the CAPTCHA.";
    }
}

// Generate random CAPTCHA code and store it in session
$randomNumber = rand(1000, 9999);
$_SESSION['captcha'] = $randomNumber;

?>

<form method="post" action="">
    <label for="captcha">Please enter the CAPTCHA code: <?php echo $randomNumber; ?></label>
    <input type="text" name="captcha" id="captcha" required>
    <button type="submit">Submit</button>
</form>