How can HTML attribute values be properly handled when passing strings to form fields in PHP?

When passing strings to form fields in PHP, HTML attribute values must be properly handled to prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks. To ensure the safety of attribute values, you can use the htmlspecialchars() function to escape special characters in the string before outputting it to the form field.

<?php
// Example string to be passed to form field
$string = "<script>alert('XSS attack!');</script>";

// Escaping special characters in the string using htmlspecialchars()
$escaped_string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

// Outputting the escaped string to the form field
echo "<input type='text' value='$escaped_string'>";
?>