What are the best practices for validating and sanitizing user input in a PHP contact form to prevent vulnerabilities like E-Mail Header Injection?
To prevent vulnerabilities like E-Mail Header Injection in a PHP contact form, it is essential to validate and sanitize user input before using it to construct email headers. This involves checking for potentially malicious characters or patterns in the input data and sanitizing it to ensure it does not contain any harmful content. By implementing proper validation and sanitization techniques, you can protect your application from attacks that exploit vulnerabilities in email header parsing.
// Validate and sanitize user input for email headers
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Construct email headers
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $name <$email>" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
// Send email
mail($to, $subject, $message, $headers);
Related Questions
- In what situations is it recommended to use echo or print instead of <?php ?> for outputting text in PHP?
- What steps can be taken to ensure that a newly uploaded image is displayed immediately on a PHP forum without needing to refresh the page?
- What potential security risks are associated with using PHP_SELF in form actions?