What best practices should be followed when handling user input in PHP mail functions?
When handling user input in PHP mail functions, it is important to sanitize and validate the input to prevent malicious code injection. One way to do this is by using the filter_var() function with the FILTER_SANITIZE_EMAIL filter to ensure that the input is a valid email address. Additionally, always use the htmlspecialchars() function to escape any special characters in the input to prevent cross-site scripting attacks.
// Sanitize and validate user input for email address
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Escape special characters in the input
$email = htmlspecialchars($email);
// Use the sanitized input in the mail function
mail('recipient@example.com', 'Subject', 'Message', 'From: ' . $email);