What are potential issues with using the mail() function in PHP for form submission?

One potential issue with using the mail() function in PHP for form submission is that it can be vulnerable to email injection attacks if user input is not properly sanitized. To mitigate this risk, it is crucial to validate and sanitize user input before using it in the mail() function. This can help prevent malicious users from injecting additional headers into the email and potentially compromising the email server.

// Sanitize user input before using it in the mail() function
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Use the sanitized variables in the mail() function
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$body = "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Message: $message\n";

// Additional headers
$headers = 'From: ' . $email;

// Send the email
if (mail($to, $subject, $body, $headers)) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email';
}