How can the PHP code be improved to handle form submissions more securely, considering email injection vulnerabilities?
Email injection vulnerabilities can be mitigated by sanitizing user input before using it in email headers. One way to achieve this is by using the `filter_var()` function with the `FILTER_SANITIZE_EMAIL` filter to validate email addresses. This function will remove any potentially malicious characters from the input.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Proceed with sending the email
$to = $email;
$subject = "Form Submission";
$message = "Thank you for submitting the form.";
$headers = "From: your@example.com";
mail($to, $subject, $message, $headers);
echo "Email sent successfully.";
} else {
echo "Invalid email address.";
}
}
?>
Related Questions
- What are the potential security risks associated with not properly sanitizing SQL queries in PHP?
- In what ways can breaking down a large variable into smaller sub-variables impact the functionality of the mail() function in PHP for sending emails?
- What security measures should be taken when evaluating mathematical expressions in PHP to prevent malicious code execution?