Are there any best practices or guidelines for securing PHP contact forms against spam attacks?

One common way to secure PHP contact forms against spam attacks is to use a CAPTCHA system, which requires users to complete a challenge to prove they are human. This can help prevent automated bots from submitting spam messages through the form.

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['captcha']) && $_POST['captcha'] == $_SESSION['captcha']) {
        // Process the form submission
        // Code to handle form data
    } else {
        // Display error message for incorrect CAPTCHA
        echo "CAPTCHA verification failed. Please try again.";
    }
}

// Generate random CAPTCHA code
$captcha = rand(1000, 9999);
$_SESSION['captcha'] = $captcha;
?>

<form method="post" action="">
    <label for="captcha">Enter the code shown above:</label>
    <input type="text" id="captcha" name="captcha" required>
    <img src="captcha_image.php" alt="CAPTCHA Image">
    <input type="submit" value="Submit">
</form>