How does the htmlspecialchars() function help in preventing HTML code manipulation?

When user input is displayed on a webpage without proper sanitization, it can be vulnerable to HTML injection attacks where malicious users can inject their own HTML code. This can lead to various security risks such as cross-site scripting (XSS) attacks. The htmlspecialchars() function in PHP helps prevent HTML code manipulation by converting special characters in a string to HTML entities, rendering them harmless and preventing them from being interpreted as HTML code.

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