How can the use of htmlspecialchars() and htmlentities() improve the security of PHP forms?

When displaying user input on a webpage in PHP forms, it is important to sanitize the input to prevent cross-site scripting (XSS) attacks. The functions htmlspecialchars() and htmlentities() can be used to convert special characters in the input to their HTML entities, which prevents malicious scripts from being executed in the browser.

// Using htmlspecialchars() to sanitize user input
$input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
echo $sanitized_input;