What are common best practices for implementing an email form in PHP?

When implementing an email form in PHP, it is important to validate user input to prevent malicious code injection and ensure data integrity. Use PHP's built-in functions like filter_var() to validate email addresses and htmlspecialchars() to sanitize user input before sending the email. Additionally, always use a secure method like PHPMailer to send emails to prevent spam and ensure proper delivery.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    $message = htmlspecialchars($_POST["message"]);

    if ($email && $message) {
        require 'PHPMailer/PHPMailer.php';
        $mail = new PHPMailer();
        $mail->addAddress('recipient@example.com');
        $mail->setFrom($email);
        $mail->Subject = 'New message from contact form';
        $mail->Body = $message;

        if ($mail->send()) {
            echo 'Email sent successfully';
        } else {
            echo 'Error sending email';
        }
    } else {
        echo 'Invalid email or message';
    }
}
?>