How can the use of htmlspecialchars function enhance the security of PHP forms and prevent XSS attacks?

Using the htmlspecialchars function in PHP helps enhance security by converting special characters into their HTML entities, preventing malicious scripts from being executed as part of user input. This helps prevent Cross-Site Scripting (XSS) attacks by ensuring that user input is displayed as text rather than interpreted as code.

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