What are best practices for handling form data in PHP when using PHPMailer?

When handling form data in PHP and using PHPMailer to send emails, it is important to sanitize and validate the input data to prevent security vulnerabilities such as SQL injection and cross-site scripting. One way to do this is by using PHP's filter_input function to sanitize user input. Additionally, always use prepared statements when interacting with a database to prevent SQL injection attacks.

// Sanitize and validate form data
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);

// Check if all required fields are filled
if(empty($name) || empty($email) || empty($message)){
    // Handle error
    die('Please fill in all required fields');
}

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("INSERT INTO messages (name, email, message) VALUES (:name, :email, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':message', $message);
$stmt->execute();

// Send email using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress($email, $name);
$mail->Subject = 'Thank you for your message';
$mail->Body = 'Your message has been received. We will get back to you soon.';

if($mail->send()){
    echo 'Message sent successfully';
} else {
    echo 'Message could not be sent.';
}