Skip to content

Instantly share code, notes, and snippets.

@pyrou
Created August 25, 2017 08:14
Show Gist options
  • Save pyrou/58bc57b6810f4080627cb24238762fc8 to your computer and use it in GitHub Desktop.
Save pyrou/58bc57b6810f4080627cb24238762fc8 to your computer and use it in GitHub Desktop.
Generate a random number without uses of deterministic rand / mt_rand php function
<?php
/**
* Generate a random number without uses of deterministic rand / mt_rand php function
* based on https://codeascraft.com/2012/07/19/better-random-numbers-in-php-using-devurandom
* - Add 64 bit support
* - Removed mcrypt dependency (PHP7 required)
*/
function devurandom_rand($min = 0, $max = PHP_INT_MAX) {
$diff = $max - $min;
if ($diff < 0 || $diff > PHP_INT_MAX) {
throw new RuntimeException("Bad range");
}
// get some random bytes from /dev/urandom
$bytes = random_bytes(PHP_INT_SIZE);
if ($bytes === false || strlen($bytes) != PHP_INT_SIZE) {
throw new RuntimeException("Unable to get ".PHP_INT_SIZE." bytes");
}
if (PHP_INT_SIZE == 8) { // 64-bit versions
list($higher, $lower) = array_values(unpack('N2', $bytes));
$value = $higher << 32 | $lower;
}
else { // 32-bit versions
list($value) = array_values(unpack('Nint', $bytes));
}
$val = $value & PHP_INT_MAX;
$fp = (float)$val / PHP_INT_MAX; // convert to [0,1]
return (int)(round($fp * $diff) + $min);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment