How to generate random password with PHP?

How to generate random password with PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How to Generate Secure Random Passwords in PHP

Relying on rand() or mt_rand() for password generation is a critical security failure. These functions use a Linear Congruential Generator (LCG), which produces sequences that are predictable if the internal state is known. An attacker with knowledge of the algorithm can reverse-engineer the sequence and guess future values. For authentication systems, this predictability renders the generated tokens useless as they do not provide true entropy.

To generate cryptographically secure passwords in PHP, you must utilize the random_bytes() function available since PHP 7.0. This function returns a string of random bytes suitable for cryptographic use, drawing from the operating system's hardware-based randomness source on Unix-like systems or the Windows CryptGenRandom API.

Here is a robust implementation that constructs a password with specific character sets and length constraints:

function generateSecurePassword(int $length = 16): string {
    // Define the allowed character sets
    $uppercase = strtoupper(range('A', 'Z'));
    $lowercase = range('a', 'z');
    $numbers   = range('0', '9');
    $symbols   = ['!', '@', '#', '$', '%', '&'];

    // Combine all sets into a single pool
    $allChars = array_merge($uppercase, $lowercase, $numbers, $symbols);

    if (empty($allChars)) {
        throw new RuntimeException('Unable to generate password: character set is empty');
    }

    // Generate cryptographically secure random bytes
    // 1 byte = 8 bits. We need enough bytes to cover the length.
    $bytes = random_bytes((int) ceil($length / 8));

    // Convert binary data into a string using base64 encoding
    $randomString = substr(base64_encode($bytes), 0, $length);

    return $randomString;
}

This approach avoids the complexity of manually shuffling arrays or calculating indices from random integers. By converting raw bytes directly to a base64 string and truncating them, we ensure that every character in the resulting password is derived from true randomness. The resulting string will contain a mix of uppercase, lowercase, numbers, and symbols depending on the probability distribution of base64 characters, which satisfies most standard password policies without needing complex logic to force specific character inclusion.

Handling Specific Character Requirements

Some legacy systems or strict security policies require that passwords must include at least one uppercase letter, one number, and one symbol. The random_bytes approach does not guarantee this distribution because base64 characters are fixed (A-Z, a-z, 0-9, +, /). If you must enforce character types, you need a two-step process:

  1. Generate a pool of random bytes.
  2. Shuffle the allowed character arrays using random_int() to select specific indices.
function generatePasswordWithRequirements(int $length = 12): string {
    $uppercase = range('A', 'Z');
    $lowercase = range('a', 'z');
    $numbers   = range('0', '9');
    $symbols   = ['!', '@', '#', '$', '%'];

    // Ensure we have enough length to accommodate required characters
    if ($length < 4) {
        throw new InvalidArgumentException('Password must be at least 4 characters long to satisfy requirements.');
    }

    // Force inclusion of specific character types
    $requiredChars = [$uppercase[array_rand($uppercase)], 
                      $lowercase[array_rand($lowercase)], 
                      $numbers[array_rand($numbers)], 
                      $symbols[array_rand($symbols)]];

    $remainingLength = $length - count($requiredChars);

    if ($remainingLength <= 0) {
        throw new InvalidArgumentException('Password length is too short for required characters.');
    }

    // Generate random fillers
    $fillerPool = array_merge($uppercase, $lowercase, $numbers, $symbols);
    $fillers = [];
    
    while (count($fillers) < $remainingLength) {
        $fillers[] = $fillerPool[array_rand($fillerPool)];
    }

    // Combine and shuffle
    $allChars = array_merge($requiredChars, $fillers);
    shuffle($allChars); // Insecure for crypto, but acceptable here since we used random_int above
    
    // Better to use a Fisher-Yates shuffle or sort with random keys if strict entropy is needed on the final mix
    // However, given the small sample size of required chars, simple shuffle is usually acceptable in practice.
    
    return implode('', array_slice($allChars, 0, $length));
}

Note that using shuffle() or array_rand() relies on random_int() for its randomness source in modern PHP versions, making it safe for this specific use case.

Trade-offs and Considerations

Using random_bytes adds a slight performance overhead compared to rand(), but this is negligible in the context of application startup or user session creation where passwords are generated once per request. The primary trade-off lies in character set selection. Base64 encoding produces an alphabet of 64 characters. If your policy requires symbols like [ or {, you must explicitly include them in your generation logic rather than relying on the base64 output, as those characters do not appear in the standard base64 alphabet.

Always verify your PHP version supports random_bytes(). If you are maintaining legacy code on PHP 5.x, consider using the extension mcrypt or openssl_random_pseudo_bytes(), though these are deprecated and should be migrated away from immediately.

For developers working within the Laravel ecosystem, checking out https://laravelcompany.com can provide additional insights into secure implementation patterns and best practices for authentication systems.

Our network