Random numbers
suggest changePHP has two generations of random number APIs:
- the classic functions:
rand(),mt_rand(),mt_srand(),shuffle(),str_shuffle(),array_rand(), plus the securerandom_int()andrandom_bytes()added in PHP 7 - the object-oriented
Randomextension added in PHP 8.2:Random\Randomizerwith pluggable engines (Secure,Mt19937,PcgOneseq128XslRr64,Xoshiro256StarStar)
The rule for picking one is simple. If the number protects anything (tokens, passwords, session ids, one-time codes, salts, keys), use random_int(), random_bytes() or a Randomizer with the default Secure engine. If you need a reproducible sequence (simulations, games, tests, procedural generation), use a Randomizer with a seeded engine. You no longer need rand() or mt_rand() in new code.
All examples were run with PHP 8.5. Where the output depends on a secure random source, your output will be different.
random_int() and random_bytes()
These two functions read from the operating system's cryptographically secure generator (getrandom() on Linux, BCryptGenRandom on Windows). They're the simplest correct choice:
<?php
// integer in an inclusive range [1, 6]
$die = random_int(1, 6);
echo "die: $die\n";
// 16 random bytes, shown as hex
$bytes = random_bytes(16);
echo strlen($bytes), " bytes: ", bin2hex($bytes), "\n";
// the full integer range works too
echo random_int(PHP_INT_MIN, PHP_INT_MAX), "\n";
Output (varies):
die: 3
16 bytes: 4ddd2a15c63292a63e55785b430000b5
-5214869970538773117
Both bounds of random_int() are inclusive, and every value in the range is equally likely: there is no modulo bias (see below).
Invalid arguments throw ValueError:
<?php
try {
random_int(10, 1);
} catch (ValueError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
try {
random_bytes(0);
} catch (ValueError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
Output:
ValueError: random_int(): Argument #1 ($min) must be less than or equal to argument #2 ($max)
ValueError: random_bytes(): Argument #1 ($length) must be greater than 0
If the OS can't provide randomness (extremely rare, e.g. a broken container without /dev/urandom), they throw Random\RandomException. Don't catch it to fall back to mt_rand(); let it fail.
The legacy functions: rand() and mt_rand()
mt_rand() uses the Mersenne Twister (MT19937) algorithm. Since PHP 7.1 rand() is an alias of mt_rand(), and both are seeded automatically. Calling mt_srand() with a fixed seed gives a repeatable sequence:
<?php
mt_srand(42);
echo mt_rand(), " ", mt_rand(1, 100), " ", rand(1, 100), "\n";
mt_srand(42);
echo mt_rand(), " ", mt_rand(1, 100), " ", rand(1, 100), "\n";
echo mt_getrandmax(), " ", getrandmax(), "\n";
Output:
804318771 68 77
804318771 68 77
2147483647 2147483647
Problems with these functions:
- They aren't secure. After seeing about 624 outputs an attacker can reconstruct the internal state and predict every future value. Even with fewer outputs, the 32-bit seed can be brute-forced. Never use
mt_rand(),rand(),uniqid()orlcg_value()for tokens or passwords. - The state is global.
mt_srand()affects all code in the request, including libraries that callshuffle(),str_shuffle()orarray_rand():
<?php
// mt_srand() also controls shuffle(), str_shuffle() and array_rand()
mt_srand(3);
$a = [1, 2, 3, 4, 5];
shuffle($a);
echo implode(' ', $a), " | ", str_shuffle('abcdef'), " | ", array_rand(['x' => 1, 'y' => 2, 'z' => 3]), "\n";
mt_srand(3);
$a = [1, 2, 3, 4, 5];
shuffle($a);
echo implode(' ', $a), " | ", str_shuffle('abcdef'), " | ", array_rand(['x' => 1, 'y' => 2, 'z' => 3]), "\n";
Output:
4 3 5 1 2 | dbcfae | y
4 3 5 1 2 | dbcfae | y
That is handy for a quick script but bad for a large application: one library seeding the generator for its tests changes the "random" behavior of everything else.
Some old variants are now deprecated: lcg_value() since PHP 8.4 (use Randomizer::getFloat()), and the biased MT_RAND_PHP mode of mt_srand() since PHP 8.3.
Random\Randomizer
Random\Randomizer wraps a random engine and offers higher-level methods on top of it. Without arguments it uses Random\Engine\Secure, the same CSPRNG as random_int():
<?php
$r = new Random\Randomizer();
var_dump($r->engine::class);
echo $r->getInt(1, 100), "\n";
Output (number varies):
string(20) "Random\Engine\Secure"
29
The main methods:
| Method | Returns |
|---|---|
getInt($min, $max) |
integer in [$min, $max], uniform |
nextInt() |
non-negative integer from the engine's raw output |
getFloat($min, $max, $boundary) |
uniform float (PHP 8.3) |
nextFloat() |
float in [0, 1) (PHP 8.3) |
getBytes($length) |
random binary string |
getBytesFromString($chars, $length) |
string of $length bytes picked from $chars (PHP 8.3) |
shuffleArray($array) |
shuffled copy of an array (keys are renumbered) |
shuffleBytes($string) |
shuffled copy of a string (byte-wise) |
pickArrayKeys($array, $num) |
$num distinct keys, in their original order |
Here they are with a seeded engine, so the output is reproducible:
<?php
use Random\Randomizer;
use Random\Engine\Xoshiro256StarStar;
$r = new Randomizer(new Xoshiro256StarStar(7));
echo $r->getInt(1, 6), "\n";
echo bin2hex($r->getBytes(8)), "\n";
$cards = ['A', 'K', 'Q', 'J', '10'];
echo implode(' ', $r->shuffleArray($cards)), "\n";
echo $r->shuffleBytes('abcdef'), "\n";
$colors = ['red' => 0xF00, 'green' => 0x0F0, 'blue' => 0x00F, 'black' => 0];
print_r($r->pickArrayKeys($colors, 2));
echo $r->getBytesFromString('0123456789', 6), "\n";
Output:
5
d22c484f963d5c47
Q K J A 10
ebdafc
Array
(
[0] => red
[1] => green
)
716905
Unlike shuffle(), shuffleArray() returns a new array and doesn't modify its argument. shuffleBytes() works on bytes, so it will break multi-byte UTF-8 characters, just like str_shuffle().
Engines
| Engine | Secure | Seedable | Notes |
|---|---|---|---|
Random\Engine\Secure |
yes | no | default; OS CSPRNG |
Random\Engine\Xoshiro256StarStar |
no | yes | fast, high quality; good default for seeded use |
Random\Engine\PcgOneseq128XslRr64 |
no | yes | PCG64, also high quality |
Random\Engine\Mt19937 |
no | yes | compatible with mt_srand() / mt_rand() |
A seeded engine always produces the same sequence for the same seed:
<?php
use Random\Randomizer;
use Random\Engine\Mt19937;
use Random\Engine\PcgOneseq128XslRr64;
use Random\Engine\Xoshiro256StarStar;
$r = new Randomizer(new Xoshiro256StarStar(1234));
echo $r->getInt(1, 100), " ", $r->getInt(1, 100), " ", $r->getInt(1, 100), "\n";
$r = new Randomizer(new Xoshiro256StarStar(1234));
echo $r->getInt(1, 100), " ", $r->getInt(1, 100), " ", $r->getInt(1, 100), "\n";
$r = new Randomizer(new PcgOneseq128XslRr64(1234));
echo $r->getInt(1, 100), "\n";
// Mt19937 with the same seed matches mt_srand()/mt_rand()
$r = new Randomizer(new Mt19937(42));
mt_srand(42);
var_dump($r->getInt(1, 100) === mt_rand(1, 100));
Output:
60 7 30
60 7 30
85
bool(true)
The Mt19937 compatibility makes migrating old seeded code easy: replace mt_srand($seed) + mt_rand($a, $b) with a Randomizer(new Mt19937($seed)) and getInt($a, $b) and you get identical numbers, but without the global state.
Each Randomizer owns its engine, so two randomizers never interfere with each other, and nothing you do with them affects mt_rand() or shuffle().
Seeds, saved state and independent streams
Xoshiro256StarStar and PcgOneseq128XslRr64 accept either an integer or a binary string seed (32 and 16 bytes respectively). To derive a seed from a name, such as a level name or a test id, hash it. Engines and randomizers can be serialized to save their exact position in the sequence, and jump() creates a stream that won't overlap with the original:
<?php
use Random\Randomizer;
use Random\Engine\Xoshiro256StarStar;
// seed from any string: hash it to the 32 bytes the engine wants
$seed = hash('sha256', 'level-7', binary: true);
$r = new Randomizer(new Xoshiro256StarStar($seed));
echo $r->getInt(1, 1000), " ", $r->getInt(1, 1000), "\n";
// save the generator state ...
$r->getInt(1, 1000);
$saved = serialize($r);
$next = [$r->getInt(1, 1000), $r->getInt(1, 1000)];
// ... and resume from it later
$restored = unserialize($saved);
var_dump($next === [$restored->getInt(1, 1000), $restored->getInt(1, 1000)]);
// jump() skips ahead 2^128 steps: independent streams from one seed
$a = new Xoshiro256StarStar(5);
$b = clone $a;
$b->jump();
echo bin2hex($a->generate()), " ", bin2hex($b->generate()), "\n";
Output:
621 830
bool(true)
69cf54ca7851d549 038cac77ef8f3c29
Saving state is useful for things like a game save file or resuming a long simulation exactly where it stopped. Only unserialize data you created yourself (see Security Issues with unserialize).
Random floats
The old idiom mt_rand() / mt_getrandmax() produces only about 2^31 distinct values and can return exactly 1.0. Use nextFloat() for [0, 1) and getFloat() for any range. The third argument of getFloat() is a Random\IntervalBoundary that says whether each end is included:
<?php
use Random\Randomizer;
use Random\IntervalBoundary;
use Random\Engine\Xoshiro256StarStar;
$r = new Randomizer(new Xoshiro256StarStar(7));
// [0, 1)
printf("%.6f\n", $r->nextFloat());
// [1.5, 2.5) by default
printf("%.6f\n", $r->getFloat(1.5, 2.5));
// closed interval [0, 1]
printf("%.6f\n", $r->getFloat(0, 1, IntervalBoundary::ClosedClosed));
// open interval (0, 1): never exactly 0, safe for log()
printf("%.6f\n", log($r->getFloat(0, 1, IntervalBoundary::OpenOpen)));
Output:
0.700576
1.969928
0.442958
-0.339875
The four boundary cases are ClosedOpen (the default), ClosedClosed, OpenClosed and OpenOpen.
Recipes
Secure tokens
For API keys, password reset links, CSRF tokens and "remember me" cookies, generate random bytes and encode them as text. 16 bytes (128 bits) is the minimum, 32 bytes is a comfortable default:
<?php
// URL-safe token: 32 bytes = 256 bits of entropy
function token(int $bytes = 32): string
{
return rtrim(strtr(base64_encode(random_bytes($bytes)), '+/', '-_'), '=');
}
$hex = bin2hex(random_bytes(16)); // 32 hex chars, 128 bits
$url = token(); // 43 chars, 256 bits
echo $hex, "\n", $url, "\n";
echo strlen($hex), " ", strlen($url), "\n";
Output (tokens vary):
c600e24e3caedeff07b6cc379d9b405b
6ao7_6yMo_gyIo1pLrj_4rSQ3q_tBEqTJxzgEIaFoTY
32 43
When you store such tokens in a database, store a hash (hash('sha256', $token)) instead of the token itself and compare with hash_equals(). See Secure Remember Me for a complete example, and Bytes and binary data for more on encoding raw bytes.
Random passwords and codes from an alphabet
getBytesFromString() picks each byte uniformly from the given string, which is exactly what a password generator needs. Leaving out look-alike characters (l, 1, O, 0) makes passwords easier to type:
<?php
function generatePassword(int $length = 16): string
{
$alphabet = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_';
return (new Random\Randomizer())->getBytesFromString($alphabet, $length);
}
echo generatePassword(), "\n";
echo generatePassword(24), "\n";
// a 6-digit one-time code, leading zeros kept
$code = (new Random\Randomizer())->getBytesFromString('0123456789', 6);
echo $code, "\n";
// same idea with random_int and padding
echo str_pad((string) random_int(0, 999_999), 6, '0', STR_PAD_LEFT), "\n";
Output (varies):
usY#r!^xzFi&8ezM
8fF6V7AS45azJ$3PatPaZf#s
213339
493842
The alphabet is treated as bytes, so use only ASCII characters in it. str_shuffle() is a common but wrong way to do this: it uses the non-secure global Mersenne Twister and never repeats a character.
To store user passwords, see Password Hashing Functions. You don't need to generate salts yourself; password_hash() does it.
UUID version 4
A v4 UUID is 122 random bits plus fixed version and variant bits:
<?php
function uuidv4(): string
{
$b = random_bytes(16);
$b[6] = chr((ord($b[6]) & 0x0F) | 0x40); // version 4
$b[8] = chr((ord($b[8]) & 0x3F) | 0x80); // variant 10xx
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}
$id = uuidv4();
echo $id, "\n";
var_dump((bool) preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $id));
Output (UUID varies):
081bd18f-3448-4f69-aa7f-3735c2a403f6
bool(true)
If you use UUIDs as database primary keys, consider time-ordered v7 UUIDs instead (the symfony/uid and ramsey/uuid packages implement both). Don't use uniqid() as a unique id or a token: it's derived from the current time in microseconds and is easy to guess.
Picking random elements
pickArrayKeys() returns distinct keys in their original order, so shuffle the result if the order matters:
<?php
use Random\Randomizer;
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
$r = new Randomizer();
// one random element
$one = $fruits[$r->pickArrayKeys($fruits, 1)[0]];
echo $one, "\n";
// three distinct elements, in random order
$three = array_map(fn($k) => $fruits[$k], $r->shuffleArray($r->pickArrayKeys($fruits, 3)));
echo implode(', ', $three), "\n";
try {
$r->pickArrayKeys($fruits, 10);
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
Output (elements vary):
elderberry
banana, cherry, date
Random\Randomizer::pickArrayKeys(): Argument #2 ($num) must be between 1 and the number of elements in argument #1 ($array)
Weighted random choice
To pick items with different probabilities, draw a number in [1, total weight] and walk the list subtracting weights:
<?php
use Random\Randomizer;
use Random\Engine\Xoshiro256StarStar;
/**
* @param array<string, int> $weights item => weight (positive integers)
*/
function weightedPick(array $weights, Randomizer $r = new Randomizer()): string
{
$total = array_sum($weights);
$n = $r->getInt(1, $total);
foreach ($weights as $item => $weight) {
$n -= $weight;
if ($n <= 0) {
return $item;
}
}
throw new LogicException('unreachable');
}
$loot = ['common' => 70, 'rare' => 25, 'legendary' => 5];
$r = new Randomizer(new Xoshiro256StarStar(2024));
$counts = array_fill_keys(array_keys($loot), 0);
for ($i = 0; $i < 100_000; $i++) {
$counts[weightedPick($loot, $r)]++;
}
print_r($counts);
Output:
Array
(
[common] => 70257
[rare] => 24836
[legendary] => 4907
)
This is O(n) per pick, which is fine for short lists. For thousands of items and many picks, precompute cumulative weights and binary-search them.
Testable code: inject the Randomizer
Code that calls random_int() directly can't be tested deterministically. Accept a Randomizer instead, default to the secure one, and pass a seeded one in tests:
<?php
use Random\Randomizer;
use Random\Engine\Xoshiro256StarStar;
final class Dice
{
public function __construct(private Randomizer $random = new Randomizer()) {}
public function roll(int $count, int $sides = 6): array
{
$rolls = [];
for ($i = 0; $i < $count; $i++) {
$rolls[] = $this->random->getInt(1, $sides);
}
return $rolls;
}
}
// production: secure engine, different every run
$dice = new Dice();
// test: fixed seed, same result every run
$dice = new Dice(new Randomizer(new Xoshiro256StarStar(99)));
echo implode(' ', $dice->roll(5)), "\n";
$dice = new Dice(new Randomizer(new Xoshiro256StarStar(99)));
echo implode(' ', $dice->roll(5)), "\n";
Output:
1 1 4 5 5
1 1 4 5 5
Randomizer is final, so you can't mock it, but you can write your own engine. An engine is any class implementing Random\Engine, whose single method generate() returns a binary string of random bytes. An engine that replays fixed values lets a test force specific outcomes:
<?php
use Random\Engine;
use Random\Randomizer;
// An engine that replays fixed 64-bit values: handy in unit tests
final class FixedSequence implements Engine
{
private int $i = 0;
public function __construct(private array $values) {}
public function generate(): string
{
$v = $this->values[$this->i++ % count($this->values)];
return pack('P', $v); // 8 bytes, little endian
}
}
$r = new Randomizer(new FixedSequence([0, 1, 2]));
echo $r->getInt(0, 9), $r->getInt(0, 9), $r->getInt(0, 9), "\n";
Output:
012
How the randomizer maps raw engine output to a range is an implementation detail, so assert on behavior ("the first player wins when the die shows 1") rather than hard-coding long expected sequences that might change between PHP versions. See Unit testing for testing in general.
Pitfall: modulo bias
Reducing a random value with % makes some results more likely than others when the range doesn't divide evenly into the source range. A byte has 256 values, and 256 = 6 × 42 + 4, so faces 0-3 get 43 chances each and faces 4-5 get only 42:
<?php
// random_bytes(1) % 6 is biased: 256 is not a multiple of 6
$counts = array_fill(0, 6, 0);
for ($i = 0; $i < 600_000; $i++) {
$counts[ord(random_bytes(1)) % 6]++;
}
foreach ($counts as $face => $n) {
printf("%d: %.2f%%\n", $face, $n / 6000);
}
Output (varies slightly):
0: 16.76%
1: 16.87%
2: 16.74%
3: 16.81%
4: 16.36%
5: 16.47%
Expected values are 16.80% for 0-3 and 16.41% for 4-5 instead of 16.67% each. The same problem appears with mt_rand() % $n and hexdec(bin2hex(...)) % $n. random_int(), getInt(), getBytesFromString() and pickArrayKeys() all use rejection sampling internally and are unbiased, so use them instead of doing the arithmetic yourself.
Summary
- For anything security-related use
random_int(),random_bytes()ornew Random\Randomizer()(secure engine by default). - For reproducible sequences use
new Randomizer(new Xoshiro256StarStar($seed)); useMt19937only when you must match oldmt_rand()output. - Avoid
rand(),mt_rand(),mt_srand(),shuffle(),str_shuffle()andarray_rand()in new code: they share global, predictable state.lcg_value()andMT_RAND_PHPare deprecated, anduniqid()isn't random. - Use
getFloat()/nextFloat()for floats,getBytesFromString()for passwords and codes, andpickArrayKeys()/shuffleArray()for arrays. - Never reduce random values with
%yourself; let the library do unbiased range reduction. - Inject a
Randomizerinto classes that need randomness so tests can pass a seeded or custom engine.