区别于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);
}

Related Posts: PHP 使用/dev/urandom 随机数生成函数 :

留言

avatar