If you can't see obvious patterns, that does not make it cryptographically secure! See also my answer to this question on our sibling site: What does it mean for a random number generator to be cryptographically secure?
At the risk of stating the obvious, rand()
and mt_rand()
are NOT SECURE for security purposes. Do NOT use them for things like shuffling a deck of virtual cards in games where there is (virtual) money at stake, generating security tokens, or any such thing. Such random functions are meant for fast randomness where security does not matter. Common applications for insecure randomness are simulations and games (the game AI repeating itself in 1 out of every 2 billion games is fine, but a secret key repeating itself 1 in every 2 billion keys can be crackable in a reasonable amount of time).
By coincidence I was looking at this 2 hours ago as well, since I was curious if they had finally aliased rand()
to use mt_rand()
instead, since mt_rand
has been both faster and better since its introduction many years ago, but this does not appear to be the case. Therefore:
- To generate insecure, fast random:
$n = mt_rand(0, 10);
generates a number from 0 through 10 (inclusive) (docs) - To generate secure random data:
$data = random_bytes(32);
generates 32 bytes of random data (docs) - To generate a secure random number:
$n = random_int(0, 10);
generates a number from 0 through 10 (inclusive) (docs)
Note that this only goes up toPHP_INT_MAX
, which is at most approximately 264, so too small as a security key by itself. Userandom_bytes()
for generating secret keys, security tokens, etc. This function may aid in generating an unpredictable number, like for shuffling a deck of cards, where you may need a random number ≤52 instead of random bytes.