How can PHP mail() function be used securely to avoid vulnerabilities?
To use the PHP mail() function securely and avoid vulnerabilities, it is important to validate and sanitize user input to prevent injection attacks. Additionally, it is recommended to set the "From" header explicitly to prevent email header injection. Finally, consider using a library like PHPMailer for more advanced email functionalities and better security.
$to = "recipient@example.com";
$subject = "Test email";
$message = "This is a test email.";
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
// Sanitize user input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);
// Send email
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}