What is the importance of using htmlspecialchars() when inserting values into HTML code in PHP?

When inserting values into HTML code in PHP, it is important to use the htmlspecialchars() function to prevent cross-site scripting (XSS) attacks. This function converts special characters into their HTML entities, ensuring that user input is displayed as plain text and not executed as code. By using htmlspecialchars(), you can protect your website from malicious scripts that could potentially harm users or steal sensitive information.

<?php
$user_input = "<script>alert('XSS attack!');</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "<p>User input: $escaped_input</p>";
?>