How can developers ensure the security and reliability of emails sent using the PHP mail() function?
Developers can ensure the security and reliability of emails sent using the PHP mail() function by validating user input, sanitizing input data, and implementing proper email headers to prevent header injections and spam. They should also consider using a third-party email service provider for more robust email delivery.
// Example code snippet to send a secure and reliable email using PHP mail() function
$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";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
// Sanitize input data
$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.";
}