-->

PHP rand() vs. random_int()

2020-05-31 05:37发布

问题:

As php.net indicates: random_int() function Generates cryptographically secure pseudo-random integers.

But, Can someone explain whats the difference between rand() & random_int()? Can I use random_int() instead of rand() when only requiring a random integer? Which one is faster?

回答1:

Revisiting the question and seeing there's been an answer given, I find it's only fair that I submit my comments to an answer, seeing they were submitted before.

The manual on PHP 7's random_int() function states:

"Returns a cryptographically secure random integer in the range min to max, inclusive."

  • http://php.net/manual/en/function.random-int.php

and for rand()

*This function does not generate cryptographically secure values" *

  • http://php.net/manual/en/function.rand.php

OP's comment:

"@Fred-ii- thank you. But what does "cryptographically secure pseudo-random" mean? – NDFA"

That can be found in the following links as per my findings:

  • https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator

Which states:

A cryptographically secure pseudo-random number generator (CSPRNG) or cryptographic pseudo-random number generator (CPRNG)[1] is a pseudo-random number generator (PRNG) with properties that make it suitable for use in cryptography.


  • How does a cryptographically secure random number generator work?

In regards to performance, you will need to run a benchmark yourself.



回答2:

As of PHP 7.1, rand() is basically an alias for mt_rand(). The newer random_int() is the slowest, but only secure method of the three.

<?php

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += rand(0, 32767);
}
printf('[rand] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += mt_rand(0, 32767);
}
printf('[mt_rand] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

$start = microtime(true);
$sum = 0.0;
for ($i = 0; $i < 10000000; $i++) {
    $sum += random_int(0, 32767);
}
printf('[random_int] Time: %.3f s%s', microtime(true) - $start, PHP_EOL);

Results:

[rand] Time: 10.973 s
[mt_rand] Time: 9.628 s
[random_int] Time: 23.069 s


回答3:

As most number generators, using rand() is not secure because it does not generate cryptographically secure values and the output of rand() is predictable.

PHP 7.0 introduces random_bytes and random_int as core functions which are free from the problems that most of random number generators have.



回答4:

I have not personally encountered any problems using random_int but it should be used with try/catch as it throws an exception if it was not possible to gather sufficient entropy.



标签: php php-7