random_bytes
: random_bytes
and random_int
.
random_bytes
function returns a string and takes as input parameters an int
that defines the length (in bytes) of the return value:
$bytes = random_bytes(10); var_dump(bin2hex($bytes)); //possible ouput: string(20) "7dfab0af960d359388e6"
random_int
returns an integer in the specified range:
var_dump(random_int(1, 100)); //possible output: 27
CryptGenRandom();
arc4random_buf()
will be enabled (true for BSD-derived systems or systems with libbsd
).getrandom(2)
will be used in Linux./dev/urandom
as the final attempt. $times = 1000000; $result = []; for ($i=0; $i < $times; $i++) { $dieRoll = array(6 => 0); //initializes just the six counting to zero $dieRoll[roll()] += 1; //first die $dieRoll[roll()] += 1; //second die $dieRoll[roll()] += 1; //third die $result[$dieRoll[6]] += 1; //counts the sixes } function roll() { return random_int(1,6); } var_dump($result);
random_int
and a simple rand
will random_int
following results:
Sixes | Expected Result | random_int | rand |
---|---|---|---|
0 | 579,000 | 579430 | 578179 |
one | 347,000 | 346927 | 347620 |
2 | 69000 | 68985 | 69586 |
3 | 5000 | 4658 | 4615 |
rand
and random_int
we construct a graph of results using the formula: PHP
-
/ sqrt( )
.
random_int
over rand
.
openssl_random_pseudo_bytes()
, mcrypt_create_iv()
or using /dev/random
directly or /dev/urandom
with fread()
. There are also libraries such as RandomLib or libsodium .
random_compat
library from Paragon Initiative Enterprises. It allows using random_bytes()
and random_int()
in PHP 5.x projects.
composer require paragonie/random_compat
require 'vendor/autoload.php'; $string = random_bytes(32); var_dump(bin2hex($string)); // string(64) "8757a27ce421b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2aaec6f" $int = random_int(0,255); var_dump($int); // int(81)
random_compat
uses slightly different priorities:
fread()
/dev/urandom
if availablemcrypt_create_iv($bytes, MCRYPT_CREATE_IV)
COM('CAPICOM.Utilities.1')->GetRandom()
openssl_random_pseudo_bytes()
$passwordChar = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $passwordLength = 8; $max = strlen($passwordChar) - 1; $password = ''; for ($i = 0; $i < $passwordLength; ++$i) { $password .= $passwordChar[random_int(0, $max)]; } echo $password; //possible output: 7rgG8GHu
random_compat
pseudo-random number generators, and random_compat
is a good solution for this.
random_int
and random_bytes
.
Source: https://habr.com/ru/post/272509/