What best practices can be followed to ensure proper data sanitization and security when handling user input in PHP?

Proper data sanitization and security when handling user input in PHP can be ensured by using functions like htmlspecialchars() to prevent XSS attacks, validating input data against expected formats, and using prepared statements to prevent SQL injection attacks.

// Sanitize user input to prevent XSS attacks
$user_input = htmlspecialchars($_POST['user_input']);

// Validate input data against expected formats
if (filter_var($user_input, FILTER_VALIDATE_EMAIL)) {
    // Process the input data
}

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