PHP example

How to generate a random string in PHP

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

On PHP 8.3 and later, use (new Random\Randomizer())->getBytesFromString($alphabet, $length): it picks each character from your alphabet with a cryptographically secure generator. On older PHP, loop $length times and append $alphabet[random_int(0, $max)]. For a token where the characters don't matter, bin2hex(random_bytes(16)) gives 32 hex characters (128 bits). Don't use rand(), mt_rand(), str_shuffle() or uniqid() for anything that must not be guessed.

Random strings in PHP are usually tokens: password-reset links, API keys, invite codes, file names, IDs. For all of those the string must be unpredictable, and the most-copied answers online (str_shuffle, mt_rand, uniqid, md5(time())) are not. The sections below cover the PHP 8.3 Randomizer method, the random_int loop for older versions, hex and URL-safe tokens from random_bytes, a v4 UUID, why the old tricks are predictable, and seeded strings for tests, then a table to pick from. The secure examples print a new string on every run, so they also print checks (length, characters) you can rely on. Each example runs on this page: hit Run, then edit the code and run it again.

1Randomizer::getBytesFromString (PHP 8.3+)Recommended

PHP 8.2 added the Random\Randomizer class, and PHP 8.3 gave it getBytesFromString($string, $length), which returns $length characters, each picked from $string with every character equally likely. Created without an argument, the randomizer uses the Random\Engine\Secure engine, the same cryptographically secure source as random_bytes. The alphabet is yours to choose: letters and digits, digits only for a numeric code, or a set without characters people confuse when they type a code by hand.

randomizer.php
<?php

// PHP 8.3+: no engine argument means the secure engine
$randomizer = new Random\Randomizer();

$alnum = 'abcdefghijklmnopqrstuvwxyz'
    . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

$token = $randomizer->getBytesFromString($alnum, 22);
echo $token, "\n";
echo 'length: ', strlen($token), "\n";
echo 'alphanumeric: ',
    preg_match('/^[a-zA-Z0-9]{22}$/', $token) ? 'yes' : 'no', "\n";
printf("strength: %.1f bits\n", 22 * log(strlen($alnum), 2));

// Any alphabet works: a 6-digit code, or no look-alike characters
$pin = $randomizer->getBytesFromString('0123456789', 6);
echo $pin, ' ', ctype_digit($pin) ? 'digits only' : 'not digits', "\n";

$noLookAlikes = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O, 1/I
$readable = $randomizer->getBytesFromString($noLookAlikes, 8);
echo $readable, ' ',
    preg_match('/[01OI]/', $readable) ? 'has look-alikes' : 'clean', "\n";

echo get_class($randomizer->engine), "\n";

Output

The token changes on every run, so check the lines under it: length: 22, alphanumeric: yes and strength: 131.0 bits. With 62 possible characters each one carries about 5.95 bits, so 22 characters are a little more than the 128 bits usually asked of a secret token; 16 characters give about 95. The PIN line is six digits and the readable code never contains 0, O, 1 or I. The last line, Random\Engine\Secure, confirms the default engine. An empty alphabet or a length of 0 throws a ValueError.

2A random_int loop (PHP 7.0+)

If your server runs PHP 8.2 or older, build the string yourself. random_int (PHP 7.0) returns a cryptographically secure integer in a range, and every value in the range is equally likely, so using it as an index into the alphabet gives each character the same chance. Avoid the variant that takes random_bytes and applies % strlen($alphabet): unless the alphabet size divides 256, some characters come up more often than others. The function below runs unchanged from PHP 7.0 to 8.5.

random_int_loop.php
<?php

const ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
    . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Works on PHP 7.0 and later: random_int is cryptographically secure
function randomString(int $length, string $alphabet = ALNUM): string
{
    if ($length < 1 || $alphabet === '') {
        throw new InvalidArgumentException('length and alphabet required');
    }
    $max = strlen($alphabet) - 1;
    $result = '';
    for ($i = 0; $i < $length; $i++) {
        $result .= $alphabet[random_int(0, $max)];
    }
    return $result;
}

