What are some best practices for preventing form spam in PHP applications?

Form spam can be prevented in PHP applications by implementing CAPTCHA verification, using honeypot fields, and validating form inputs on the server side. CAPTCHA helps to ensure that the form is being submitted by a human rather than a bot, while honeypot fields act as traps for spam bots. Validating form inputs on the server side helps to prevent malicious code injections.

// Example of implementing CAPTCHA verification in PHP
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST['captcha'] != $_SESSION['captcha']) {
        // CAPTCHA verification failed
        echo "CAPTCHA verification failed!";
    } else {
        // Process form submission
    }
}

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

// Display CAPTCHA code in the form
echo '<label for="captcha">Enter the code: ' . $captcha . '</label>';
echo '<input type="text" id="captcha" name="captcha">';