What are some common methods for implementing spam protection in PHP forms?

Spam protection in PHP forms is essential to prevent automated bots from submitting unwanted or malicious content. Some common methods for implementing spam protection include using CAPTCHA, honeypot fields, and input validation techniques.

// Example of implementing CAPTCHA in a PHP form
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($_POST["captcha"] == $_SESSION["captcha"]) {
        // CAPTCHA verification successful, process form data
    } else {
        // CAPTCHA verification failed, display error message
    }
}

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

// Display CAPTCHA in form
echo "<label for='captcha'>Enter the code shown above:</label>";
echo "<input type='text' name='captcha' id='captcha'>";
echo "<img src='captcha_image.php' alt='CAPTCHA'>";