What are some potential pitfalls to consider when using htmlspecialchars in PHP to prevent XSS attacks in input fields?

When using htmlspecialchars in PHP to prevent XSS attacks in input fields, it's important to be aware of potential pitfalls such as double encoding, not using the correct flags, and not properly validating and sanitizing input data. To avoid these issues, always use the ENT_QUOTES flag to encode both double and single quotes, validate input data before applying htmlspecialchars, and be cautious of where and how you apply the function.

// Example of using htmlspecialchars to prevent XSS attacks in input fields
$input = "<script>alert('XSS attack!')</script>";
$clean_input = htmlspecialchars($input, ENT_QUOTES);
echo $clean_input;