What potential security risks are associated with using the mail() function in PHP scripts?

The mail() function in PHP scripts can be vulnerable to email header injection attacks, where an attacker can manipulate the email headers to include malicious content or redirect the email to a different recipient. To mitigate this risk, it is important to sanitize and validate user input before using it in the mail() function.

$to = 'recipient@example.com';
$subject = 'Subject';
$message = 'Message';

// Sanitize and validate input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);

// Send email
mail($to, $subject, $message);