Skip to content
PHP Logo

Are there any potential pitfalls or limitations to using the mail() function in PHP for sending form input via email?

One potential pitfall of using the mail() function in PHP for sending form input via email is that it is susceptible to email injection attacks, where malicious users can inject additional headers into the email. To prevent this, you should sanitize and validate user input before using it in the mail() function. Additionally, the mail() function may not work properly if the server is not configured correctly or if the email is flagged as spam.

php
// Sanitize and validate user input before using it in the mail() function
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Use additional headers to prevent email injection
$subject = "Contact Form Submission";
$headers = "From: $name <$email>";

// Send the email
if(mail("recipient@example.com", $subject, $message, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}