Another replacement for rand() using OpenSSL.
Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.
A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.
<?php
function crypto_rand_secure($min, $max) {
$range = $max - $min;
if ($range == 0) return $min; $log = log($range, 2);
$bytes = (int) ($log / 8) + 1; $bits = (int) $log + 1; $filter = (int) (1 << $bits) - 1; do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
$rnd = $rnd & $filter; } while ($rnd >= $range);
return $min + $rnd;
}
?>