How does the htmlspecialchars() function help prevent security vulnerabilities in PHP applications by sanitizing user input before rendering it in HTML output?

When user input is directly rendered in HTML output without proper sanitization, it can lead to cross-site scripting (XSS) attacks where malicious scripts are executed in the context of a user's browser. The htmlspecialchars() function in PHP converts special characters like <, >, ", ', and & into their HTML entities, preventing them from being interpreted as HTML tags or script. This helps to mitigate the risk of XSS attacks by ensuring that user input is displayed as plain text rather than being executed as code.

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