What best practices should be followed when inserting text into a textarea in PHP?

When inserting text into a textarea in PHP, it is important to properly escape the text to prevent any potential security vulnerabilities such as cross-site scripting attacks. One common method to achieve this is by using the htmlspecialchars() function to convert special characters to HTML entities. This ensures that the text is displayed as-is and does not execute any malicious scripts.

// Example of inserting text into a textarea with proper escaping
$text = "This is some <script>alert('malicious code');</script> text.";
$escaped_text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
echo '<textarea>' . $escaped_text . '</textarea>';