What are the potential pitfalls of using escape sequences and encoding functions like htmlentities in PHP?

Using escape sequences and encoding functions like htmlentities in PHP can potentially lead to security vulnerabilities if not used correctly. One common pitfall is double-encoding, where data is encoded multiple times, leading to unexpected output or rendering issues. To avoid this, always ensure that data is only encoded once and properly decoded when needed.

// Example of using htmlentities to encode data safely
$input = "<script>alert('XSS attack!')</script>";
$encoded_input = htmlentities($input, ENT_QUOTES, 'UTF-8');
echo $encoded_input;