What is the best practice for displaying user input in an input field before submitting it in PHP?

When displaying user input in an input field before submitting it in PHP, it is important to prevent any potential security vulnerabilities such as cross-site scripting attacks. One way to do this is by using the htmlspecialchars() function to escape any special characters in the user input before displaying it in the input field. This ensures that the input is safely rendered on the page without executing any malicious scripts.

<?php
$user_input = isset($_POST['user_input']) ? htmlspecialchars($_POST['user_input']) : '';
?>

<form method="post">
    <input type="text" name="user_input" value="<?php echo $user_input; ?>">
    <input type="submit" value="Submit">
</form>