In PHP, what are some common pitfalls to avoid when processing form data before sending it via email using the mail() function?

One common pitfall to avoid when processing form data before sending it via email using the mail() function is not properly sanitizing user input to prevent malicious code injection. To solve this issue, always use functions like filter_var() or htmlspecialchars() to sanitize input before including it in the email body.

// Sanitize form data before sending via email
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars($_POST['message'], ENT_QUOTES);

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

mail($to, $subject, $body, $headers);