PHP rand() vs. random_int()

2020-05-31 05:07发布

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?

标签: php php-7
4条回答
冷血范
2楼-- · 2020-05-31 05:49

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楼-- · 2020-05-31 05:50

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楼-- · 2020-05-31 05:52

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."

and for rand()

*This function does not generate cryptographically secure values" *

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:

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.


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

查看更多
Luminary・发光体
5楼-- · 2020-05-31 05:57

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.

查看更多
登录 后发表回答