What are the best practices for sanitizing user input in PHP to prevent malicious code injection?
To prevent malicious code injection in PHP, it is crucial to sanitize user input by using functions like `htmlspecialchars()` to escape special characters that could be used for cross-site scripting attacks. Additionally, validating and filtering input using functions like `filter_input()` can help ensure that only expected data types are accepted.
// Sanitize user input using htmlspecialchars()
$user_input = htmlspecialchars($_POST['user_input'], ENT_QUOTES, 'UTF-8');
// Validate and filter input using filter_input()
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);