Are there any best practices for sanitizing user input in PHP to prevent security vulnerabilities?

When sanitizing user input in PHP to prevent security vulnerabilities, it is important to use functions like htmlspecialchars() to escape special characters and prevent cross-site scripting attacks. Additionally, validating input using functions like filter_var() can help ensure that the input meets expected criteria. It's also recommended to use prepared statements when interacting with databases to prevent SQL injection attacks.

// Sanitize user input to prevent XSS attacks
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES);

// Validate user input using filter_var
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Email is valid.";
} else {
    echo "Invalid email.";
}

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);