What potential pitfalls should be considered when creating and sending emails with PHP?
One potential pitfall when creating and sending emails with PHP is the risk of exposing sensitive information in the email headers. To prevent this, make sure to sanitize user input and avoid directly inserting user-provided data into email headers. Instead, use proper email header injection prevention techniques to ensure the security of your emails.
// Sanitize user input for email headers
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Use proper email header injection prevention techniques
$subject = str_replace(array("\r", "\n", "%0a", "%0d"), '', $subject);
$to = str_replace(array("\r", "\n", "%0a", "%0d"), '', $to);
$message = str_replace(array("\r", "\n", "%0a", "%0d"), '', $message);
// Send email
$headers = "From: sender@example.com\r\n";
mail($to, $subject, $message, $headers);