What are the best practices for sanitizing user input in PHP to prevent injection attacks and malicious code execution?

To prevent injection attacks and malicious code execution, it is important to sanitize user input in PHP by using functions like htmlentities() or htmlspecialchars() to encode special characters. Additionally, using prepared statements with parameterized queries when interacting with databases can help prevent SQL injection attacks.

$user_input = $_POST['user_input'];
$sanitized_input = htmlentities($user_input);
// Use $sanitized_input in your application to prevent injection attacks