What are the potential security risks of not using htmlspecialchars() when outputting HTML in PHP?

When outputting HTML in PHP without using htmlspecialchars(), there is a risk of Cross-Site Scripting (XSS) attacks. This is because user input containing malicious scripts can be executed on the webpage, potentially compromising sensitive information or harming users. To prevent this, it is important to use htmlspecialchars() to encode special characters in the output, rendering them harmless.

// Outputting HTML without using htmlspecialchars() (unsafe)
$user_input = "<script>alert('XSS attack');</script>";
echo $user_input;

// Using htmlspecialchars() to encode special characters (safe)
$user_input = "<script>alert('XSS attack');</script>";
echo htmlspecialchars($user_input);