$id = randomString(16);
echo $id, "\n";
echo 'length: ', strlen($id), "\n";
echo 'alphanumeric: ', ctype_alnum($id) ? 'yes' : 'no', "\n";

$hexish = randomString(10, 'abcdef0123456789');
echo $hexish, ' ', ctype_xdigit($hexish) ? 'hex' : 'not hex', "\n";

// Every character of the alphabet comes up about equally often
$counts = count_chars(randomString(60000, 'abc'), 1);
foreach ($counts as $byte => $n) {
    printf("%s: %s\n", chr($byte), $n > 19000 && $n < 21000 ? '~1/3' : $n);
}

Output

The 16-character ID passes ctype_alnum (alphanumeric: yes), and the custom alphabet produces a string that ctype_xdigit accepts as hex. The last three lines count 60,000 characters drawn from abc: each letter lands near 20,000 (~1/3), which is the even spread you want. On PHP 5, random_int does not exist; the paragonie/random_compat package adds it.

3Hex and URL-safe tokens from random_bytes

When nobody reads or types the string, skip the alphabet and encode raw bytes. random_bytes(16) returns 16 secure bytes (128 bits). bin2hex turns them into 32 characters from 0-9a-f, the classic token for reset links and API keys. Base64 is shorter, but its +, / and = need escaping in a URL; the base64url variant swaps the first two for - and _ and drops the padding, which is what rtrim(strtr(base64_encode($b), '+/', '-_'), '=') does.

tokens.php
<?php

function base64url(string $bytes): string
{
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

$bytes = random_bytes(16); // 16 bytes = 128 bits

$hex = bin2hex($bytes);
echo $hex, "\n";
echo 'hex: ', strlen($hex), ' chars, ',
    preg_match('/^[0-9a-f]{32}$/', $hex) ? '0-9a-f only' : 'other', "\n";

$url = base64url($bytes);
echo $url, "\n";
echo 'base64url: ', strlen($url), ' chars, ',
    preg_match('/^[A-Za-z0-9_-]{22}$/', $url) ? 'URL-safe' : 'other', "\n";

// Same bits, both decode back to the original bytes
var_dump(hex2bin($hex) === $bytes);
var_dump(base64_decode(strtr($url, '-_', '+/')) === $bytes);

// sodium has the same encoding built in
var_dump(sodium_bin2base64(
    $bytes,
    SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING,
) === $url);

// 32 bytes = 256 bits
$long = random_bytes(32);
echo strlen(bin2hex($long)), ' hex chars, ',
    strlen(base64url($long)), ' base64url chars', "\n";

Output

The same 128 bits come out as hex: 32 chars or base64url: 22 chars; hex spends 4 bits per character and base64url 6. Both decode back to the original bytes (the first two bool(true) lines), and sodium_bin2base64 with SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING gives the identical string, so use that if you prefer a built-in. For 256 bits, random_bytes(32) gives 64 hex chars, 43 base64url chars.

4A v4 UUID from random_bytes

PHP has no built-in UUID function, so either install a library (ramsey/uuid with Uuid::uuid4(), or symfony/uid with Uuid::v4()) or write the dozen lines yourself. A version 4 UUID is 16 random bytes with six bits fixed: the high four bits of byte 6 hold the version (0100) and the high two bits of byte 8 hold the variant (10), as RFC 9562 (which replaced RFC 4122) defines. That leaves 122 random bits, formatted as hex in groups of 8, 4, 4, 4 and 12. The regular expression checks the format, including the 4 and the variant digit.

uuid_v4.php
<?php

function uuidV4(): string
{
    $bytes = random_bytes(16);
    // Version 4: the high 4 bits of byte 6 become 0100
    $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
    // Variant (RFC 9562): the high 2 bits of byte 8 become 10
    $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}

const UUID_V4 = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}'
    . '-[0-9a-f]{12}$/';

$uuid = uuidV4();
echo $uuid, "\n";
echo 'length: ', strlen($uuid), "\n";
echo 'valid v4: ', preg_match(UUID_V4, $uuid) ? 'yes' : 'no', "\n";
echo 'version digit: ', $uuid[14], "\n";

