How can PHP beginners avoid common pitfalls when sending emails from a form?

One common pitfall when sending emails from a form in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as injection attacks. To avoid this, always validate and sanitize user input before using it in the email headers or body. Additionally, make sure to handle errors gracefully and provide informative feedback to users if the email fails to send.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $to = "recipient@example.com";
    $subject = "Contact Form Submission";
    
    $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
    
    $headers = "From: $name <$email>";
    
    if (mail($to, $subject, $message, $headers)) {
        echo "Email sent successfully";
    } else {
        echo "Failed to send email";
    }
}
?>