What best practices should be followed when creating a contact form in PHP to ensure data security and proper functionality?

When creating a contact form in PHP, it is important to follow best practices to ensure data security and proper functionality. This includes validating user input to prevent SQL injection and cross-site scripting attacks, sanitizing input to remove any potentially harmful characters, and using prepared statements to interact with the database securely.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate and sanitize input
    $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

    // Prepare the SQL statement
    $stmt = $pdo->prepare("INSERT INTO contacts (name, email, message) VALUES (:name, :email, :message)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':message', $message);

    // Execute the statement
    $stmt->execute();
}
?>