How can one securely process form data in PHP to prevent vulnerabilities when using the mail() function?
To securely process form data in PHP to prevent vulnerabilities when using the mail() function, it is important to sanitize and validate the input data before using it in the email message. This can help prevent common vulnerabilities such as email injection attacks. One way to achieve this is by using PHP's filter_var() function to sanitize the input data and ensuring that the email headers are properly formatted to prevent injection attacks.
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Handle invalid email address
exit('Invalid email address');
}
// Prevent email header injection
$subject = 'Contact Form Submission';
$headers = 'From: ' . $email . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
// Send email
if (mail('recipient@example.com', $subject, $message, $headers)) {
echo 'Email sent successfully';
} else {
echo 'Failed to send email';
}