What is the function htmlspecialchars() used for in PHP?

The function htmlspecialchars() in PHP is used to convert special characters into their HTML entities. This is important when displaying user input on a webpage to prevent cross-site scripting attacks. By using htmlspecialchars(), you can ensure that any potentially harmful characters are safely displayed as text on the page.

$user_input = "<script>alert('XSS attack');</script>";
$safe_input = htmlspecialchars($user_input);
echo $safe_input;