How can PHP developers prevent email header injection vulnerabilities in their code?
Email header injection vulnerabilities can be prevented by sanitizing user input before using it to construct email headers. PHP developers can use the `filter_var()` function with the `FILTER_SANITIZE_EMAIL` filter to validate and sanitize email addresses before including them in email headers. This helps to prevent malicious users from injecting additional headers into the email, which could be used for spamming or phishing attacks.
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Construct email headers
$headers = "From: webmaster@example.com\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
// Send email
mail("recipient@example.com", $subject, $message, $headers);
Related Questions
- How can a message box with options for "Yes" and "No" be implemented in PHP for user interaction?
- How can the extraction of POST and GET variables using the extract() function in PHP affect the security and stability of a script, especially in the context of an online shop?
- How can someone effectively use PHPMyAdmin to manage SQL databases, including setting up passwords?