What are some best practices for handling email headers and addresses in PHP scripts?
When handling email headers and addresses in PHP scripts, it is important to properly sanitize and validate user input to prevent email header injection attacks. One common best practice is to use the PHP built-in function `filter_var()` with the `FILTER_VALIDATE_EMAIL` filter to validate email addresses before using them in email headers. Additionally, always use the `mb_encode_mimeheader()` function to encode any non-ASCII characters in email headers to ensure proper display.
// Sanitize and validate email address
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Encode email address for use in headers
$encoded_email = mb_encode_mimeheader($email);
// Set email headers
$headers = "From: $encoded_email\r\n";
$headers .= "Reply-To: $encoded_email\r\n";
// Send email
mail('recipient@example.com', 'Subject', 'Message', $headers);