What are the best practices for handling user input in PHP to prevent PHP injection attacks, especially when using functions like htmlspecialchars?

To prevent PHP injection attacks when handling user input in PHP, especially when using functions like htmlspecialchars, it is important to sanitize and validate all user input before processing it. One way to do this is by using functions like filter_input() or filter_var() to sanitize input data. Additionally, always use prepared statements when interacting with databases to prevent SQL injection attacks.

// Sanitize user input using filter_var
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $user_input);
$stmt->execute();