What are the best practices for protecting a contact form from spam emails without using deprecated PHP functions?
Spam emails can be prevented in a contact form by implementing a CAPTCHA system. This requires users to complete a simple task to prove they are human before submitting the form. By using a CAPTCHA, automated bots are less likely to successfully submit spam emails.
```php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["captcha"] == $_SESSION["captcha"]) {
// Process the form submission
// Your code here
} else {
// Handle invalid CAPTCHA
echo "Invalid CAPTCHA, please try again.";
}
}
?>
```
In this code snippet, we start a session and generate a random CAPTCHA code, storing it in `$_SESSION["captcha"]`. When the form is submitted, we check if the entered CAPTCHA matches the one stored in the session. If they match, the form submission is processed. If not, an error message is displayed.