What are the best practices for handling user input in PHP forms to prevent spam?

To prevent spam in PHP forms, it is essential to implement validation and sanitization techniques on user input. This can include using CAPTCHA, input validation, and filtering out common spam keywords. Additionally, implementing honeypot fields and setting form submission limits can also help reduce spam submissions.

// Example PHP code snippet to prevent spam in a form submission

// Validate and sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Implement CAPTCHA verification
$secretKey = "YOUR_SECRET_KEY";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = json_decode(file_get_contents($url));
if($response->success) {
    // Process the form submission
    // This is a valid user
} else {
    // This is likely a spam submission
    // Handle accordingly
}