How can one ensure the security and reliability of a PHP template when assigning variables dynamically?

When assigning variables dynamically in a PHP template, it is important to sanitize user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to ensure security and reliability is to use PHP's built-in functions like htmlentities() or htmlspecialchars() to escape the output before displaying it in the template. This will help prevent malicious code from being executed and keep your application safe.

<?php
// Example of dynamically assigning and outputting a variable in a PHP template
$user_input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "<p>User input: $sanitized_input</p>";
?>