PHP

Generate Crypto-Strong Password

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generate a strong random password with configurable length and character sets. Uses rejection sampling to keep the distribution uniform across the chosen alphabet (no biased % alphabetLen).
PHP
Raw
<?php
function generatePassword(int $length = 20, array $sets = ['lower', 'upper', 'digits', 'symbols']): string {
    $alphabets = [
        'lower'   => 'abcdefghijklmnopqrstuvwxyz',
        'upper'   => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'digits'  => '0123456789',
        'symbols' => '!@#$%^&*()-_=+[]{};:,.<>?/~',
    ];
    $alpha = '';
    foreach ($sets as $s) $alpha .= $alphabets[$s] ?? '';
    if ($alpha === '' || $length < 1) throw new InvalidArgumentException('Bad input');

    $alphaLen = strlen($alpha);
    $limit    = intdiv(256, $alphaLen) * $alphaLen;
    $out      = '';
    while (strlen($out) < $length) {
        $b = ord(random_bytes(1));
        if ($b < $limit) $out .= $alpha[$b % $alphaLen];
    }
    return $out;
}

echo generatePassword(16);                                  // e.g. "X9k!nQ2pR&7vL@bW"
echo generatePassword(24, ['lower','upper','digits']);      // no symbols
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.