How to generate a random, unique, alphanumeric string?

How to generate a random, unique, alphanumeric string?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Secure Verification Tokens in PHP

When building a registration flow, the verification token embedded in your email links needs to satisfy two competing requirements: it must be unpredictable enough to prevent guessing attacks, and it must be unique within the scope of your system's lifetime. Relying on simple random number generators or short hashes is often insufficient because they can lead to collisions or predictable sequences that compromise security.

To generate a robust alphanumeric string suitable for verification links, you should leverage PHP's cryptographic functions. The standard approach involves using random_bytes() to generate cryptographically secure random bytes, which are then mapped to a specific character set. This ensures that every bit of entropy comes from the operating system's secure random number generator rather than a potentially predictable source like rand().

The implementation typically follows a two-step process: generating raw binary data and encoding it into your desired alphabet. You define a character set containing uppercase letters, lowercase letters, and digits to create a compact, readable string. A common size for these tokens is 16 or 32 characters, though the exact length depends on your collision probability requirements. The following PHP snippet demonstrates how to construct a 32-character token using only alphanumeric characters:

function generateVerificationToken(int $length = 32): string
{
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    
    // Generate cryptographically secure random bytes
    $randomBytes = random_bytes($length / 2); 
    
    $token = '';
    for ($i = 0; $i < $length; $i++) {
        $token .= $characters[random_int(0, $charactersLength - 1)];
    }
    
    return $token;
}

In this example, random_bytes() provides the necessary entropy, while random_int() maps that entropy into indices within your character set. This method avoids modulo bias, a common pitfall when using rand() % strlen($characters), which can skew probability distributions if the range of random numbers does not perfectly divide by the character set length.

Handling Collisions and Storage

Generating a unique string is distinct from guaranteeing that no other record in your database shares it. Even with a cryptographically secure generator, collisions are statistically possible but highly improbable with sufficiently long strings. However, uniqueness is ultimately determined by how you store and check these tokens.

You must store the generated token in your database alongside a timestamp or an expiration flag. When verifying a user, your application checks if the token exists in the database. If it does, you validate whether the associated account is still pending verification. Once verified, you should mark the record as active and invalidate the token immediately to prevent reuse. This pattern ensures that even if an attacker intercepts a valid token, they cannot use it after the user has completed the verification process.

Trade-offs in Token Length and Complexity

There is a practical trade-off between token length, usability, and security. Longer tokens are more secure against brute-force attacks but result in longer URL parameters, which can be truncated by email clients or social media platforms. A 32-character alphanumeric string offers approximately $62^{32}$ possible combinations, making brute-force guessing computationally infeasible for any attacker with realistic resources.

If you need to support international characters or want to reduce the length of the token while maintaining security, you might consider Base64 encoding. However, standard Base64 includes symbols like +, /, and =, which can cause issues with URL parsing or email filtering if not carefully handled. Sticking to a strict alphanumeric set is generally safer for email links unless you explicitly implement URL-safe Base64 encoding and handle padding removal.

Conclusion on Best Practices

For most web applications, generating a 32-character alphanumeric string using random_bytes() and random_int() provides the optimal balance of security and usability. Always ensure your database queries are indexed on the token column to make lookups efficient, as high-traffic sites could face performance issues with linear scans on large datasets. Finally, remember that the security of the entire verification flow depends not just on the randomness of the token, but also on secure session management and proper expiration handling.

Our network