How can the htmlspecialchars() function be used to prevent context switching vulnerabilities in PHP?

Context switching vulnerabilities in PHP can be prevented by using the htmlspecialchars() function to encode special characters in user input before displaying it on a webpage. This function converts characters like <, >, ", ', and & into their respective HTML entities, preventing them from being interpreted as HTML or JavaScript code. By using htmlspecialchars() to sanitize user input, you can protect your application from cross-site scripting (XSS) attacks.

$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_input = htmlspecialchars($user_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo $safe_input;