What are the best practices for sanitizing user input in PHP to prevent HTML injection?

To prevent HTML injection in PHP, it is important to sanitize user input by using functions like htmlspecialchars() or htmlentities() to convert special characters into their HTML entities. This helps to render any injected HTML harmless and display it as plain text on the webpage.

$user_input = "<script>alert('Hello!');</script>";
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $sanitized_input;