// 1,000 more: all valid, none repeated
$many = [];
for ($i = 0; $i < 1000; $i++) {
    $many[] = uuidV4();
}
$valid = count(preg_grep(UUID_V4, $many));
echo "valid: $valid, unique: ", count(array_unique($many)), "\n";

// The check rejects other versions and junk
foreach (['550e8400-e29b-11d4-a716-446655440000', 'not-a-uuid'] as $s) {
    echo $s, ' -> ', preg_match(UUID_V4, $s) ? 'v4' : 'not v4', "\n";
}

Output

Every run prints a different UUID, but always length: 36, valid v4: yes and version digit: 4 at index 14. The batch of a thousand comes back as valid: 1000, unique: 1000. The check rejects 550e8400-e29b-11d4-... because its version digit is 1 (a time-based UUID). To accept any version, replace 4[0-9a-f]{3} with [0-9a-f]{4}. If you need UUIDs that sort by creation time, for example as database keys, both libraries also generate version 7.

5Why not rand, mt_rand, str_shuffle or uniqid

The top answers on older threads build tokens from rand(), mt_rand(), str_shuffle(), uniqid() or md5(time()). They produce strings that look random, but none of them is meant for secrets. mt_rand is a Mersenne Twister: fast and fine for games or sampling, but its output can be predicted once its seed or enough outputs are known, and rand() and str_shuffle() use the same generator. uniqid and time() are clocks. The script shows each problem.

not_secure.php
<?php

// mt_rand, rand and str_shuffle share one seeded generator
mt_srand(42);
echo mt_rand(), ' ', rand(), ' ', str_shuffle('abcdefgh'), "\n";
mt_srand(42);
echo mt_rand(), ' ', rand(), ' ', str_shuffle('abcdefgh'), "\n";

// str_shuffle never repeats a character, so fewer strings are possible
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$s = substr(str_shuffle($chars), 0, 10);
echo 'distinct chars: ', count(array_unique(str_split($s))), " of 10\n";

// uniqid is the current time in hex, not a random value
$a = uniqid();
$b = uniqid();
echo $a, ' ', $b, "\n";
echo 'same first 8 chars: ',
    substr($a, 0, 8) === substr($b, 0, 8) ? 'yes' : 'no', "\n";
echo 'first 8 chars = Unix time: ',
    abs(hexdec(substr($a, 0, 8)) - time()) <= 1 ? 'yes' : 'no', "\n";

// md5(time()) looks random, but anyone can try the last minute
$token = md5((string) time());
$found = null;
for ($t = time(); $t > time() - 60; $t--) {
    if (md5((string) $t) === $token) {
        $found = $t;
        break;
    }
}
echo 'md5(time()) token guessed: ', $found !== null ? 'yes' : 'no', "\n";

Output

After mt_srand(42), both lines read 804318771 1710563033 bdchgafe: the same seed replays the same mt_rand, rand and str_shuffle results, and an attacker who recovers the seed or the generator state can do the same. The popular substr(str_shuffle($chars), 0, 10) always gives distinct chars: 10 of 10, because shuffling never repeats a character. The two uniqid() values (13 hex characters each) share their first 8 characters, which are the Unix time in seconds, and the rest is microseconds, so the two differ only at the end. uniqid('', true) appends a few more digits from a non-secure generator, which does not change that. Finally, a md5(time()) token is found by hashing the last 60 timestamps.

6Reproducible strings for tests (seeded engine)

Sometimes you want the opposite: the same "random" strings on every run, for test fixtures, sample data or a bug you need to replay. random_int and random_bytes can't be seeded, and mt_srand changes global state for the whole script. Instead, pass the code a Randomizer: production gives it the default secure one, and a test gives it one built on a seeded engine such as Random\Engine\Mt19937 (PHP 8.2). Because the output here does not change, it is printed in full.

seeded.php
<?php

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';

// Take the Randomizer as a parameter instead of creating it inside
function makeCode(Random\Randomizer $random, int $length = 12): string
{
    return $random->getBytesFromString(ALPHABET, $length);
}

// In a test: a seeded engine gives the same strings on every run
$seeded = new Random\Randomizer(new Random\Engine\Mt19937(42));
echo makeCode($seeded), "\n";
echo makeCode($seeded), "\n";
echo makeCode($seeded, 6), "\n";

