What are common pitfalls when using PHP for form handling, especially in relation to email sending?
Common pitfalls when using PHP for form handling, especially in relation to email sending, include not properly sanitizing user input, not validating input data, and not handling errors effectively. To solve these issues, always sanitize and validate user input to prevent SQL injection and other security vulnerabilities, and implement error handling to provide feedback to users in case of email sending failures.
// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Validate input data
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
exit;
}
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email";
$body = "Name: $name\nEmail: $email\nMessage: $message";
if (mail($to, $subject, $body, $headers)) {
echo "Email sent successfully";
} else {
echo "Failed to send email";
}