What best practices should be followed when handling email forms in PHP?

When handling email forms in PHP, it is important to validate user input to prevent malicious attacks such as SQL injection or cross-site scripting. Additionally, always sanitize and escape user input before using it in email headers to prevent header injection attacks. Finally, use a secure email library like PHPMailer to send emails securely and reliably.

<?php
// Validate user input
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];
    
    // Sanitize and escape user input
    $name = filter_var($name, FILTER_SANITIZE_STRING);
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    $message = filter_var($message, FILTER_SANITIZE_STRING);
    
    // Use PHPMailer to send email
    require 'PHPMailer/PHPMailer.php';
    $mail = new PHPMailer\PHPMailer\PHPMailer();
    
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject';
    $mail->Body = 'Message: ' . $message;
    
    if($mail->send()) {
        echo 'Email sent successfully';
    } else {
        echo 'Email could not be sent';
    }
}
?>