I’m trying to create a function using mt_rand() in order to generate a truly random number, since rand() just isn’t suffice.
The problem is I need to pre-define the length of the number, say I need a 10 digit random number.
Anyway, I’ve been messing around and this is what I’ve come up with:
function randomNumber($length) {
$min = str_repeat(0, $length-1) . 1;
$max = str_repeat(9, $length);
return mt_rand($min, $max);
}
In theory that should work (as far as I can tell), but it doesn’t. The length is completely random and it also throws out negative values.
Any ideas?
If by “a truly random number” you mean a cryptographically secure random number, make sure to use
random_intinstead ofmt_rand.mt_randis not based on a CSPRNG. If you don’t know whether you need a CSPRNG, userandom_intanyway – it’s not slow.If you want an n-digit numeric string, that’s exactly what you should get: n individual digits.
The reason your existing code isn’t working is because
0000...01is still1tomt_rand, and also thatmt_rand‘s range isn’t infinite. The negative numbers are integer overflows.