// Same seed, same sequence; another seed, another sequence
$again = new Random\Randomizer(new Random\Engine\Mt19937(42));
var_dump(makeCode($again) === '275l2d8ov9hu');
$other = new Random\Randomizer(new Random\Engine\Mt19937(7));
echo makeCode($other), "\n";

// In production: the default secure engine
$code = makeCode(new Random\Randomizer());
echo 'production code length: ', strlen($code), "\n";

Output

Seed 42 always starts with 275l2d8ov9hu, then bzulywy8sbwx and kr4okv, so a test can assert on exact values; a new randomizer with the same seed starts over (bool(true)), and seed 7 gives itezchrdwtqx. The same makeCode with new Random\Randomizer() is secure and different every time; only its length is fixed. Never let a seeded engine reach code that creates real tokens.

7Which should you use?

MethodSecureOutputBest for
$randomizer->getBytesFromString()YesAny alphabet, any lengthMost code on PHP 8.3+
$alphabet[random_int(0, $max)]YesAny alphabet, any lengthPHP 7.0 to 8.2
bin2hex(random_bytes(16))Yes32 hex chars, 128 bitsTokens, API keys, file names
base64url(random_bytes(16))Yes22 URL-safe chars, 128 bitsShort tokens in URLs
uuidV4()Yes36-char UUID, 122 bitsIDs where a UUID is expected
new Mt19937($seed)No, by designSame strings every runTests and fixtures
mt_rand, rand, str_shuffleNoPredictable from the seedAvoid for tokens
uniqid(), md5(time())NoBased on the clockAvoid for tokens

Frequently asked questions

How do I generate a random alphanumeric string in PHP?

On PHP 8.3 and later: (new Random\Randomizer())->getBytesFromString('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 16). On PHP 7.0 to 8.2, loop $length times and append $alphabet[random_int(0, strlen($alphabet) - 1)]. Both are cryptographically secure and give every character the same chance.

Is uniqid() unique and random?

Neither, in the way most people mean. uniqid() returns 13 hex characters made from the current time: 8 for the seconds and 5 for the microseconds, so two values made close together share most of their characters and anyone who knows roughly when it was made can guess it. uniqid('', true) adds more characters from a non-secure generator. Use bin2hex(random_bytes(16)) when the value must be hard to guess.

Does PHP have a built-in UUID function?

No. Install ramsey/uuid (Uuid::uuid4()) or symfony/uid (Uuid::v4()), or build a v4 UUID from random_bytes(16): set the high bits of byte 6 to 0100 and of byte 8 to 10, then format the hex as 8-4-4-4-12. Both libraries also generate time-ordered version 7 UUIDs, which work better as database keys.

Are rand() and mt_rand() secure enough for tokens?

No. Since PHP 7.1, rand() is an alias of mt_rand(), a Mersenne Twister that is fast but predictable: the same seed gives the same sequence, and its state can be recovered from enough outputs. str_shuffle() and array_rand() use the same generator. For anything secret use random_int, random_bytes or a Random\Randomizer with the default engine.

How long should a random token be?

Aim for at least 128 random bits. That is random_bytes(16), which is 32 hex characters or 22 base64url characters, or 22 characters drawn from 62 letters and digits (about 131 bits). Guessing such a token is not feasible, and collisions between tokens you generate are vanishingly unlikely.

How do I make sure a random string is unique?

With 128 bits of randomness a duplicate is so unlikely that you can treat each token as unique, but if you store tokens, put a UNIQUE index on the column anyway and generate a new one if an insert fails on a duplicate key. Do not try to get uniqueness from the clock (uniqid, time()): that makes the value easier to guess without making it unique across servers.

What does random_int or random_bytes throw?

A ValueError for bad arguments, such as random_int(5, 1): random_int(): Argument #1 ($min) must be less than or equal to argument #2 ($max). If the system has no usable source of randomness they throw a Random\RandomException (PHP 8.2 and later; a plain Exception before). The second case almost never happens on a normal server, so let it propagate rather than fall back to mt_rand.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground