How can htmlspecialchars be used to prevent security vulnerabilities in PHP?

Using htmlspecialchars in PHP helps prevent security vulnerabilities such as cross-site scripting (XSS) attacks by converting special characters into their HTML entity equivalents. This ensures that user-inputted data is displayed as intended on the webpage without executing any malicious scripts.

// Using htmlspecialchars to prevent XSS attacks
$user_input = "<script>alert('XSS attack!')</script>";
$safe_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $safe_input;