Skip to content
PHP Logo

How can developers ensure the security and reliability of the mail() function in PHP scripts?

Developers can ensure the security and reliability of the mail() function in PHP scripts by properly sanitizing user input to prevent injection attacks, validating email addresses to prevent spoofing, and implementing proper error handling to handle any issues that may arise during the email sending process.

php
// Sanitize user input
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Validate email address
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email address");
}

// Send email
if (mail($to, $subject, $message)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}