What best practices should be followed when handling user input in PHP, especially when validating form fields?

When handling user input in PHP, especially when validating form fields, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Best practices include using functions like htmlspecialchars() to prevent XSS attacks, validating input using functions like filter_var() or regular expressions, and using prepared statements when interacting with a database to prevent SQL injection attacks.

// Example of sanitizing user input using htmlspecialchars
$user_input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlspecialchars($user_input);

// Example of validating user input using filter_var
$email = "invalid_email";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address";
} else {
    echo "Invalid email address";
}

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();