What are the best practices for automatically populating a text field with a PHP variable value?

When populating a text field with a PHP variable value, it is important to properly sanitize the input to prevent security vulnerabilities such as SQL injection. One common way to achieve this is by using htmlspecialchars() function to escape special characters. Additionally, make sure to properly validate the input before displaying it to the user.

<?php
// Assuming $variable contains the value to be populated in the text field
$populated_value = htmlspecialchars($variable);
echo '<input type="text" name="textfield" value="' . $populated_value . '">';
?>