How can PHP be used to validate user input in contact forms to prevent errors and improve user experience?

To validate user input in contact forms using PHP, you can check for required fields, validate email addresses, sanitize input to prevent SQL injection, and provide meaningful error messages to the user. This helps prevent errors and improves the overall user experience by ensuring that the data submitted through the form is accurate and secure.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate required fields
    if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["message"])) {
        echo "All fields are required.";
    } else {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $message = $_POST["message"];
        
        // Validate email address
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo "Invalid email format.";
        } else {
            // Sanitize input
            $name = htmlspecialchars($name);
            $email = filter_var($email, FILTER_SANITIZE_EMAIL);
            $message = htmlspecialchars($message);
            
            // Process form submission
            // Additional validation and processing code here
        }
    }
}
?>