请知悉:本文最近一次更新为 6年 前,文中内容可能已经过时。

区别于mt_rand函数,利用/dev/urandom生成随机数是依靠设备本身生成的,函数如下:

function GetURandom($min = 0, $max = 0x7FFFFFFF){
$diff = $max - $min;
if ($diff > PHP_INT_MAX) {
throw new RuntimeException('Bad Range');
}
$fh = fopen('/dev/urandom', 'r');
stream_set_read_buffer($fh, PHP_INT_SIZE);
$bytes = fread($fh, PHP_INT_SIZE );
if ($bytes === false || strlen($bytes) != PHP_INT_SIZE ) {
return 0;
}
fclose($fh);
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);
}

如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《PHP 使用/dev/urandom 随机数生成函数》相关的博文:


发布时间 10/24/2017 10:27:50栏目 Software.标签 .

留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