What are some best practices for handling user input in PHP to prevent vulnerabilities like email header injection?
Email header injection occurs when user input is not properly sanitized before being used in email headers, allowing an attacker to inject additional headers or manipulate the email content. To prevent this vulnerability, always sanitize and validate user input before using it in email headers. One way to do this is by using PHP's filter_var() function with the FILTER_SANITIZE_EMAIL filter to ensure that the input is a valid email address.
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
// Additional email headers and sending email code here