What are common issues when using PHP to send emails through a contact form?
Common issues when using PHP to send emails through a contact form include emails not being delivered due to misconfigured SMTP settings, emails being marked as spam because of missing or incorrect headers, and potential security vulnerabilities if user input is not properly sanitized. To solve these issues, make sure to properly configure your SMTP settings, include necessary headers such as From and Reply-To, and sanitize user input to prevent injection attacks.
<?php
// Example code snippet to send an email with proper headers and sanitized input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $name <$email>\r\n";
$headers .= "Reply-To: $email\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully";
} else {
echo "Failed to send email";
}
}
?>