What are the best practices for handling user-generated content that may contain malicious code in PHP applications?

User-generated content that may contain malicious code can pose a security risk to PHP applications. To mitigate this risk, it is essential to sanitize and validate all user input before processing or displaying it. This can be done by using functions like htmlentities() or htmlspecialchars() to encode user input and prevent script injection attacks.

// Sanitize user input to prevent malicious code injection
$userInput = htmlentities($_POST['user_input'], ENT_QUOTES, 'UTF-8');
echo $userInput;