How can PHP developers prevent spam attacks via contact forms?

Spam attacks via contact forms can be prevented by implementing CAPTCHA verification to ensure that the form is being submitted by a human rather than a bot. By adding a CAPTCHA field to the form, users are required to complete a simple task, such as entering a code or selecting images, before submitting the form. This can help reduce the number of spam submissions and protect the website from unwanted automated submissions.

```php
// Add CAPTCHA verification to contact form
if(isset($_POST['submit'])){
    $captcha = $_POST['captcha'];
    $correct_captcha = "7g3p9"; // Define the correct CAPTCHA code

    if($captcha == $correct_captcha){
        // Process form submission
        // Add code to send email or save form data to database
    } else {
        // Display error message or redirect back to form with error message
        echo "Incorrect CAPTCHA code. Please try again.";
    }
}
```
In this code snippet, a CAPTCHA field is added to the contact form and users are required to enter the correct CAPTCHA code ("7g3p9" in this example) to submit the form. If the entered code matches the correct code, the form submission is processed. Otherwise, an error message is displayed prompting the user to try again.