What best practices should be followed when handling form submissions and sending confirmation emails in PHP?
When handling form submissions in PHP, it is important to sanitize and validate user input to prevent SQL injection and cross-site scripting attacks. Additionally, when sending confirmation emails, make sure to use a secure email library to prevent email injection and properly format the email content.
// Sanitize and validate form 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);
// Send confirmation email
$to = $email;
$subject = 'Confirmation Email';
$body = 'Thank you for your submission. We will get back to you shortly.';
$headers = 'From: your_email@example.com';
// Use a secure email library like PHPMailer
require 'PHPMailer/PHPMailer.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('your_email@example.com', 'Your Name');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if($mail->send()) {
echo 'Confirmation email sent successfully.';
} else {
echo 'Error sending confirmation email: ' . $mail->ErrorInfo;
}