What are common pitfalls when creating a PHP mail form on a single page?

One common pitfall when creating a PHP mail form on a single page is not properly validating user input before sending the email. This can lead to security vulnerabilities such as injection attacks. To solve this, make sure to sanitize and validate all user input before processing the form.

// Example of sanitizing and validating user input before sending the email

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
    exit;
}

// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email";
$mailBody = "Name: $name\nEmail: $email\nMessage: $message";

mail($to, $subject, $mailBody, $headers);
echo "Email sent successfully";