What are the best practices for handling form data and sending emails in PHP?
When handling form data in PHP, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, when sending emails in PHP, it is crucial to properly set headers, validate email addresses, and handle errors gracefully to ensure reliable email delivery.
// Example of handling form data and sending email in PHP
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Send email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$mailSent = mail($to, $subject, $message, $headers);
if($mailSent) {
echo "Email sent successfully";
} else {
echo "Failed to send email";
}