What are the best practices for handling error messages and user input validation in PHP contact forms?

When handling error messages and user input validation in PHP contact forms, it is important to provide clear and informative error messages to the user when input validation fails. Additionally, it is crucial to sanitize and validate user input to prevent SQL injection and cross-site scripting attacks. Using PHP functions like filter_var() and htmlspecialchars() can help in sanitizing and validating user input effectively.

// Example code for handling error messages and user input validation in PHP contact form

// Validate and sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars($_POST['message']);

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = "Invalid email format";
}

// Check for empty fields
if (empty($name) || empty($email) || empty($message)) {
    $error = "Please fill in all fields";
}

// Display error message
if (isset($error)) {
    echo $error;
} else {
    // Process the form submission
    // Code to send email or save to database
}