What are some best practices for validating user input in PHP, specifically when it comes to usernames?

When validating user input for usernames in PHP, it is important to enforce certain rules to ensure data integrity and security. Some best practices include checking for the length of the username, allowed characters (such as alphanumeric characters, underscores, and dashes), and uniqueness. Additionally, it is recommended to sanitize the input to prevent SQL injection attacks.

// Validate username input
$username = $_POST['username'];

// Check if username meets length requirements
if (strlen($username) < 3 || strlen($username) > 20) {
    echo "Username must be between 3 and 20 characters.";
}

// Check if username contains only allowed characters
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $username)) {
    echo "Username can only contain letters, numbers, underscores, and dashes.";
}

// Check if username is unique (assuming database connection)
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
if ($stmt->rowCount() > 0) {
    echo "Username is already taken.";
}

// Sanitize username input
$username = filter_var($username, FILTER_SANITIZE_STRING);