What are some best practices for preventing spam entries in a PHP guestbook?

Spam entries in a PHP guestbook can be prevented by implementing CAPTCHA verification, input validation, and using honeypot fields to trick bots. By adding these measures, you can effectively reduce the amount of spam submissions in your guestbook.

<?php

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Verify CAPTCHA code
    if ($_POST["captcha"] != $_SESSION["captcha_code"]) {
        echo "CAPTCHA verification failed.";
    } else {
        // Validate input fields
        $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
        $comment = filter_var($_POST["comment"], FILTER_SANITIZE_STRING);
        
        // Check for honeypot field
        if (!empty($_POST["website"])) {
            echo "Spam submission detected.";
        } else {
            // Process guestbook entry
            // Insert into database or save to file
        }
    }
}

?>