What best practices should be followed when outputting user input in HTML form fields to avoid unwanted character escaping?

When outputting user input in HTML form fields, it is important to avoid unwanted character escaping to prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks. To ensure safe output, you can use the htmlspecialchars() function in PHP to encode special characters like <, >, ", ', and & before displaying the user input in the form fields.

&lt;?php
// Retrieve user input from a form field
$userInput = $_POST[&#039;user_input&#039;];

// Output the user input in an HTML form field with htmlspecialchars() function
echo &#039;&lt;input type=&quot;text&quot; name=&quot;user_input&quot; value=&quot;&#039; . htmlspecialchars($userInput) . &#039;&quot;&gt;&#039;;
?&gt;