What are the common pitfalls when sending form data via PHP mail and how can they be avoided?
Common pitfalls when sending form data via PHP mail include not properly sanitizing user input, not validating email addresses, and not setting proper headers for the email. To avoid these pitfalls, make sure to sanitize and validate user input, use the filter_var function to validate email addresses, and set the necessary headers for the email.
// Sanitize and validate user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Check if email is valid
if (!$email) {
echo 'Invalid email address';
exit;
}
// Set headers for the email
$headers = 'From: ' . $email . "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Send the email
$mailSent = mail('recipient@example.com', 'Contact Form Submission', $message, $headers);
if ($mailSent) {
echo 'Email sent successfully';
} else {
echo 'Failed to send email';
}