What are some common methods for filtering out spam in PHP applications?

Spam filtering is crucial in PHP applications to prevent unwanted and potentially harmful content from being submitted through forms or messages. Common methods for filtering out spam include using CAPTCHA, honeypot fields, and third-party spam detection services.

// Example of implementing CAPTCHA for spam filtering in PHP

// Generate a random CAPTCHA code
$captcha = rand(1000, 9999);

// Store the CAPTCHA code in a session variable
$_SESSION['captcha'] = $captcha;

// Display the CAPTCHA image in the form
echo '<img src="captcha.php" alt="CAPTCHA image">';

// Validate the submitted CAPTCHA code
if(isset($_POST['captcha']) && $_POST['captcha'] == $_SESSION['captcha']) {
    // CAPTCHA code is correct, process the form submission
} else {
    // CAPTCHA code is incorrect, display an error message
    echo 'CAPTCHA code is incorrect';
}