What is the purpose of double encoding in PHP and when does it make sense to use it?

Double encoding in PHP is used to prevent Cross-Site Scripting (XSS) attacks by encoding user input multiple times. This helps to ensure that any special characters are properly escaped and cannot be interpreted as code by the browser. It makes sense to use double encoding when dealing with user input that will be displayed on a webpage to prevent malicious scripts from being executed.

$user_input = '<script>alert("XSS attack")</script>';
$encoded_input = htmlspecialchars(htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8'));
echo $encoded_input;