What are best practices for handling form data in PHP to ensure successful email delivery?
When handling form data in PHP to ensure successful email delivery, it is important to properly sanitize and validate the user input to prevent any malicious code injections. Additionally, make sure to set the appropriate headers and parameters when sending the email to ensure it is delivered successfully. Lastly, consider using a reliable email service provider or library to handle the email sending process.
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Set email headers
$headers = "From: Your Name <your_email@example.com>\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$mailBody = "Name: $name <br>Email: $email <br>Message: $message";
$mailSent = mail($to, $subject, $mailBody, $headers);
if ($mailSent) {
echo "Email sent successfully!";
} else {
echo "Failed to send email. Please try again.";
}